分析 datetime 欄位
特徵工程是所有機器學習流程中的重要步驟,用來處理不同資料型別的特徵。特別是,許多資料集中常見 datetime 欄位。在這個練習中,你會探索資料集中的 hour 欄位。它以整數儲存,但其實代表 datetime。你會先解析 hour 欄位,將它轉換成 datetime 欄位。接著,從該 datetime 欄位擷取一天中的小時,並依此小時計算總點擊數。
pandas 模組已在你的工作區以 pd 提供,範例 DataFrame 也已載入為 df。
本練習屬於課程
用 Python 透過機器學習預測 CTR
練習說明
- 使用
pd.to_datetime()將hour欄位從整數轉換成datetime欄位。 - 使用 datetime 存取器
.dt,透過.hour從轉換後的欄位擷取小時值。 - 依擷取的一天中的小時計算總點擊數,使用
.sum()。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Change the hour column to a datetime and extract hour of day
df['hour'] = pd.____(df['hour'], format = '%y%m%d%H')
df['hour_of_day'] = df['hour'].____.____
print(df.head(5))
# Get and plot total clicks by hour of day
df.____('hour_of_day')['click'].____.plot.bar(figsize=(12,6))
plt.ylabel('Number of clicks')
plt.title('Number of clicks by hour of day')
plt.show()