learnpy 2019-12-02
1。 将本地sql文件写入mysql数据库
本文写入的是python数据库的taob表
source [本地文件]
其中总数据为9616行,列分别为title,link,price,comment
2。使用python链接并读取数据
查看数据概括
#-*- coding:utf-8 -*- #author:M10 import numpy as np import pandas as pd import matplotlib.pylab as plt import mysql.connector conn = mysql.connector.connect(host='localhost', user='root', passwd='123456', db='python')#链接本地数据库 sql = 'select * from taob'#sql语句 data = pd.read_sql(sql,conn)#获取数据 print(data.describe())
说明数据的导入是正确的,简单的分析发现问题并不是这么简单,因为comment均值562可能偏大,最大评论数454037也可能出现错误,price价格为0也不太可能出现。
price comment count 9616.00000 9616.000000 mean 64.49324 562.239601 std 176.10901 6078.909643 min 0.00000 0.000000 25% 20.00000 16.000000 50% 36.00000 58.000000 75% 66.00000 205.000000 max 7940.00000 454037.000000
3。缺失值处理
将价格为0的值设置为中位数36
#-*- coding:utf-8 -*- #author:M10 import numpy as np import pandas as pd import matplotlib.pylab as plt import mysql.connector conn = mysql.connector.connect(host='localhost', user='root', passwd='123456', db='python')#链接本地数据库 sql = 'select * from taob'#sql语句 data = pd.read_sql(sql,conn)#获取数据 data['price'][data['price']==0]=None x = 0 for i in data.columns: for j in range(len(data)): if (data[i].isnull()) [j]: data[i][j]='36' x+=1 print(x) #44
结果显示修改了44行的数据。
4。异常值处理
#-*- coding:utf-8 -*- #author:M10 import numpy as np import pandas as pd import matplotlib.pylab as plt import mysql.connector conn = mysql.connector.connect(host='localhost', user='root', passwd='123456', db='python')#链接本地数据库 sql = 'select * from taob'#sql语句 data = pd.read_sql(sql,conn)#获取数据 #缺失值处理 data['price'][data['price']==0]=None x = 0 for i in data.columns: for j in range(len(data)): if (data[i].isnull()) [j]: data[i][j]='36' x+=1 print(x) #异常值处理 #绘制散点图,价格为横轴 data1 = data.T#转置 price = data1.values[2] comment = data1.values[3] plt.plot(price,comment,'o') plt.show() #print(price)
结果如下图,价格为0左右时comment很大可能为异常值,comments为0时,价格极大这个有可能的。
接下来处理评论数异常值,假设异常值分割线设置为20w,
#-*- coding:utf-8 -*- #author:M10 import numpy as np import pandas as pd import matplotlib.pylab as plt import mysql.connector conn = mysql.connector.connect(host='localhost', user='root', passwd='123456', db='python')#链接本地数据库 sql = 'select * from taob'#sql语句 data = pd.read_sql(sql,conn)#获取数据 #缺失值处理 data['price'][data['price']==0]=None x = 0 for i in data.columns: for j in range(len(data)): if (data[i].isnull()) [j]: data[i][j]='36' x+=1 print(x) #异常值处理 da = data.values#重新赋值data #异常值处理,将commments大于200000的数据comments设置为58 cont_clou = len(da)#获取行数 #遍历数据进行处理 for i in range(0,cont_clou): if(data.values[i][3]>200000): #print(data.values[i][3]) da[i][3]='58' #print(da[i][3]) #绘制散点图,价格为横轴 data1 = da.T#转置 price = data1[2] comment = data1[3] plt.plot(price,comment,'o') plt.xlabel('price') plt.ylabel('comments') plt.show()
处理后的输出结果为: