python實現淘寶使用者行為分析

qq_22790151發表於2020-11-15

1、前言

專案背景:阿里天池提供了淘寶平臺2014年11月18日至2014年12月18日的使用者行為資料(點選、收藏、加入購物車以及購買行為),針對該資料我們做探索性的資料分析,分析內容包含:

  • 基於AARRR模型對使用者的活躍情況、使用者行為路徑漏斗轉化、使用者的變現情況進行分析
  • 從時間的維度分析使用者行為
  • 利用RFM模型對使用者進行分層分析
  • 找到使用者對不同種類商品的偏好,制定針對不同商品的營銷策略

在這裡插入圖片描述

2、資料集

資料來源:阿里天池

3、資料探索和清洗

# 引入第三方庫
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 讓matplotlib畫的圖顯示出來,pycharm工具不用新增
%matplotlib inline 
# 讀取資料
data_user = pd.read_csv("tianchi_mobile_recommend_train_user.csv")
# 檢視資料規模
data_user.shape
(12256906, 6)
# 檢視資料資訊,由於資料量過大,只取2014-12-09到2014-12-16一週的資料
data_user=data_user[(pd.to_datetime(data_user["time"],format="%Y-%m-%d")>=pd.to_datetime("20141209",format="%Y-%m-%d"))&(pd.to_datetime(data_user["time"],format="%Y-%m-%d")<pd.to_datetime("20141217",format="%Y-%m-%d"))]
data_user.head(10)
user_iditem_idbehavior_typeuser_geohashitem_categorytime
1977261363835835901NaN58942014-12-09 20
4981459082902085201NaN139262014-12-16 21
6948327431057497251NaN95592014-12-13 20
8966102961611666431NaN30642014-12-11 23
1110178172113914413119rgt16234242014-12-13 21
13101260672212072908195q0is4109842014-12-12 11
141048112653227367921NaN65132014-12-11 19
161042212742626618661NaN43702014-12-14 12
171104186061449025061NaN116392014-12-09 16
201017817211934930719rgt16g18632014-12-12 12

資料欄位說明

  • user_id:使用者ID
  • item_id:商品ID
  • behavior_type:使用者行為,用數字代替(點選,收藏,加購物車和付款四種行為,相應的值分別為1,2,3和4)
  • user_geohash:使用者地理位置
  • item_category:商品類別ID
  • time:使用者行為時間
# 檢視資料缺失值情況
data_user.isnull().sum() # 對每一列缺失值個數進行統計
user_id                0
item_id                0
behavior_type          0
user_geohash     2197244
item_category          0
time                   0
dtype: int64

說明:user_geohash(使用者地理位置)缺失值較多,對該資料不做處理和分析

# 查詢各欄位型別等基本資訊
data_user.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 3603297 entries, 1 to 12256903
Data columns (total 6 columns):
user_id          int64
item_id          int64
behavior_type    int64
user_geohash     object
item_category    int64
time             object
dtypes: int64(4), object(2)
memory usage: 192.4+ MB
# 對time做處理,獲得兩個新欄位:日期和小時
data_user["date"] = data_user["time"].apply(lambda x:str(x).split(" ")[0])
data_user["hour"] = data_user["time"].apply(lambda x:str(x).split(" ")[1])
data_user.head(10)
user_iditem_idbehavior_typeuser_geohashitem_categorytimedatehour
1977261363835835901NaN58942014-12-09 202014-12-0920
4981459082902085201NaN139262014-12-16 212014-12-1621
6948327431057497251NaN95592014-12-13 202014-12-1320
8966102961611666431NaN30642014-12-11 232014-12-1123
1110178172113914413119rgt16234242014-12-13 212014-12-1321
13101260672212072908195q0is4109842014-12-12 112014-12-1211
141048112653227367921NaN65132014-12-11 192014-12-1119
161042212742626618661NaN43702014-12-14 122014-12-1412
171104186061449025061NaN116392014-12-09 162014-12-0916
201017817211934930719rgt16g18632014-12-12 122014-12-1212
# 對date轉變為日期格式,hour轉變成int
data_user["date"] = pd.to_datetime(data_user["date"])
data_user["hour"] = data_user["hour"].astype("int64")
data_user.dtypes
user_id                   int64
item_id                   int64
behavior_type             int64
user_geohash             object
item_category             int64
time                     object
date             datetime64[ns]
hour                      int64
dtype: object

4、資料分析和視覺化

1、AARRR模型

1.1活躍使用者單天人均消費次數
# 統計單日使用者總的購買次數,除以活躍次數(有操作行為的使用者都作為活躍使用者)
data_user["operation"]=1
data_user_operation=data_user.groupby(["date","user_id","behavior_type"])["operation"].count().reset_index()
data_user_count = data_user_operation.groupby(["date"]).apply(lambda x:x[x.behavior_type==4].operation.sum()/len(x.user_id.unique()))
plt.plot(range(9,17),data_user_count.values)
plt.xticks(range(9,17),data_user_count.index.strftime("%Y-%m-%d"),rotation=45)                                             

在這裡插入圖片描述

分析:平日單天使用者平均消費次數是0.4-0.6,雙12使用者單天平均消費次數達到2次

1.2付費率統計(付費人數/活躍人數)
data_user_buy = data_user_operation.groupby(["date"]).apply(lambda x:x[x.behavior_type==4].operation.count()/len(x.user_id.unique()))
plt.plot(range(9,17),data_user_buy.values)
plt.xticks(range(9,17),data_user_buy.index.strftime("%Y-%m-%d"),rotation=45)  

在這裡插入圖片描述

分析:平日裡活躍使用者有20%-25%轉化為付費使用者,雙12這部分使用者可以達到接近50%

1.3.復購率統計
#復購率=復購使用者數(不考慮同一天購買多次的情況)/產生購買行為的使用者數
data_user_buy_all =data_user[data_user["behavior_type"]==4].groupby("user_id")["date"].apply(lambda x:len(x.unique()))
first = data_user_buy_all.count()
again = data_user_buy_all[data_user_buy_all>=2].count()
print("復購率:",format(again/first,".2%"))

復購率: 60.19%
1.4.復購率間隔時間統計
data_user_rebuy= data_user[data_user["behavior_type"]==4].groupby(["user_id"])["date"].apply(lambda x:x.drop_duplicates().sort_values().diff(1).dropna())
data_user_rebuy.apply(lambda x:x.days).value_counts().plot(kind="bar")
plt.title("gap-day")
plt.xlabel("gap-days")
plt.ylabel("gap-count")

在這裡插入圖片描述

分析:使用者復購率較高,且復購大都發生在3天以內,應重點喚起3天內有購買行為的使用者

1.5.漏斗轉化分析
#分析使用者從點選——收藏/加購物車——購買行為的漏斗轉化情況
data_behavior_count = data_user.groupby("behavior_type")["user_id"].count().reset_index()
data_series = pd.Series([data_behavior_count["user_id"].loc[0],data_behavior_count["user_id"].loc[1]+data_behavior_count["user_id"].loc[2],data_behavior_count["user_id"].loc[3]],index=["pv","collect_cart","buy"])
print(data_series)
pv              3389835
collect_cart     173824
buy               39638
dtype: int64

在這裡插入圖片描述

2.時間維度分析使用者行為

2.1日pv、uv變化
data_pv = data_user.groupby("date")["user_id"].count().reset_index().rename(columns={"user_id":"pv"})
data_uv = data_user.groupby("date")["user_id"].apply(lambda x:x.drop_duplicates().count()).reset_index().rename(columns={"user_id":"uv"})
fig,axes = plt.subplots(2,1,sharex=True)
data_pv.plot(x="date",y="pv",ax=axes[0])
data_uv.plot(x="date",y="uv",ax=axes[1])
axes[0].set_title("pv-daily")
axes[1].set_title("uv-daily")

在這裡插入圖片描述

分析:pv和uv變化趨勢基本一致,在雙12當天均出現高峰,符合預期

2.2小時pv、uv變化
hour_pv = data_user.groupby(["hour","date"])["user_id"].count().reset_index() #獲得各小時對應日期的pv數
hour_pv=hour_pv.groupby("hour")["user_id"].mean().reset_index().rename(columns={"user_id":"pv"}) #獲得每天各小時的平均pv
hour_uv=data_user.groupby(["hour","date"])["user_id"].apply(lambda x:x.drop_duplicates().count()).reset_index()# 獲得各小時對應日期的uv數
hour_uv=hour_uv.groupby("hour")["user_id"].mean().reset_index().rename(columns={"user_id":"uv"})
fig,ax1=plt.subplots(1,1) #兩個圖畫在一個座標軸上
ax2 = plt.twinx(ax1)#共用x座標軸,並建立y副座標軸
hour_pv.plot(x="hour",y="pv",ax=ax1,color="red",label="pv")
hour_uv.plot(x="hour",y="uv",ax=ax2,color="blue",label="uv")
ax1.legend(loc="upper left")
ax2.legend(loc="upper right")
plt.xticks(range(24),hour_pv["hour"])

在這裡插入圖片描述

分析:使用者在0-5點不活躍,在18-22點屬於活躍高峰期

3.分析不同商品的使用者行為

3.1商品品類購買次數統計
data_item=data_user[data_user["behavior_type"]==4]["item_category"].value_counts().reset_index().rename(columns={"index":"item_category","item_category":"total"}).groupby("total")["item_category"].count()
bar = data_item.head(10).plot(kind="bar")
plt.xlabel("buy_counts")
plt.ylabel("item_category_counts")
for x,y in zip(data_item.head(10).index,data_item.head(10).values):
    plt.text(x-1,y,y,ha="center",va="bottom")

在這裡插入圖片描述

分析:969種商品種類使用者只有一次購買行為,505種商品有2次購買行為,佔據了總商品的絕大部分比例,說明淘寶主要靠長尾商品的累計盈利,而非靠爆品帶動盈利

3.2統計點選量在前20的商品品類
!pip install squarify --user #繪製樹圖的庫
Looking in indexes: https://mirrors.aliyun.com/pypi/simple
Requirement already satisfied: squarify in /data/nas/workspace/envs/python3.6/site-packages (0.4.3)
import squarify 
data_pv_counts = data_user[data_user["behavior_type"]==1]["item_category"].value_counts().head(20)
squarify.plot(
    sizes=data_pv_counts.values,
    label=data_pv_counts.index.map(lambda x:str(x)+':'),
    value=data_pv_counts.values,
    text_kwargs={'color':"white","fontsize":10}
)

在這裡插入圖片描述

3.3統計銷量前20的商品種類
data_pv_counts = data_user[data_user["behavior_type"]==4]["item_category"].value_counts().head(20)
squarify.plot(
    sizes=data_pv_counts.values,
    label=data_pv_counts.index.map(lambda x:str(x)+':'),
    value=data_pv_counts.values,
    text_kwargs={'color':"white","fontsize":10}
)

在這裡插入圖片描述

分析:1863是一個瀏覽量和銷量都排在第一的商品種類,其他商品種類的瀏覽量和銷量沒有呈正相關,可能浪費了一部分商品的曝光量,應集中把曝光給到更多熱銷商品

4.RFM使用者價值分析

RFM模型是用作評估客戶價值和客戶創利能力的工具,R代表最近一次消費時間,F代表在一定時間段內的消費頻率,M代表在一定時間內的消費金額,通常我們會根據把每個指標細化為2等分,加在一起就是8等分。

  • 重要價值客戶——RFM:111,近期有過消費,高頻且消費金額高,VIP客戶;
  • 重點喚醒客戶——RFM:011,近期沒有消費,高頻且消費金額高,需要和客戶保持聯絡,喚醒客戶再次消費;
  • 重點發展客戶——RFM:101,近期有消費,消費頻次不高,消費金額高,說明客戶的忠誠度不高,需要幫助客戶養成消費習慣;
  • 重點促銷客戶——RFM:110,近期有消費,消費頻次高,消費金額低,說明客戶的忠誠度很高,可以針對使用者打折或者發放代金券,刺激使用者大額消費;
pip install datetime --user
#由於資料來源沒有提供金額資料,所以只針對RF兩個維度進行客戶細分
# R:獲得使用者最後一次消費時間,據此劃分客戶
from datetime import datetime
date_now=datetime(2014,12,18)
R_data=data_user[data_user["behavior_type"]==4].groupby("user_id")["date"].apply(lambda x:(date_now-x.max()).days)
R_data_new=pd.qcut(R_data,2,labels=[0,1]).reset_index()
# F:獲得使用者近一週的消費頻次,據此劃分客戶
F_data=data_user[data_user["behavior_type"]==4].groupby("user_id")["behavior_type"].count()
F_data_new=pd.qcut(F_data,2,labels=[0,1]).reset_index()
RF_data=pd.merge(R_data_new,F_data_new,how="outer")
RF_data["RF"]=RF_data["date"].astype("str")+RF_data["behavior_type"].astype("str")
RF_data.drop(["date","behavior_type"],axis=1,inplace=True)
RF_data.head(10)
user_idRF
0491300
1752810
2759111
31264500
46334810
57982401
68893001
710053901
810415500
910910311

分析:11屬於VIP客戶,重點關注;10忠誠度不高,重點培養使用者購買習性;01近期沒有消費,需要喚醒使用者。

相關文章