我想为数据透视表重新索引,以获取每日索引链。当前索引如下:
您可以看到第一个级别是某些系列从开始算起的每月周期性,而其他系列则是每天一次。
start_date = piv_table.index.min()
end_date = piv_table.index.max()
我正在获取每日索引的开始和结束日期,如下所示(piv_table是我的数据透视表):
new_dates = pd.date_range(start_date[0], end_date[0], freq='D')
我需要创建一个每日日期时间对象的列表,像这样:
new_pivot = piv_table.reindex(new_dates,level=0).ffill()
接下来,我要重新索引数据:
date type frequency expiration_date ADP LEVL Index ADS BCI Index
1/31/1919 PX_LAST M 12/31/2099 2 3
2/28/1919 PX_LAST M 12/31/2099
3/31/1919 PX_LAST M 12/31/2099
4/30/1919 PX_LAST M 12/31/2099
5/31/1919 PX_LAST M 12/31/2099
6/30/1919 PX_LAST M 12/31/2099
7/31/1919 PX_LAST M 12/31/2099
8/31/1919 PX_LAST M 12/31/2099
9/30/1919 PX_LAST M 12/31/2099
10/31/1919 PX_LAST M 12/31/2099
11/30/1919 PX_LAST M 12/31/2099
12/31/1919 PX_LAST M 12/31/2099
1/31/1920 PX_LAST M 12/31/2099
2/29/1920 PX_LAST M 12/31/2099
3/31/1920 PX_LAST M 12/31/2099
4/30/1920 PX_LAST M 12/31/2099
5/31/1920 PX_LAST M 12/31/2099
6/30/1920 PX_LAST M 12/31/2099
6/1/2020 PX_LAST D 12/31/2099 23 2342
6/1/2020 PX_LAST W 12/31/2099
6/2/2020 PX_LAST D 12/31/2099
6/3/2020 PX_LAST D 12/31/2099
6/4/2020 PX_LAST D 12/31/2099
6/5/2020 PX_LAST D 12/31/2099
6/6/2020 PX_LAST D 12/31/2099
6/7/2020 PX_LAST D 12/31/2099
6/8/2020 PX_LAST D 12/31/2099
6/8/2020 PX_LAST W 12/31/2099
6/9/2020 PX_LAST D 12/31/2099
6/30/2020 PX_LAST M 12/31/2099
但是实际上什么也没发生,我的new_pivot表还是一样。索引没有变化以合并每日变化。我在做什么错了?
这是我的示例数据:
sorted
答案 0 :(得分:0)
这是一种实现方法:
min_date = df.reset_index()["date"].min()
max_date = df.reset_index()["date"].max()
all_dates = pd.date_range(min_date, max_date, freq="D")
all_dates.name = "date"
pd.DataFrame(index=all_dates).join(df.reset_index().set_index("date")).sort_index().fillna(method="ffill")
结果是(我没有索引,ADS和BSI的值):
type frequency expiration_date ADP LEVL Index ADS BCI \
date
1919-01-31 PX_LAST M 12/31/2099 2.0 3.0 NaN NaN NaN
1919-02-01 PX_LAST M 12/31/2099 2.0 3.0 NaN NaN NaN
1919-02-02 PX_LAST M 12/31/2099 2.0 3.0 NaN NaN NaN
1919-02-03 PX_LAST M 12/31/2099 2.0 3.0 NaN NaN NaN
1919-02-04 PX_LAST M 12/31/2099 2.0 3.0 NaN NaN NaN