开始使用免费开始使用

比较年度股价走势

在视频中,您已经看到如何从时间序列中选择子区间。

现在请用这一方法来比较 Yahoo 股票在三个年份的表现。

本练习是课程的一部分

Python 中的时间序列数据处理

查看课程

练习说明

我们已将 pandas 导入为 pd,将 matplotlib.pyplot 导入为 plt,并已将 'yahoo.csv' 文件加载到变量 yahoo 中。yahoo 具有 DateTimeIndex,且只有一列 price

  • 创建一个空的 pd.DataFrame(),命名为 prices
  • 遍历包含 2013、2014 和 2015 三个年份的列表(类型为 string),在每次循环中:
    • 使用循环变量选择该年份的数据以及 price 列。
    • 使用 .reset_index() 并设置 drop=True 来移除 DatetimeIndex
    • price 列重命名为对应的 year
    • 使用 pd.concat() 沿着 axis=1 将该年份的数据与 prices 合并。
  • 绘制 prices

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Create dataframe prices here
prices = ____

# Select data for each year and concatenate with prices here 
for year in [___, ___, ___]:
    price_per_year = yahoo.loc[___, [___]].reset_index(drop=True)
    price_per_year.rename(columns={___: year}, inplace=True)
    prices = pd.concat([prices, ___], axis=1)

# Plot prices

编辑并运行代码