開始使用免費開始

建立星期幾特徵

我們可以工程化日期時間特徵,為非線性模型加入更多資訊。多數金融資料都帶有日期時間,其中包含大量資訊——年份、月份、日期,有時還有時、分、秒。我們也能取得星期幾、年度的季度,或自某事件(例如財報發布)以來的經過時間。

這裡我們只要擷取星期幾,因為這個資料集的時間範圍不長。pandas 日期時間索引的 dayofweek 屬性能幫我們取得星期幾。接著使用 pandas 的 get_dummies()dayofweek 做虛擬變數轉換。這會為每個星期幾建立一個欄位,值為二元(0 或 1)。我們會丟棄第一個欄位,因為它可以由其他欄位推得。

本練習屬於課程

Python 金融 Machine Learning

檢視課程

練習說明

  • 使用 lng_df 索引的 dayofweek 屬性取得星期幾。
  • 對星期幾變數使用 get_dummies 函式,並加上字首 'weekday'
  • days_of_week 變數的索引設為與 lng_df 索引相同,方便之後合併。
  • lng_dfdays_of_week 兩個 DataFrame 串接為一個 DataFrame。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Use pandas' get_dummies function to get dummies for day of the week
days_of_week = pd.get_dummies(lng_df.index.____,
                              prefix=____,
                              drop_first=True)

# Set the index as the original dataframe index for merging
days_of_week.index = lng_df.____

# Join the dataframe with the days of week dataframe
lng_df = pd.concat([lng_df, ____], axis=1)

# Add days of week to feature names
feature_names.extend(['weekday_' + str(i) for i in range(1, 5)])
lng_df.dropna(inplace=True)  # drop missing values in-place
print(lng_df.head())
編輯並執行程式碼