溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么用Pandas構建數(shù)據(jù)

發(fā)布時間:2022-01-26 09:30:30 來源:億速云 閱讀:85 作者:iii 欄目:開發(fā)技術

本文小編為大家詳細介紹“怎么用Pandas構建數(shù)據(jù)”,內容詳細,步驟清晰,細節(jié)處理妥當,希望這篇“怎么用Pandas構建數(shù)據(jù)”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學習新知識吧。

構建數(shù)據(jù)

本案例中用的數(shù)據(jù)是小編自行模擬的,主要包含兩個數(shù)據(jù):訂單數(shù)據(jù)和水果信息數(shù)據(jù),并且會將兩份數(shù)據(jù)合并

import pandas as pd
import numpy as np
import random
from datetime import *
import time

import plotly.express as px
import plotly.graph_objects as go
import plotly as py

# 繪制子圖
from plotly.subplots import make_subplots

1、時間字段

怎么用Pandas構建數(shù)據(jù)

2、水果和用戶

怎么用Pandas構建數(shù)據(jù)

3、生成訂單數(shù)據(jù)

order = pd.DataFrame({
    "time":time_range,  # 下單時間
    "fruit":fruit_list,  # 水果名稱
    "name":name_list,  # 顧客名
    # 購買量
    "kilogram":np.random.choice(list(range(50,100)), size=len(time_range),replace=True) 
})

order

怎么用Pandas構建數(shù)據(jù)

4、生成水果的信息數(shù)據(jù)

infortmation = pd.DataFrame({
    "fruit":fruits,
    "price":[3.8, 8.9, 12.8, 6.8, 15.8, 4.9, 5.8, 7],
    "region":["華南","華北","西北","華中","西北","華南","華北","華中"]
})

infortmation

怎么用Pandas構建數(shù)據(jù)

5、數(shù)據(jù)合并

將訂單信息和水果信息直接合并成一個完整的DataFrame,這個df就是接下來處理的數(shù)據(jù)

怎么用Pandas構建數(shù)據(jù)

6、生成新的字段:訂單金額

怎么用Pandas構建數(shù)據(jù)

到這里你可以學到:

  • 如何生成時間相關的數(shù)據(jù)

  • 如何從列表(可迭代對象)中生成隨機數(shù)據(jù)

  • Pandas的DataFrame自行創(chuàng)建,包含生成新字段

  • Pandas數(shù)據(jù)合并

分析維度1:時間

2019-2021年每月銷量走勢

1、先把年份和月份提取出來:

df["year"] = df["time"].dt.year
df["month"] = df["time"].dt.month
# 同時提取年份和月份
df["year_month"] = df["time"].dt.strftime('%Y%m')

df

怎么用Pandas構建數(shù)據(jù)

2、查看字段類型:

怎么用Pandas構建數(shù)據(jù)

3、分年月統(tǒng)計并展示:

# 分年月統(tǒng)計銷量
df1 = df.groupby(["year_month"])["kilogram"].sum().reset_index()

fig = px.bar(df1,x="year_month",y="kilogram",color="kilogram")
fig.update_layout(xaxis_tickangle=45)   # 傾斜角度

fig.show()

怎么用Pandas構建數(shù)據(jù)

2019-2021銷售額走勢

df2 = df.groupby(["year_month"])["amount"].sum().reset_index()

df2["amount"] = df2["amount"].apply(lambda x:round(x,2))

fig = go.Figure()
fig.add_trace(go.Scatter(  #
    x=df2["year_month"],
    y=df2["amount"],
    mode='lines+markers', # mode模式選擇
    name='lines')) # 名字

fig.update_layout(xaxis_tickangle=45)   # 傾斜角度

fig.show()

怎么用Pandas構建數(shù)據(jù)

年度銷量、銷售額和平均銷售額

怎么用Pandas構建數(shù)據(jù)

分析維度2:商品

水果年度銷量占比

df4 = df.groupby(["year","fruit"]).agg({"kilogram":"sum","amount":"sum"}).reset_index()
df4["year"] = df4["year"].astype(str)
df4["amount"] = df4["amount"].apply(lambda x: round(x,2))

from plotly.subplots import make_subplots
import plotly.graph_objects as go

fig = make_subplots(
    rows=1, 
    cols=3,
    subplot_titles=["2019年","2020年","2021年"],
    specs=[[{"type": "domain"},   # 通過type來指定類型
           {"type": "domain"},
           {"type": "domain"}]]
)  

years = df4["year"].unique().tolist()

for i, year in enumerate(years):
    name = df4[df4["year"] == year].fruit
    value = df4[df4["year"] == year].kilogram
    
    fig.add_traces(go.Pie(labels=name,
                        values=value
                       ),
                 rows=1,cols=i+1
                )

fig.update_traces(
    textposition='inside',   # 'inside','outside','auto','none'
    textinfo='percent+label',
    insidetextorientation='radial',   # horizontal、radial、tangential
    hole=.3,
    hoverinfo="label+percent+name"
)

fig.show()

怎么用Pandas構建數(shù)據(jù)

各水果年度銷售金額對比

years = df4["year"].unique().tolist()

for _, year in enumerate(years):
    
    df5 = df4[df4["year"]==year]
    fig = go.Figure(go.Treemap( 
        labels = df5["fruit"].tolist(),
        parents = df5["year"].tolist(),
        values = df5["amount"].tolist(),
        textinfo = "label+value+percent root"
    ))
    
    fig.show()

怎么用Pandas構建數(shù)據(jù)

怎么用Pandas構建數(shù)據(jù)

怎么用Pandas構建數(shù)據(jù)

商品月度銷量變化

怎么用Pandas構建數(shù)據(jù)

fig = px.bar(df5,x="year_month",y="amount",color="fruit")
fig.update_layout(xaxis_tickangle=45)   # 傾斜角度
fig.show()

怎么用Pandas構建數(shù)據(jù)

折線圖展示的變化:

怎么用Pandas構建數(shù)據(jù)

分析維度3:地區(qū)

不同地區(qū)的銷量

怎么用Pandas構建數(shù)據(jù)

怎么用Pandas構建數(shù)據(jù)

不同地區(qū)年度平均銷售額

df7 = df.groupby(["year","region"])["amount"].mean().reset_index()

怎么用Pandas構建數(shù)據(jù)

分析維度4:用戶

用戶訂單量、金額對比

df8 = df.groupby(["name"]).agg({"time":"count","amount":"sum"}).reset_index().rename(columns={"time":"order_number"})
df8.style.background_gradient(cmap="Spectral_r")

怎么用Pandas構建數(shù)據(jù)

用戶水果喜好

根據(jù)每個用戶對每種水果的訂單量和訂單金額來分析:

df9 = df.groupby(["name","fruit"]).agg({"time":"count","amount":"sum"}).reset_index().rename(columns={"time":"number"})

df10 = df9.sort_values(["name","number","amount"],ascending=[True,False,False])

df10.style.bar(subset=["number","amount"],color="#a97fcf")

怎么用Pandas構建數(shù)據(jù)

px.bar(df10,
       x="fruit",
       y="amount",
#            color="number",
       facet_col="name"
      )

怎么用Pandas構建數(shù)據(jù)

用戶分層—RFM模型

RFM模型是衡量客戶價值和創(chuàng)利能力的重要工具和手段。

通過這個模型能夠反映一個用戶的交期交易行為、交易的總體頻率和總交易金額3項指標,通過3個指標來描述該客戶的價值狀況;同時依據(jù)這三項指標將客戶劃分為8類客戶價值:

  • Recency(R)是客戶最近一次購買日期距離現(xiàn)在的天數(shù),這個指標與分析的時間點有關,因此是變動的。理論上客戶越是在近期發(fā)生購買行為,就越有可能復購

  • Frequency(F)指的是客戶發(fā)生購買行為的次數(shù)–最常購買的消費者,忠誠度也就較高。增加顧客購買的次數(shù)意味著能占有更多的時長份額。

  • Monetary value(M)是客戶購買花費的總金額。

怎么用Pandas構建數(shù)據(jù)

下面通過Pandas的多個方法來分別求解這個3個指標,首先是F和M:每位客戶的訂單次數(shù)和總金額

怎么用Pandas構建數(shù)據(jù)

如何求解R指標呢?

1、先求解每個訂單和當前時間的差值

怎么用Pandas構建數(shù)據(jù)

2、根據(jù)每個用戶的這個差值R來進行升序排列,排在第一位的那條數(shù)據(jù)就是他最近購買記錄:以xiaoming用戶為例,最近一次是12月15號,和當前時間的差值是25天

怎么用Pandas構建數(shù)據(jù)

3、根據(jù)用戶去重,保留第一條數(shù)據(jù),這樣便得到每個用戶的R指標:

怎么用Pandas構建數(shù)據(jù)

4、數(shù)據(jù)合并得到3個指標:

怎么用Pandas構建數(shù)據(jù)

怎么用Pandas構建數(shù)據(jù)

當數(shù)據(jù)量足夠大,用戶足夠多的時候,就可以只用RFM模型來將用戶分成8個類型

用戶復購周期分析

復購周期是用戶每兩次購買之間的時間間隔:以xiaoming用戶為例,前2次的復購周期分別是4天和22天

怎么用Pandas構建數(shù)據(jù)

下面是求解每個用戶復購周期的過程:

1、每個用戶的購買時間升序

怎么用Pandas構建數(shù)據(jù)

2、將時間移動一個單位:

怎么用Pandas構建數(shù)據(jù)

3、合并后的差值:

出現(xiàn)空值是每個用戶的第一條記錄之前是沒有數(shù)據(jù),后面直接刪除了空值部分

怎么用Pandas構建數(shù)據(jù)

怎么用Pandas構建數(shù)據(jù)

直接取出天數(shù)的數(shù)值部分:

怎么用Pandas構建數(shù)據(jù)

5、復購周期對比

px.bar(df16,
       x="day",
       y="name",
       orientation="h",
       color="day",
       color_continuous_scale="spectral"   # purples
      )

怎么用Pandas構建數(shù)據(jù)

上圖中矩形越窄表示間隔越?。幻總€用戶整個復購周期由整個矩形長度決定。查看每個用戶的整體復購周期之和與平均復購周期:

怎么用Pandas構建數(shù)據(jù)

得到一個結論:Michk和Mike兩個用戶整體的復購周期是比較長的,長期來看是忠誠的用戶;而且從平均復購周期來看,相對較低,說明在短時間內復購活躍。

從下面的小提琴中同樣可以觀察到,Michk和Mike的復購周期分布最為集中。

怎么用Pandas構建數(shù)據(jù)

讀到這里,這篇“怎么用Pandas構建數(shù)據(jù)”文章已經介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領會,如果想了解更多相關內容的文章,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI