填写缺失的数据 pandas

如何在此日期范围内填写缺失的数据.

在没有销售的日子里缺少值.如何在特定商店和日期售出某件商品的0天的缺失值?

输入项

Dates            Store            Item        Sales           
2017-01-01       Chicago          Apple       10
2017-01-02       NewYork          Pear        10 
2017-01-03       Chicago          Apple       10

输出量

Dates            Store            Item        Sales           
2017-01-01       Chicago          Apple       10
2017-01-01       Chicago          Pear        0
2017-01-02       Chicago          Apple       0
2017-01-02       Chicago          Pear        0
2017-01-03       Chicago          Apple       10
2017-01-03       Chicago          Pear        0    
2017-01-01       NewYork          Apple       0
2017-01-01       NewYork          Pear        0 
2017-01-02       NewYork          Apple       0 
2017-01-02       NewYork          Pear        10 
2017-01-03       NewYork          Apple       0 
2017-01-03       NewYork          Pear        0 

最佳答案

采用:

>多索引的第一个set_index
>创建新的Multiindex from_product
> reindex并为缺失值添加0
>最后排序级别按sort_indexreset_index存储

df = df.set_index(['Dates','Store','Item'])
mux = pd.MultiIndex.from_product(df.index.levels, names=df.index.names)
df = df.reindex(mux, fill_value=0).sort_index(level='Store').reset_index()
print (df)
        Dates    Store   Item  Sales
0  2017-01-01  Chicago  Apple     10
1  2017-01-01  Chicago   Pear      0
2  2017-01-02  Chicago  Apple      0
3  2017-01-02  Chicago   Pear      0
4  2017-01-03  Chicago  Apple     10
5  2017-01-03  Chicago   Pear      0
6  2017-01-01  NewYork  Apple      0
7  2017-01-01  NewYork   Pear      0
8  2017-01-02  NewYork  Apple      0
9  2017-01-02  NewYork   Pear     10
10 2017-01-03  NewYork  Apple      0
11 2017-01-03  NewYork   Pear      0