開始使用免費開始

指定每日取得的同批族群(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())
編輯並執行程式碼