商品零售购物篮分析
#8-1 import numpy as np import pandas as pd inputfile="D:\数据分析\GoodsOrder.csv" data=pd.read_csv(inputfile,encoding = 'gbk') data.info() data=data['id'] description=[data.count(),data.min(),data.max()] description=pd.DataFrame(description,index=['Count','Min','Max']).T print('描述性统计结果:\n',np.round(description))
#8-2 import pandas as pd inputfile="D:\数据分析\GoodsOrder.csv" data=pd.read_csv(inputfile,encoding='gbk') group=data.groupby(['Goods']).count().reset_index() sorted=group.sort_values('id',ascending=False) print('销量排行前10商品的销量:\n',sorted[:10]) import matplotlib.pyplot as plt x=sorted[:10]['Goods'] y=sorted[:10]['id'] plt.figure(figsize=(8,4)) plt.barh(x,y) plt.rcParams['font.sans-serif']='SimHei' plt.xlabel('销量') plt.ylabel('商品类别') plt.title('学号3108商品的销量TOP10') plt.savefig("D:/数据分析/top10.png") plt.show() data_nums=data.shape[0] for index,row in sorted[:10].iterrows(): print(row['Goods'],row['id'],row['id']/data_nums)
#8-3 import pandas as pd inputfile1="D:\数据分析\GoodsOrder.csv" inputfile2 ="D:\数据分析\GoodsTypes.csv" data= pd.read_csv(inputfile1,encoding='gbk') types = pd.read_csv(inputfile2,encoding='gbk') group = data.groupby(['Goods']).count().reset_index() sort = group.sort_values( 'id',ascending=False).reset_index() datanums=data.shape[0] del sort['index'] sort_links= pd.merge(sort,types) sort_link = sort_links.groupby(['Types']).sum().reset_index() sort_link = sort_link.sort_values('id',ascending=False).reset_index() del sort_link['index'] sort_link['count'] = sort_link.apply(lambda line: line['id']/data_nums,axis=1) sort_link.rename(columns={'count':'percent'},inplace=True) print('各类别商品的销量及其占比:\n',sort_link) outfile1='D:/数据分析/percent.csv' sort_link.to_csv(outfile1,index=False,header=True,encoding='gbk') import matplotlib.pyplot as plt data = sort_link['percent'] labels = sort_link['Types'] plt.figure(figsize=(8,6)) plt.pie(data,labels=labels,autopct='%1.2f%%') plt.rcParams['font.sans-serif'] = 'SimHei' plt.title('学号3108每类商品销量占比') plt.savefig('D:/数据分析/persent.png') plt.show()
#8-4 selected= sort_links.loc[sort_links['Types'] =='非酒精饮料'] child_nums= selected['id'].sum() selected['child_percent'] = selected.apply(lambda line: line['id']/child_nums,axis=1) selected.rename(columns={'id':'count'},inplace=True) print('非酒精饮料内部商品的销量及其占比:\n',selected) outfile2='D:/数据分析/child percent.csv' sort_link.to_csv(outfile2,index=False,header=True,encoding='gbk') import matplotlib.pyplot as plt data = selected['child_percent'] labels = selected['Goods'] plt.figure(figsize=(8,6)) explode = (0.02,0.03,0.04,0.05,0.06,0.07,0.08,0.08,0.3,0.1,0.3) plt.pie(data,explode=explode,labels=labels,autopct='%1.2f%%',pctdistance=1.1,labeldistance=1.2) plt.rcParams['font.sans-serif'] ='SimHei' plt.title('学号3108非酒精饮料内部各商品的销量占比') plt.axis('equal') plt.savefig('D:/数据分析/child_persent.png') plt.show()