使用单个
DatetimeIndex
然后
groupby
+
resample.asfreq()
,(可以对数字列使用sum),因为日期范围取决于组。
import pandas as pd
df['Date'] = pd.to_datetime(df.Date)
df = df.set_index('Date')
df.groupby(['Product', 'eCommerce'], sort=False).Sales.resample('D').sum().reset_index()
如果有许多列要用零填充,则:
(df.groupby(['Product', 'eCommerce'], sort=False)
.resample('D').sum()
.drop(columns=['Product', 'eCommerce'])
.reset_index())
输出:
Product eCommerce Date Sales
0 A 1 2018-12-10 10
1 A 1 2018-12-11 0
2 A 1 2018-12-12 0
3 A 1 2018-12-13 4
4 A 1 2018-12-14 0
5 A 1 2018-12-15 2
6 A 0 2018-12-12 7
7 A 0 2018-12-13 0
8 A 0 2018-12-14 0
9 A 0 2018-12-15 2
10 B 1 2018-12-11 8
11 B 1 2018-12-12 0
12 B 1 2018-12-13 6