python+matplotlib+web.py

最近看了厦门大学数据库实验室林子雨老师的《大数据课程实验案例:网站用户行为分析》,可视化这块是用的R语言,我决定用Python来实现一下。

参考文献 http://dblab.xmu.edu.cn/post/7499/

数据来源 http://pan.baidu.com/s/1nuOSo7B

  1 # -*- coding: utf-8 -*-
  2 """
  3 Created on Wed Apr 19 17:26:53 2017
  4 
  5 @author: touristlee
  6 
  7 TO:Don't worry,be happy!
  8 """
  9 
 10 import pandas as pd
 11 import numpy as np
 12 import matplotlib.pylab as plt
 13 import matplotlib.patches as mpatches
 14 
 15 #数据下载地址https://pan.baidu.com/s/1nuOSo7B
 16 #本案例采用的数据集为user.zip,包含了一个大规模数据集raw_user.csv(包含2000万条记录),
 17 #和一个小数据集small_user.csv(只包含30万条记录)。
 18 #小数据集small_user.csv是从大规模数据集raw_user.csv中抽取的一小部分数据。
 19 #之所以抽取出一少部分记录单独构成一个小数据集,是因为,在第一遍跑通整个实验流程时,
 20 #会遇到各种错误,各种问题,先用小数据集测试,可以大量节约程序运行时间。
 21 #等到第一次完整实验流程都顺利跑通以后,就可以最后用大规模数据集进行最后的测试。
 22 #user_id(用户id)
 23 #item_id(商品id)
 24 #behaviour_type(包括浏览、收藏、加购物车、购买,对应取值分别是1、2、3、4)
 25 #user_geohash(用户地理位置哈希值,有些记录中没有这个字段值,所以后面我们做数据预处理时把这个字段全部删除,用随机生成的省份代替)
 26 #item_category(商品分类)
 27 #time(该记录产生时间)
 28 
 29 
 30 #读取数据
 31 df = pd.read_csv('small_user.csv',encoding='utf-8')
 32 #随机生成一个省份列表
 33 def get_province(x):
 34     youlist = []
 35     for i in x:
 36         maplist = [u'北京',u'天津',u'上海',u'重庆',u'河北',u'山西',u'辽宁',u'吉林',u'黑龙江',u'江苏',u'浙江',u'安徽',u'福建',u'江西',u'山东',u'河南',u'湖北',u'湖南',u'广东',u'海南',u'四川',u'贵州',u'云南',u'陕西',u'甘肃',u'青海',u'台湾',u'内蒙古',u'广西',u'西藏',u'宁夏',u'新疆',u'香港',u'澳门']  
 37         youlist.append(maplist[i])
 38     return youlist
 39 #切割字符串
 40 def format_time(x):
 41     return str(x).split(' ')[0]
 42 #格式化
 43 df = df[['user_id','item_id','behavior_type','item_category','time']]
 44 df['province'] = get_province(np.random.randint(0,33,len(df)))
 45 df['time'] = df['time'].map(format_time)
 46 df.columns=['uid','itemid','behavior','itemcagegory','time','province']
 47 df['time']=df['time'].astype('datetime64')
 48 print df.dtypes
 49 
 50 #查询
 51 #查询有多少条数据
 52 print df.count()
 53 #查询有多少用户
 54 print df.drop_duplicates(['uid']).count()
 55 #查询有多少不重复的数据
 56 print df.drop_duplicates().count()
 57 
 58 #条件查询
 59 #查询2014年12月10日到2014年12月13日有多少人浏览了商品
 60 print df[('2014-12-13'>=df['time']) & (df['time'] >= '2014-12-10') & (df['behavior']==1)].head()
 61 #每天网站卖出去的商品的个数
 62 df2=df.drop_duplicates()
 63 print df2[df2['behavior']==4].groupby('time').itemcagegory.count()
 64 #取给定时间和给定地点,求当天发出到该地点的货物的数量
 65 print df[(df['time']=='2014-12-12') & (df['province']==u'山西') & (df['behavior']==4)].itemcagegory.count()
 66 
 67 
 68 
 69 #根据用户行为分析
 70 #查询一件商品在某天的购买比例或浏览比例
 71 print df[df['time']=='2014-12-11'].itemcagegory.count()
 72 print df[(df['time']=='2014-12-11') & (df['behavior']==4)].itemcagegory.count()
 73 print float(df[(df['time']=='2014-12-11') & (df['behavior']==4)].itemcagegory.count())/float(df[df['time']=='2014-12-11'].itemcagegory.count())
 74 
 75 
 76 
 77 ##查询某个用户在某一天点击网站占该天所有点击行为的比例(点击行为包括浏览,加入购物车,收藏,购买)
 78 print df[(df['uid']==10001082) & (df['time']=='2014-12-12')].behavior.count()
 79 print float(df[(df['uid']==10001082) & (df['time']=='2014-12-12')].behavior.count())/float(df[df['time']=='2014-12-12'].behavior.count())
 80 
 81 #用户实时查询分析
 82 #各个地区浏览网站的访问次数
 83 
 84 df2=df[df['behavior']==1]
 85 df2=df2.drop_duplicates('uid')
 86 print df2.groupby('province').uid.count()
 87 
 88 
 89 
 90 #可视化
 91 #分析各省份消费者对商品的行为(浏览)
 92 fig=plt.figure(figsize=(8,4))
 93 ax1=fig.add_subplot(111)
 94 plt.title(u'behavior by province')
 95 plt.xlabel('province')
 96 plt.ylabel('count')
 97 df2=df[df['behavior']==1]
 98 df2=df2.groupby('province').uid.count()
 99 df2.plot(kind='bar')
100 #分析消费者对商品的行为
101 
102 df3=df[['behavior']]
103 df3=df3.groupby('behavior').behavior.count()
104 fig2=plt.figure(figsize=(8,4))
105 ax2=fig2.add_subplot(111)
106 plt.title(u'behavior')
107 plt.xlabel('behavior')
108 plt.ylabel('count')
109 df3.plot(kind='bar')
110 
111 ##分析被购买最多的商品是哪一类 TOP10
112 df4=df[['behavior','itemcagegory']]
113 df4=df4[df4['behavior']==4]
114 df4=df4.groupby('itemcagegory').itemcagegory.count()
115 df5=df4.sort_values(ascending=False).head(10)
116 fig3=plt.figure(figsize=(8,4))
117 ax3=fig3.add_subplot(1,1,1)
118 colors=['red','blue','yellow','green','white','black','magenta','cyan','yellowgreen','lightcoral']
119 ax3.scatter(df5.index,df5.values,c=colors)
120 plt.xlabel('var')
121 plt.ylabel('freq')
122 plt.title('TOP10 category')
123 plt.legend(handles=[mpatches.Patch(color=x, label=y,joinstyle='round') for (x,y) in zip(colors,df5.index)],bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
124 plt.show()
125 
126 ##分析每年的那个月份购买商品的量最多
127 #先增加一列 月份
128 df6=df[df['behavior']==4]
129 df7=df6.copy()
130 df7['month']=np.array([i.month for i in df7['time']])
131 df7=df7[['behavior','month']]
132 df7=df7.groupby('month').count()
133 df7.plot(kind='bar')
134 
135 ##分析每年的每个月份的行为习惯
136 df7=df.copy()
137 df7['month']=np.array([i.month for i in df7['time']])
138 df7=df7[['behavior','month']]
139 tmp=df7.groupby(['month','behavior']).behavior.count()
140 tmp.plot(kind='bar',color=['red','blue','green','yellow'])
141 
142 
143 #分析各省份消费者对商品的行为(收藏)
144 #分析国内哪个省份的消费者最有购买欲望 即收藏
147 df8=df[df['behavior']==3]
148 df8=df8.drop_duplicates('uid')
149 tmp8=df8.groupby('province').uid.count()
150 fig8=plt.figure(figsize=(8,4))
151 ax8=fig.add_subplot(111)
152 plt.title(u'behavior by province')
153 plt.xlabel('province')
154 plt.ylabel('count')
155 tmp8.plot(kind='bar')

最后一个分析那个省份的消费者最有购买欲望的,原文用的是R语言的地图,matplotlib画地图很麻烦。

我想到的办法是用第三方模块来替代。首先想到的是百度的echarts了,这可以说是百度的良心产品了。

使用这个可以用Django或者web.py,这里我选择最简单的web.py。

代码我上传到了 https://github.com/touristlee/webpy.git

 

posted on 2017-07-20 19:00  touristlee  阅读(1615)  评论(0编辑  收藏  举报

导航