首页 > 解决方案 > 如何根据日期和两列的组合将缺失的行添加到 pandas DataFrame?

问题描述

我有一个场景,其中我有一个包含 4 列的数据框:

date, product, store, sales_amt

1/1/2019, A,A,200

1/1/2019,A,B,120

1/2/2019, A,A,75

1/3/2019,A,A,69

1/3/2019,A,B,23

--
--
--

1/31/2019,A,B,49

这些日期应该跨越一整个月(例如,在本例中为 2019 年 1 月),但数据框中缺少一些日期。

有没有人有关于 Python 代码的任何提示,可以遍历特定月份的日期并向数据框中添加缺少date, product/store组合且 asales_amt为零的新行?

product例如,2019 年 1 月 2 日 A/B 的/store组合没有条目。

最后的目标是为每个product/store组合在该月的每一天都有一个条目。

我怎样才能做到这一点?

标签: pythonpandas

解决方案


使用resampleset_index

#create a dummy dataframe with data every other day
s=pd.date_range('2019-01-01', '2019-05-01', freq='2D')
df = pd.DataFrame({'Date':s, 'sales_amt':np.random.randint(100,1000,61)})

df.set_index('Date').resample('D').asfreq().fillna(0)

输出:

            sales_amt
Date                 
2019-01-01      996.0
2019-01-02        0.0
2019-01-03      236.0
2019-01-04        0.0
2019-01-05      225.0
...               ...
2019-04-27      444.0
2019-04-28        0.0
2019-04-29      756.0
2019-04-30        0.0
2019-05-01      641.0

推荐阅读