我从 SP500 获得了所有 505 只股票的数据框。我想使用 asfreq 函数获取每个星期日的每周值。 假设我仅在 20 个交易日内将其用于 AAPL 和 MSFT 股票的两列。
AAPL MSFT
Date
2012-04-05 82.099293 27.453578
2012-04-09 82.429673 27.087763
2012-04-10 81.420407 26.539039
2012-04-11 81.130193 26.434521
2012-04-12 80.685799 26.983243
2012-04-13 78.413325 26.835175
2012-04-16 75.161385 27.070343
2012-04-17 78.992457 27.383899
2012-04-18 78.816259 27.122601
2012-04-19 76.108461 27.009374
2012-04-20 74.235032 28.237466
2012-04-23 74.069192 27.976170
2012-04-24 72.589626 27.801974
2012-04-25 79.031329 28.045851
2012-04-26 78.733339 27.967462
2012-04-27 78.124412 27.854232
2012-04-30 75.660185 27.889073
2012-05-01 75.420503 27.880361
2012-05-02 75.919303 27.697454
2012-05-03 75.380337 27.662615
我尝试在数据帧上使用 asfreq 函数。
df2 = df.asfreq("W-SUN", method="pad")
它会产生一个巨大的错误,在底部显示:
TypeError: Cannot compare type 'Timestamp' with type 'str'
我也试过 method = "ffill",同样的错误。 asfreq("W-SUN") 只给了我 NaN 值,而 asfreq("W-MON", method="pad") 也给了我同样的错误“W-SUN”。
我以前用过 asfreq 函数,效果很好,但现在不行了。是什么赋予了?非常感谢任何帮助。
请您参考如下方法:
asfreq与 DatetimeIndex 一起使用,错误告诉您它仍然是 str 因此您需要使用 to_datetime 转换 dtype :
df.index = pd.to_datetime(df.index)
然后对 asfreq 的调用应该按预期工作
