指定每日取得的同批族群(cohort)
就像你在影片中看到的,定義同批族群(cohort)是進行同批分析的第一步。現在你要依每位顧客首次交易的日期,建立「每日」同批族群。
資料已載入為 online DataFrame。你可以在主控台輸入 online.head() 來列印前幾列。
本練習屬於課程
Python 的客群分群
練習說明
- 建立一個函式,接收一個 datetime 物件,從
x擷取 year、month 和 day。 - 以
InvoiceDate欄位為輸入並套用get_day函式,建立InvoiceDay欄位。 - 建立一個
groupby物件,先依CustomerID變數分組,接著選取InvoiceDay以便後續計算。 - 選取最小的
InvoiceDay值,建立CohortDay欄位。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Define a function that will parse the date
def get_day(x): return dt.datetime(x.year, ____, ____)
# Create InvoiceDay column
online['____'] = online['____'].apply(____)
# Group by CustomerID and select the InvoiceDay value
grouping = online.groupby('____')['____']
# Assign a minimum InvoiceDay value to the dataset
online['CohortDay'] = grouping.____('____')
# View the top 5 rows
print(online.head())