【发布时间】:2021-09-28 19:25:54
【问题描述】:
- 第一期:
我正在尝试将样本的频率从单独的事件更改为连续范围:
import pandas as pd
all_days= pd.period_range('2020-01-01', '2020-01-08')
df1=pd.DataFrame.from_dict({'2020-01-04': 2, '2020-01-07': 10}, 'index')
df_new = df1.reindex(all_days, fill_value=0)
我明白了:
df_new
Out[571]:
0
2020-01-01 0
2020-01-02 0
2020-01-03 0
2020-01-04 0
2020-01-05 0
2020-01-06 0
2020-01-07 0
2020-01-08 0
但我想得到:
df_new
Out[571]:
0
2020-01-01 0
2020-01-02 0
2020-01-03 0
2020-01-04 2
2020-01-05 0
2020-01-06 0
2020-01-07 10
2020-01-08 0
-
更高级的问题:我想对一个数据框执行相同的操作,一个日期有多个值,例如:
df2=pd.DataFrame([[10, 20],[6, 8],[2, 2]],['2020-01-04', '2020-01-07', '2020-01-07'],['A','B'])
为:
df_new = df2.reindex(all_days, fill_value=0)
我收到一个错误: ValueError:无法从重复的轴重新索引
但我想得到:
df_new
Out[571]:
A B
2020-01-01 0 0
2020-01-02 0 0
2020-01-03 0 0
2020-01-04 10 20
2020-01-05 0 0
2020-01-06 0 0
2020-01-07 6 8
2020-01-07 2 2
2020-01-08 0 0
【问题讨论】:
标签: python time-series resampling