我在 pandas DataFrame 中有每日数据df
缺少某些日期(例如下面的 1980 年 12 月 25 日)。我想重新索引 DataFrame 以添加具有 NaN 值的日期。
date close
None
0 1980-12-12 28.75
1 1980-12-15 27.25
2 1980-12-16 25.25
3 1980-12-17 25.87
4 1980-12-18 26.63
5 1980-12-19 28.25
6 1980-12-22 29.63
7 1980-12-23 30.88
8 1980-12-24 32.50
9 1980-12-26 35.50
我已经生成了列表dates
以及我想要的全套日期。
[Timestamp('1980-12-12 00:00:00'), Timestamp('1980-12-15 00:00:00'), Timestamp('1980-12-16 00:00:00'), Timestamp('1980-12-17 00:00:00'), Timestamp('1980-12-18 00:00:00'), Timestamp('1980-12-19 00:00:00'), Timestamp('1980-12-22 00:00:00'), Timestamp('1980-12-23 00:00:00'), Timestamp('1980-12-24 00:00:00'), Timestamp('1980-12-25 00:00:00'), Timestamp('1980-12-26 00:00:00')]
不幸的是,当我运行下面的 reindex 命令时,表完全被 NaN 填满。
df.reindex(dates)
我进行了以下检查,一切都很好......
>>> type(df['date'][0])
<class 'pandas._libs.tslib.Timestamp'>
>>> type(dates[0])
<class 'pandas._libs.tslib.Timestamp'>
>>> dates[0] == df['date'][0]
True