python+matplotlib+web.py

时间:2023-03-08 19:31:12

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

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

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

 # -*- coding: utf-8 -*-
"""
Created on Wed Apr 19 17:26:53 2017 @author: touristlee TO:Don't worry,be happy!
""" import pandas as pd
import numpy as np
import matplotlib.pylab as plt
import matplotlib.patches as mpatches #数据下载地址https://pan.baidu.com/s/1nuOSo7B
#本案例采用的数据集为user.zip,包含了一个大规模数据集raw_user.csv(包含2000万条记录),
#和一个小数据集small_user.csv(只包含30万条记录)。
#小数据集small_user.csv是从大规模数据集raw_user.csv中抽取的一小部分数据。
#之所以抽取出一少部分记录单独构成一个小数据集,是因为,在第一遍跑通整个实验流程时,
#会遇到各种错误,各种问题,先用小数据集测试,可以大量节约程序运行时间。
#等到第一次完整实验流程都顺利跑通以后,就可以最后用大规模数据集进行最后的测试。
#user_id(用户id)
#item_id(商品id)
#behaviour_type(包括浏览、收藏、加购物车、购买,对应取值分别是1、2、3、4)
#user_geohash(用户地理位置哈希值,有些记录中没有这个字段值,所以后面我们做数据预处理时把这个字段全部删除,用随机生成的省份代替)
#item_category(商品分类)
#time(该记录产生时间) #读取数据
df = pd.read_csv('small_user.csv',encoding='utf-8')
#随机生成一个省份列表
def get_province(x):
youlist = []
for i in x:
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'澳门']
youlist.append(maplist[i])
return youlist
#切割字符串
def format_time(x):
return str(x).split(' ')[0]
#格式化
df = df[['user_id','item_id','behavior_type','item_category','time']]
df['province'] = get_province(np.random.randint(0,33,len(df)))
df['time'] = df['time'].map(format_time)
df.columns=['uid','itemid','behavior','itemcagegory','time','province']
df['time']=df['time'].astype('datetime64')
print df.dtypes #查询
#查询有多少条数据
print df.count()
#查询有多少用户
print df.drop_duplicates(['uid']).count()
#查询有多少不重复的数据
print df.drop_duplicates().count() #条件查询
#查询2014年12月10日到2014年12月13日有多少人浏览了商品
print df[('2014-12-13'>=df['time']) & (df['time'] >= '2014-12-10') & (df['behavior']==1)].head()
#每天网站卖出去的商品的个数
df2=df.drop_duplicates()
print df2[df2['behavior']==4].groupby('time').itemcagegory.count()
#取给定时间和给定地点,求当天发出到该地点的货物的数量
print df[(df['time']=='2014-12-12') & (df['province']==u'山西') & (df['behavior']==4)].itemcagegory.count() #根据用户行为分析
#查询一件商品在某天的购买比例或浏览比例
print df[df['time']=='2014-12-11'].itemcagegory.count()
print df[(df['time']=='2014-12-11') & (df['behavior']==4)].itemcagegory.count()
print float(df[(df['time']=='2014-12-11') & (df['behavior']==4)].itemcagegory.count())/float(df[df['time']=='2014-12-11'].itemcagegory.count()) ##查询某个用户在某一天点击网站占该天所有点击行为的比例(点击行为包括浏览,加入购物车,收藏,购买)
print df[(df['uid']==10001082) & (df['time']=='2014-12-12')].behavior.count()
print float(df[(df['uid']==10001082) & (df['time']=='2014-12-12')].behavior.count())/float(df[df['time']=='2014-12-12'].behavior.count()) #用户实时查询分析
#各个地区浏览网站的访问次数 df2=df[df['behavior']==1]
df2=df2.drop_duplicates('uid')
print df2.groupby('province').uid.count() #可视化
#分析各省份消费者对商品的行为(浏览)
fig=plt.figure(figsize=(8,4))
ax1=fig.add_subplot(111)
plt.title(u'behavior by province')
plt.xlabel('province')
plt.ylabel('count')
df2=df[df['behavior']==1]
df2=df2.groupby('province').uid.count()
df2.plot(kind='bar')
#分析消费者对商品的行为 df3=df[['behavior']]
df3=df3.groupby('behavior').behavior.count()
fig2=plt.figure(figsize=(8,4))
ax2=fig2.add_subplot(111)
plt.title(u'behavior')
plt.xlabel('behavior')
plt.ylabel('count')
df3.plot(kind='bar') ##分析被购买最多的商品是哪一类 TOP10
df4=df[['behavior','itemcagegory']]
df4=df4[df4['behavior']==4]
df4=df4.groupby('itemcagegory').itemcagegory.count()
df5=df4.sort_values(ascending=False).head(10)
fig3=plt.figure(figsize=(8,4))
ax3=fig3.add_subplot(1,1,1)
colors=['red','blue','yellow','green','white','black','magenta','cyan','yellowgreen','lightcoral']
ax3.scatter(df5.index,df5.values,c=colors)
plt.xlabel('var')
plt.ylabel('freq')
plt.title('TOP10 category')
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.)
plt.show() ##分析每年的那个月份购买商品的量最多
#先增加一列 月份
df6=df[df['behavior']==4]
df7=df6.copy()
df7['month']=np.array([i.month for i in df7['time']])
df7=df7[['behavior','month']]
df7=df7.groupby('month').count()
df7.plot(kind='bar') ##分析每年的每个月份的行为习惯
df7=df.copy()
df7['month']=np.array([i.month for i in df7['time']])
df7=df7[['behavior','month']]
tmp=df7.groupby(['month','behavior']).behavior.count()
tmp.plot(kind='bar',color=['red','blue','green','yellow']) #分析各省份消费者对商品的行为(收藏)
#分析国内哪个省份的消费者最有购买欲望 即收藏
df8=df[df['behavior']==3]
df8=df8.drop_duplicates('uid')
tmp8=df8.groupby('province').uid.count()
fig8=plt.figure(figsize=(8,4))
ax8=fig.add_subplot(111)
plt.title(u'behavior by province')
plt.xlabel('province')
plt.ylabel('count')
tmp8.plot(kind='bar')

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

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

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

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