一、前言:
電商用戶畫像分析:用戶畫像是通過分析用戶的基礎(chǔ)信息、特征偏好、社會(huì)屬性等各維度的數(shù)據(jù),刻畫出用戶的信息全貌,它是建立在一系列屬性數(shù)據(jù)之上的目標(biāo)用戶模型。用戶畫像的本質(zhì)是一個(gè)用以描述用戶需求的工具。用戶畫像一般是產(chǎn)品設(shè)計(jì)、運(yùn)營人員從用戶群體中抽象出來的典型用戶,從中可以挖掘用戶價(jià)值,提供個(gè)性化推薦、精準(zhǔn)營銷等服務(wù)。
電商用戶畫像分析的作用:

二、理解數(shù)據(jù)與分析思路
1.導(dǎo)入使用的包:
#加上后可以直接在界面畫圖.
%matplotlib inline
#導(dǎo)入包
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# 減少繪圖產(chǎn)生的問題
matplotlib.rcParams['font.sans-serif'] = ['SimHei'] # 指定字體
matplotlib.rcParams['font.family']='sans-serif'
matplotlib.rcParams['axes.unicode_minus'] = False #解決負(fù)號(hào)'-'顯示為方塊的問題
# 導(dǎo)入數(shù)據(jù)庫包,從數(shù)據(jù)庫里讀取數(shù)據(jù)與存儲(chǔ)數(shù)據(jù)
import pymysql
pymysql.install_as_MySQLdb()
from sqlalchemy import create_engine
import gc #gc模塊可以回收內(nèi)存
import warnings
warnings.filterwarnings('ignore')#減少報(bào)錯(cuò)
from datetime import datetime
2.導(dǎo)入數(shù)據(jù):
#導(dǎo)入數(shù)據(jù)集
df = pd.read_excel('order_data.xlsx')
df_user = pd.read_excel('user_data.xlsx')
3.理解數(shù)據(jù):
df.head()

order_data共有五個(gè)字段,分別為,其中behavior_type中1為瀏覽,2為收藏,3為加購,4為購買
df_user.head()

4.分析維度:

三、數(shù)據(jù)預(yù)處理:
1.缺失值處理:


2.時(shí)間格式轉(zhuǎn)換:

3.制作用戶標(biāo)簽表:

四、分析過程:
1、用戶活躍的時(shí)間
1.1 用瀏覽活躍時(shí)間段
time_brows = df[df['behavior_type']==1].groupby(['user_id','hour']).agg({'item_id':'count'}).reset_index()
time_brows.rename(columns={'item_id':'hour_counts'},inplace=True)
#求出每個(gè)用戶最活躍的時(shí)間段
time_brows_max = time_brows.groupby('user_id').hour_counts.max().reset_index()
time_brows_max.rename(columns = {'hour_counts':'hour_counts_max'},inplace = True)
time_brows = pd.merge(time_brows,time_brows_max,how ='left',on = 'user_id')
#選取各用戶瀏覽次數(shù)最多的時(shí)段,如有并列最多的時(shí)段,用逗號(hào)連接
time_brows_hour = time_brows.loc[time_brows['hour_counts']==time_brows['hour_counts_max'],'hour'].groupby(time_brows['user_id']).aggregate(lambda x:','.join(x)).reset_index()
#將用戶瀏覽活躍時(shí)間段加入到用戶標(biāo)簽表中
labels = pd.merge(labels,time_brows_hour,how = 'left',on = 'user_id')
labels.rename(columns = {'hour':'time_browse'},inplace = True)
#查看標(biāo)簽表
labels.head()

1.2 用戶購買活躍時(shí)間段
time_buy = df[df['behavior_type'] == 4].groupby(['user_id','hour']).item_id.count().reset_index()
time_buy.rename(columns = {'item_id':'time_buy_count'},inplace = True)
time_buy_max = time_buy.groupby('user_id').time_buy_count.max().reset_index()
time_buy_max.rename(columns = {'time_buy_count':'time_buy_count_max'},inplace = True)
time_buy = pd.merge(time_buy,time_buy_max,how = 'left',on = 'user_id')
time_buy_hour = time_buy.loc[time_buy['time_buy_count'] == time_buy['time_buy_count_max'],'hour'].groupby(time_buy['user_id']).aggregate(lambda x:','.join(x)).reset_index()
labels = pd.merge(labels,time_buy_hour,how = 'left',on = 'user_id')
labels.rename(columns = {'hour':'buy_hour'},inplace = True)
#查看標(biāo)簽表
labels.head()

1.3 清除緩存:
del time_brows
del time_brows_max
del time_buy
del time_buy_max
del time_buy_hour
del time_brows_hour
gc.collect()
2、關(guān)于類目的用戶行為
# 先獲取各個(gè)需要的數(shù)據(jù)集
df_browse = df.loc[df['behavior_type']==1,['user_id','item_id','item_category']]
df_collect = df.loc[df['behavior_type']==2,['user_id','item_id','item_category']]
df_cart = df.loc[df['behavior_type']==3,['user_id','item_id','item_category']]
df_buy = df.loc[df['behavior_type']==4,['user_id','item_id','item_category']]
2.1 瀏覽最多的類目
#對用戶和類目進(jìn)行分組,統(tǒng)計(jì)瀏覽次數(shù)
df_browse_count = df_browse.groupby(['user_id','item_category']).item_id.count().reset_index()
df_browse_count.rename(columns = {'item_id':'item_category_counts'},inplace = True)
#按照用戶進(jìn)行分組,統(tǒng)計(jì)出每個(gè)用戶瀏覽最多的類目
df_browse_count_max = df_browse_count.groupby('user_id').item_category_counts.max().reset_index()
df_browse_count_max.rename(columns = {'item_category_counts':'item_category_counts_max'},inplace = True)
df_browse_count = pd.merge(df_browse_count,df_browse_count_max,how = 'left',on = 'user_id')
#將類目轉(zhuǎn)換成字符串格式,否則會(huì)報(bào)錯(cuò)
df_browse_count['item_category'] = df_browse_count['item_category'].astype(str)
#選取各用戶瀏覽次數(shù)最多的類目,如有并列最多的類目,用逗號(hào)連接
df_browse_count= df_browse_count.loc[df_browse_count['item_category_counts']==df_browse_count['item_category_counts_max'],'item_category'].groupby(df_browse_count['user_id']).aggregate(lambda x:','.join(x)).reset_index()
#將用戶瀏覽最多的類目加到標(biāo)簽表
labels = pd.merge(labels,df_browse_count,how = 'left',on = 'user_id')
labels.rename(columns = {'tiem_category':'cate_most_browse'},inplace = True)
labels.head()

2.2 收藏最多的類目
#按照用戶、類目進(jìn)行分組,統(tǒng)計(jì)收藏次數(shù)
df_collect_count = df_collect.groupby(['user_id','item_category']).item_id.count().reset_index()
df_collect_count.rename(columns = {'item_id':'item_category_count'},inplace = True)
#按照用戶分組,統(tǒng)計(jì)用戶收藏最多的類目和
df_collect_count_max = df_collect_count.groupby('user_id').item_category_count.max().reset_index()
df_collect_count_max.rename(columns = {'item_category_count':'item_category_count_max'},inplace = True)
df_collect_count = pd.merge(df_collect_count,df_collect_count_max,how = 'left',on ='user_id')
#將類目轉(zhuǎn)換成字符串格式,否則會(huì)報(bào)錯(cuò)
df_collect_count['item_category'] = df_collect_count['item_category'].astype(str)
#選取各用戶收藏次數(shù)最多的類目,如有并列最多的類目,用逗號(hào)連接
df_collect = df_collect_count.loc[df_collect_count['item_category_count']==df_collect_count['item_category_count_max'],'item_category'].groupby(df_collect_count['user_id']).aggregate(lambda x:','.join(x)).reset_index()
df_collect.rename(columns = {'item_category':'cate_most_collect'},inplace = True)
#將用戶收藏最多的類目加到標(biāo)簽表
labels = pd.merge(labels,df_collect,how ='left',on = 'user_id')
labels.head()

2.3 加購最多的類目
df_cart_count = df_cart.groupby(['user_id','item_category']).item_id.count().reset_index()
df_cart_count.rename(columns = {'item_id':'item_category_count'},inplace = True)
df_cart_count_max = df_cart_count.groupby('user_id').item_category_count.max().reset_index()
df_cart_count_max.rename(columns = {'item_category_count':'item_category_count_max'},inplace = True)
df_cart_count = pd.merge(df_cart_count,df_cart_count_max,how = 'left',on ='user_id')
df_cart_count['item_category'] = df_cart_count['item_category'].astype(str)
df_cart = df_cart_count.loc[df_cart_count['item_category_count']==df_cart_count['item_category_count_max'],'item_category'].groupby(df_cart_count['user_id']).aggregate(lambda x:','.join(x)).reset_index()
df_cart.rename(columns = {'item_category':'cate_most_cart'},inplace = True)
labels = pd.merge(labels,df_cart,how ='left',on = 'user_id')
labels.head()

2.4 購買最多的類目
df_buy_count = df_buy.groupby(['user_id','item_category']).item_id.count().reset_index()
df_buy_count.rename(columns = {'item_id':'item_category_count'},inplace = True)
df_buy_count_max = df_buy_count.groupby('user_id').item_category_count.max().reset_index()
df_buy_count_max.rename(columns = {'item_category_count':'item_category_count_max'},inplace = True)
df_buy_count = pd.merge(df_buy_count,df_buy_count_max,how ='left',on ='user_id')
df_buy_count['item_category'] = df_buy_count['item_category'].astype(str)
df_buy = df_buy_count.loc[df_buy_count['item_category_count']==df_buy_count['item_category_count_max'],'item_category'].groupby(df_buy_count['user_id']).aggregate(lambda x:','.join(x)).reset_index()
df_buy.rename(columns = {'item_category':'cate_most_buy'},inplace = True)
labels = pd.merge(labels,df_buy,how = 'left',on = 'user_id')
labels.head()

3、30天用戶行為
3.1 近30天購買次數(shù)
#將購買行為按用戶進(jìn)行分組,統(tǒng)計(jì)次數(shù)
df_count_30_buy = df[df['behavior_type'] == 4].groupby('user_id').item_id.count().reset_index()
labels = pd.merge(labels,df_count_30_buy,how = 'left',on = 'user_id')
labels.rename(columns = {'item_id':'count_30_buy'},inplace = True)
labels.head()
3.2 近30天加購次數(shù)
#將加購行為按用戶進(jìn)行分組,統(tǒng)計(jì)次數(shù)
df_count_30_cart = df[df['behavior_type'] == 3].groupby('user_id').item_id.count().reset_index()
labels = pd.merge(labels,df_count_30_cart,how = 'left',on = 'user_id')
labels.rename(columns = {'item_id':'count_30_cart'},inplace = True)
labels.head()
3.3 近30天活躍天數(shù)
#對用戶進(jìn)行分組,統(tǒng)計(jì)活躍的天數(shù),包括瀏覽、收藏、加購、購買
counts_30_active = df.groupby('user_id')['date'].nunique()
labels = pd.merge(labels,counts_30_active,how='left',on='user_id')
labels.rename(columns={'date':'count_30_active'},inplace=True)
labels.head()
4、7天用戶行為

本維度分析以2014/12/18作為最后一天去分析
4.1 近7天購買次數(shù)
df_near_7 = df[df['date']>datetime.strptime('2014-12-11','%Y-%m-%d')]
df_near_7_buy = df_near_7[df_near_7['behavior_type'] == 4].groupby('user_id').item_id.count().reset_index()
df_near_7_buy.rename(columns = {'item_id':'count_7_buy'},inplace = True)
labels = pd.merge(labels,df_near_7_buy,how = 'left',on = 'user_id')
labels.head()
4.2 近7天加購次數(shù)
df_near_7_cart = df_near_7[df_near_7['behavior_type'] == 3].groupby('user_id').item_id.count().reset_index()
df_near_7_cart.rename(columns = {'item_id':'count_7_cart'},inplace = True)
labels = pd.merge(labels,df_near_7_cart,how = 'left',on = 'user_id')
labels.head()
4.3 近7天活躍次數(shù)
counts_7_active = df_near_7.groupby('user_id')['date'].nunique()
labels = pd.merge(labels,counts_7_active,how='left',on='user_id')
labels.rename(columns={'date':'count_7_active'},inplace=True)
labels.head()
5.最后一次行為距今天數(shù)(今天取2014/12/18)
5.1 上次瀏覽距今天數(shù)
#5.1 上次瀏覽距今天數(shù)
day_browes = df[df['behavior_type']== 1].groupby('user_id').date.max().apply(lambda x:(datetime.strptime('2014-12-19','%Y-%m-%d')-x).days)
labels = pd.merge(labels,day_browes,how = 'left',on = 'user_id')
labels.rename(columns = {'date':'day_browes'},inplace = True)
5.2 上次加購距今天數(shù)
#5.2 上次加購距今天數(shù)
day_cart = df[df['behavior_type']== 3].groupby('user_id').date.max().apply(lambda x:(datetime.strptime('2014-12-19','%Y-%m-%d')-x).days)
labels = pd.merge(labels,day_cart,how = 'left',on = 'user_id')
labels.rename(columns = {'date':'day_cart'},inplace = True)
5.3 上次購買距今天數(shù)
#5.3 上次購買距今天數(shù)
day_buy = df[df['behavior_type']== 4].groupby('user_id').date.max().apply(lambda x:(datetime.strptime('2014-12-19','%Y-%m-%d')-x).days)
labels = pd.merge(labels,day_buy,how = 'left',on = 'user_id')
labels.rename(columns = {'date':'day_buy'},inplace = True)
6.最近兩次購買間隔天數(shù)
df_interval_buy = df[df['behavior_type'] == 4].groupby(['user_id','date']).item_id.count().reset_index()
interval_buy = df_interval_buy.groupby('user_id').date.apply(lambda x:x.sort_values().diff(1).dropna().head(1)).reset_index()
labels = pd.merge(labels,interval_buy,how = 'left',on = 'user_id')
labels.head()
7.是否有商品瀏覽未下單
#取出瀏覽未購買的數(shù)據(jù)
df_browse_buy = df.loc[(df['behavior_type'] == 1 )| (df['behavior_type'] == 4),['user_id','item_id','behavior_type','time']]
#對上表進(jìn)行數(shù)據(jù)透視表
browse_not_buy = pd.pivot_table(df_browse_buy,index = ['user_id','item_id'],columns = ['behavior_type'],values = ['time'],aggfunc = ['count'])
browse_not_buy.columns = ['browes','buy']
#nall值填充0
browse_not_buy.fillna(0,inplace = True)
#如果有瀏覽未購買的將browse_not_buy填充為1
browse_not_buy.loc[(browse_not_buy['browes'] > 0) & browse_not_buy['buy'] == 0,'browes_not_buy'] = 1
#統(tǒng)計(jì)用戶有多少個(gè)商品瀏覽未購買
browse_not_buy = browse_not_buy.groupby('user_id').browes_not_buy.sum().reset_index()
labels = pd.merge(labels,browse_not_buy,how = 'left',on ='user_id')
#如果有瀏覽為購買的用戶標(biāo)簽改為'是'
labels['browes_not_buy'] = labels['browes_not_buy'].apply(lambda x:'是' if x>0 else '否')
labels.rename(columns = {'browes_not_buy':'browse_not_buy'},inplace = True)
8.是否有商品加購未下單
#取出加購但未下單的數(shù)據(jù)
df_cart_buy = df.loc[(df['behavior_type'] == 3 )| (df['behavior_type'] == 4),['user_id','item_id','behavior_type','time']]
#對上表進(jìn)行數(shù)據(jù)透視表
cart_not_buy = pd.pivot_table(df_cart_buy,index = ['user_id','item_id'],columns = ['behavior_type'],values = ['time'],aggfunc = ['count'])
cart_not_buy.columns = ['cart','buy']
#對nall值進(jìn)行填充
cart_not_buy.fillna(0,inplace = True)
#如果有加購未購買的將browse_not_buy填充為1
cart_not_buy.loc[(cart_not_buy['cart'] > 0) & cart_not_buy['buy'] == 0,'cart_not_buy'] = 1
cart_not_buy = cart_not_buy.groupby('user_id').cart_not_buy.sum().reset_index()
labels = pd.merge(labels,cart_not_buy,how = 'left',on ='user_id')
#如果有瀏覽為購買的用戶標(biāo)簽改為'是'
labels['cart_not_buy'] = labels['cart_not_buy'].apply(lambda x:'是' if x>0 else '否')
9、用戶屬性標(biāo)簽
9.1 是否復(fù)購用戶
#提取購買用戶的數(shù)據(jù),并根據(jù)用戶進(jìn)行分組,統(tǒng)計(jì)購買次數(shù)
buy_again = df[df['behavior_type'] == 4].groupby('user_id').time.count().reset_index()
buy_again.rename(columns = {'time':'buy_again'},inplace = True)
labels = pd.merge(labels,buy_again,how = 'left',on = 'user_id')
#如果購買次數(shù)大于1則為復(fù)購用戶
labels['buy_again'] = labels['buy_again'].apply(lambda x:'是' if x > 1 else '否' if x == 1 else '未購買')
labels.head()
9.2 訪問活躍度
#對count_30_active進(jìn)行分組,統(tǒng)計(jì)訪問次數(shù)
user_active_level = labels['count_30_active'].value_counts().sort_index(ascending = False)
#進(jìn)行繪圖得到趨勢圖
plt.figure(figsize=(10,5))
user_active_level.plot(title='30天內(nèi)訪問天數(shù)與訪問人數(shù)的關(guān)系',fontsize=18)
plt.ylabel('訪問人數(shù)',fontsize=14)
plt.xlabel('訪問天數(shù)',fontsize=14)

總體上看,訪問天數(shù)多的訪客比訪問天數(shù)少的訪客數(shù)量多,且以20次左右為拐點(diǎn),因此定義訪問天數(shù)小于20次的為低活躍,訪問天數(shù)大于等于20次的定義為高活躍。
#定義活躍度大于20則為高活躍度用戶
labels['buy_active_level'] = '高'
labels.loc[labels['count_30_active']<=19,'buy_active_level'] = '低'
9.3 購買的品類是否單一
#提取購買的數(shù)據(jù),并根據(jù)user_id進(jìn)行分組,對購買類目進(jìn)行統(tǒng)計(jì)
buy_sinple = df[df['behavior_type'] == 4].groupby('user_id').item_category.nunique().reset_index()
buy_sinple.rename(columns = {'item_category':'buy_sinple'},inplace = True)
labels = pd.merge(labels,buy_sinple,how = 'left',on = 'user_id')
labels['buy_sinple'].fillna(-1,inplace = True)
#判斷技術(shù)是否大于1
labels['buy_sinple'] = labels['buy_sinple'].apply(lambda x:'否' if x>1 else '是' if x == 1 else '未購買')
9.4 用戶價(jià)值分組
#獲取標(biāo)簽統(tǒng)計(jì)值day_buy得到距今購買天數(shù),并進(jìn)行統(tǒng)計(jì)計(jì)數(shù)
last_buy_days = labels['day_buy'].value_counts().sort_index()
#對統(tǒng)計(jì)計(jì)數(shù)的結(jié)果進(jìn)行畫圖
plt.figure(figsize=(16,9))
last_buy_days.plot(title='最后一次購買距今天數(shù)與人數(shù)的關(guān)系',fontsize=18)
plt.ylabel('購買人數(shù)',fontsize=14)
plt.xlabel('距今天數(shù)',fontsize=14)

可以看出大于8天為低
labels['buy_days_level'] = '高'
labels.loc[labels['day_buy'] > 8,'buy_days_level'] = '低'
labels['rfm_value'] = labels['buy_active_level'].str.cat(labels['buy_days_level'])
#定義一個(gè)函數(shù)用來轉(zhuǎn)換標(biāo)簽值
def trans_value(x):
if x == '高高':
return '重要價(jià)值客戶'
elif x == '低高':
return '重要深耕客戶'
elif x == '高低':
return '重要喚回客戶'
else:
return '即將流失客戶'
#使用定義的函數(shù)轉(zhuǎn)換標(biāo)簽紙
labels['rfm'] = labels['rfm_value'].apply(trans_value)
#刪除buy_days_level
labels.drop(['buy_days_level','rfm_value'],axis=1,inplace=True)
#統(tǒng)計(jì)rfm各個(gè)值的情況
labels['rfm'].value_counts()
# 保存數(shù)據(jù)到數(shù)據(jù)庫中
#將數(shù)據(jù)存入數(shù)據(jù)庫
engine = create_engine('mysql://root:mima@localhost:3306/datafrog_study?charset=gbk')
labels.to_sql('profile_user_labels',con = engine,if_exists='replace', index=False)