熊猫用多列填充DataFrame中的缺失日期

时间:2019-03-07 04:12:14

标签: python pandas

我想为特定日期范围添加缺少的日期,但保留所有列。我发现许多帖子都使用afreq()resample()reindex(),但它们似乎是针对Series的,我无法让它们适用于我的DataFrame。

给出一个示例数据框:

data = [{'id' : '123', 'product' : 'apple', 'color' : 'red', 'qty' : 10, 'week' : '2019-3-7'}, {'id' : '123', 'product' : 'apple', 'color' : 'blue', 'qty' : 20, 'week' : '2019-3-21'}, {'id' : '123', 'product' : 'orange', 'color' : 'orange', 'qty' : 8, 'week' : '2019-3-21'}]

df = pd.DataFrame(data)


    color   id product  qty       week
0     red  123   apple   10   2019-3-7
1    blue  123   apple   20  2019-3-21
2  orange  123  orange    8  2019-3-21

我的目标是回到下面;填写数量为0,但填写其他列。当然,我还有许多其他ID。我希望能够指定要填充的开始/结束日期;本示例使用3/7至3/21。

    color   id product  qty       week
0     red  123   apple   10   2019-3-7
1    blue  123   apple   20  2019-3-21
2  orange  123  orange    8  2019-3-21
3     red  123   apple    0  2019-3-14
4     red  123   apple    0  2019-3-21 
5    blue  123   apple    0   2019-3-7
6    blue  123   apple    0  2019-3-14
7  orange  123  orange    0   2019-3-7
8  orange  123  orange    0  2019-3-14

如何保持我的DataFrame的其余部分完整?

1 个答案:

答案 0 :(得分:1)

在这种情况下,您只需要使用stackreindex + df.week=pd.to_datetime(df.week) s=pd.date_range(df.week.min(),df.week.max(),freq='7 D') df=df.set_index(['color','id','product','week']).\ qty.unstack().reindex(columns=s,fill_value=0).stack().reset_index() df color id product level_3 0 0 blue 123 apple 2019-03-14 0.0 1 blue 123 apple 2019-03-21 20.0 2 orange 123 orange 2019-03-14 0.0 3 orange 123 orange 2019-03-21 8.0 4 red 123 apple 2019-03-07 10.0 5 red 123 apple 2019-03-14 0.0

ForeignKey
相关问题