我有一个季度数据的 ID 和日期表,我想将其重新索引为每日(工作日)。
示例表:
我正在尝试找出一种 pythonic 或 pandas 方式来重新索引到更高频率的日期范围,例如每日和向前填充任何 NaN。
到目前为止已经尝试过:
df = pd.read_sql('select date, id, type, value from db_table' con=conn, index_col=['date', 'id', 'type'])
dates = pd.bdate_range(start, end)
new_idx = pd.MultiIndex.from_product([dates, df.index.get_level_values(1), df.index.get_level_values(2)]
new_df = df.reindex(new_idx)
#this just hangs
new_df = new_df.groupby(level=1).fillna(method='ffill')
无济于事。我要么得到一个
异常:无法处理非唯一的多重索引!
或者,如果 ID 和类型之间的日期一致,则各个日期会重复多次(这听起来像是一个错误?)
最终,我只想按日期、ID 和类型对表进行分组,并在 ID 和类型之间拥有一致的日期索引。
有没有办法在 pandas 中做到这一点?
最佳答案
是的,您可以使用合并
new_idx_frame=new_idx.to_frame()
new_idx_frame.columns=['date', 'id', 'type']
Yourdf=df.reset_index().merge(new_idx_frame,how='right',sort =True).groupby('id').ffill()# here I am using toy data
Out[408]:
id date type value
0 1 1 1 NaN
1 1 1 2 NaN
2 2 1 1 666666.0
3 2 1 2 99999.0
4 1 2 1 -1.0
5 1 2 1 -1.0
6 1 2 2 -1.0
7 2 2 1 99999.0
8 2 2 2 99999.0
<小时/>
示例数据
df=pd.DataFrame({'date':[1,1,2,2],'id':[2,2,1,1],'type':[2,1,1,1],'value':[99999,666666,-1,-1]})
df=df.set_index(['date', 'id', 'type'])
new_idx = pd.MultiIndex.from_product([[1,2], [1,2],[1,2]])
关于python - pandas 将多索引重新索引为更高频率的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55436896/