创建按星期几的特征
我们可以构造日期时间特征,为非线性模型提供更多信息。大多数金融数据都带有日期时间信息,其中包含大量内容——年份、月份、日期,有时还有小时、分钟和秒。此外,我们还可以得到星期几、季度,或自某事件(例如财报发布)以来的经过时间。
这里我们只提取星期几,因为我们的数据集回溯时间不长。pandas 的日期时间索引中的 dayofweek 属性可以帮助我们得到星期几。然后,我们用 pandas 的 get_dummies() 对 dayofweek 做哑变量处理。这样会为每个星期几创建一列,取二元值(0 或 1)。我们会丢弃第一列,因为它可以由其他列推断出来。
本练习是课程的一部分
Python 金融机器学习
练习说明
- 使用
lng_df索引中的dayofweek属性获取星期几。 - 对该星期几变量使用
get_dummies函数,并设置前缀为'weekday'。 - 将
days_of_week变量的索引设为与lng_df的索引相同,以便合并二者。 - 将
lng_df和days_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())