3.1 数据质量分析
脏数据包括:缺失值;异常值;不一致的值;重复数据及含有特殊符号的数据;
1.缺失值处理
统计缺失率,缺失数
2.异常值处理
(1)简单统计量分析
(2)3Q原则
正态分布情况下,小概率事件为异常值
不服从正太分布的,可以用原离平均值多少倍标准差来分析
(3)箱线图分析
使用describe()描述
import pandas as pd
catering_sale='catering_sale.xls'
data=pd.read_excel(catering_sale,index_col=u'日期')
print data
des=data.describe()
print des
import pandas as pd
from matplotlib.font_manager import FontProperties
catering_sale='catering_sale.xls'
data=pd.read_excel(catering_sale,index_col=u'日期')
import matplotlib.pyplot as plt
print plt
myfont = FontProperties(fname='/usr/share/fonts/wqy-zenhei/wqy-zenhei.ttc')
plt.rcParams['axes.unicode_minus']=False
plt.figure()
p=data.boxplot(return_type = 'dict')
x = p['fliers'][0].get_xdata() # 'flies'即为异常值的标签
y = p['fliers'][0].get_ydata()
y.sort()
for i in range(len(x)):
if i>0:
plt.annotate(y[i],xy=(x[i],y[i]),xytext=(x[i]+0.05-0.8/(y[i]-y[i-1]),y[i]))
else:
plt.annotate(y[i],xy=(x[i],y[i]),xytext=(x[i]+0.08,y[i]))
plt.savefig("/home/python/syy/images/pic1.png")
运行结果:
报错1.x = p[‘fliers’][0].get_xdata() # ‘flies’即为异常值的标签 y =
p[‘fliers’][0].get_ydata() 解决: p=data.boxplot(return_type = ‘dict’)
from __future__ import print_function
import pandas as pd
catering_sale = 'catering_sale.xls' #餐饮数据
data = pd.read_excel(catering_sale, index_col = u'日期') #读取数据,指定“日期”列为索引列
data = data[(data[u'销量'] > 400)&(data[u'销量'] < 5000)] #过滤异常数据
statistics = data.describe() #保存基本统计量
statistics.loc['range'] = statistics.loc['max']-statistics.loc['min'] #极差
statistics.loc['var'] = statistics.loc['std']/statistics.loc['mean'] #变异系数
statistics.loc['dis'] = statistics.loc['75%']-statistics.loc['25%'] #四分位数间距
print(statistics)
运行结果:
销量
count 195.000000
mean 2744.595385
std 424.739407
min 865.000000
25% 2460.600000
50% 2655.900000
75% 3023.200000
max 4065.200000
range 3200.200000
var 0.154755
dis 562.600000
分析
from __future__ import print_function
import pandas as pd
#初始化参数
from matplotlib.font_manager import FontProperties
myfont = FontProperties(fname='/usr/share/fonts/wqy-zenhei/wqy-zenhei.ttc')
dish_profit = 'catering_dish_profit.xls' #餐饮菜品盈利数据
data = pd.read_excel(dish_profit, index_col = u'菜品名')
data = data[u'盈利'].copy()
#data=data.sort(ascending=False)
import matplotlib.pyplot as plt #导入图像库
plt.rcParams['axes.unicode_minus'] = False #用来正常显示负号
plt.figure()
data.plot(kind='bar')
plt.ylabel(u'盈利(元)',fontproperties=myfont)
p = 1.0*data.cumsum()/data.sum()
p.plot(color = 'r', secondary_y = True, style = '-o',linewidth = 2)
plt.annotate(format(p[6], '.4%'), xy = (6, p[6]), xytext=(6*0.9, p[6]*0.9), arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"),fontproperties=myfont) #添加注释,即85%处的标记。这里包括了指定箭头样式。
plt.ylabel(u'盈利(比例)',fontproperties=myfont)
plt.savefig("/home/python/syy/images/pic2.png")
from __future__ import print_function
import pandas as pd
catering_sale = 'catering_sale.xls' #餐饮数据
data = pd.read_excel(catering_sale, index_col = u'日期') #读取数据,指定“日期”列为索引列
data = data[(data[u'销量'] > 400)&(data[u'销量'] < 5000)] #过滤异常数据
statistics = data.describe() #保存基本统计量
statistics.loc['range'] = statistics.loc['max']-statistics.loc['min'] #极差
statistics.loc['var'] = statistics.loc['std']/statistics.loc['mean'] #变异系数
statistics.loc['dis'] = statistics.loc['75%']-statistics.loc['25%'] #四分位数间距
print(statistics)
运行结果:
百合酱蒸凤爪 1.000000
翡翠蒸香茜饺 0.009206
金银蒜汁蒸排骨 0.016799
乐膳真味鸡 0.455638
蜜汁焗餐包 0.098085
生炒菜心 0.308496
铁板酸菜豆腐 0.204898
香煎韭菜饺 0.127448
香煎罗卜糕 -0.090276
原汁原味菜心 0.428316
Name: 百合酱蒸凤爪, dtype: float64
3.3 主要数据探索函数
1.Pandas常用函数总结
数据清理
数据处理:Filter 、Sort 和 GroupBy
数据合并、数据统计
2.拓展统计特征函数
累计统计特征函数
代码:
import pandas as pd
D=pd.Series(range(0,20))
print "D is:\n",D
print "D 前N项和是:\n",D.cumsum()
print "D 依次相邻两项求和:\n",pd.rolling_sum(D,2)
运行结果:
D is:
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
11 11
12 12
13 13
14 14
15 15
16 16
17 17
18 18
19 19
dtype: int64
D 前N项和是:
0 0
1 1
2 3
3 6
4 10
5 15
6 21
7 28
8 36
9 45
10 55
11 66
12 78
13 91
14 105
15 120
16 136
17 153
18 171
19 190
dtype: int64
0 NaN
1 1.0
2 3.0
3 5.0
4 7.0
5 9.0
6 11.0
7 13.0
8 15.0
9 17.0
10 19.0
11 21.0
12 23.0
13 25.0
14 27.0
15 29.0
16 31.0
17 33.0
18 35.0
19 37.0
dtype: float64
3.统计作图函数
盒图:表示多个样本的均值
误差条形图:同时显示上限误差和下限误差
最小二乘拟合曲线图:分析变量之间关系
python 主要作图函数:
plot ():绘制线性二维图,折线图
pie(): 绘制饼图
hist(): 绘制二维条形直方图
boxplot(): 绘制箱型图 Pandas
plot(logy=True) :绘制y轴的对数图形 Pandas
plot(yerr=error) :绘制误差条形图 Pandas
1.plot()参数
DataFrame.plot(x=None, y=None, kind=’line’, ax=None, subplots=False,
sharex=None, sharey=False, layout=None, figsize=None, use_index=True,
title=None, grid=None, legend=True, style=None, logx=False,
logy=False, loglog=False, xticks=None, yticks=None, xlim=None,
ylim=None, rot=None, fontsize=None, colormap=None, table=False,
yerr=None, xerr=None, secondary_y=False, sort_columns=False, **kwds)
详见:http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html
2.绘图
import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(0,2*np.pi,50)
y=np.sin(x)
plt.plot(x,y,'bp--')
plt.savefig("/home/python/syy/images/pic3.png")
3.饼图
代码:
labels='Frogs','Hogs','Dogs','Logs'
sizes=[15,30,45,10]
colors=['yellowgreen','gold','lightskyblue','lightcoral']
explode=(0,0.1,0,0)
plt.pie(sizes,explode=explode,labels=labels,colors=colors,
autopct='%1.1f%%',shadow=True,startangle=90)
plt.axis('equal')
plt.savefig("/home/python/syy/images/pic4.png")
4.二维条形直方图
代码:
x=np.random.randn(1000)
plt.hist(x,10)
plt.savefig("/home/python/syy/images/pic5.png")
x=np.random.randn(1000)
D=pd.DataFrame([x,x+1]).T
D.plot(kind='box')
plt.savefig("/home/python/syy/images/pic6.png")
6.对数图形
代码:
import numpy as np
from matplotlib.font_manager import FontProperties
import pandas as pd
import matplotlib.pyplot as plt
myfont = FontProperties(fname='/usr/share/fonts/wqy-zenhei/wqy-zenhei.ttc')
#plt.rcParams['font.sans-serif']=['WenQuanYi Micro Hei']
plt.rcParams['axes.unicode_minus']=False
x=pd.Series(np.exp(np.arange(20)))
x.plot(legend=True,label='原始数据图')
plt.ylabel(u'原始数据图',fontproperties=myfont)
plt.savefig("/home/python/syy/images/pic7.png")
x.plot(logy=True,legend=True,label='对数数据图')
plt.ylabel(u'对数数据图',fontproperties=myfont)
plt.savefig("/home/python/syy/images/pic8.png")
8.误差条形图
代码:
error=np.random.randn(10)
y=pd.Series(np.sin(np.arange(10)))
y.plot(yerr=error)
plt.savefig('/home/python/syy/images/pic10.png')