我有一个日期列表和一个数据框架。现在,dataframe有一个id列和其他值,这些值在所有日期都不一致。我希望在没有数据的is和日期的所有列中填充零。让我通过示例向您展示:
date id clicks conv rev
2019-01-21 234 34 1 10
2019-01-21 235 32 0 0
2019-01-24 234 56 2 20
2019-01-23 235 23 3 30
日期列表如下所示:
[2019-01-01, 2019-01-02,2019-01-03 ....2019-02-28]
我想要的是为所有in的dataframe中的所有缺失日期添加零。因此,生成的df应该如下所示:
date id clicks conv rev
2019-01-01 234 0 0 0
2019-01-01 235 0 0 0
. . . .
. . . .
2019-01-21 234 34 1 10
2019-01-21 235 32 0 0
2019-01-22 234 0 0 0
2019-01-22 235 0 0 0
2019-01-23 234 0 0 0
2019-01-23 235 0 0 0
2019-01-24 234 56 2 20
2019-01-23 235 23 3 30
. . . .
2019-02-28 0 0 0 0
发布于 2019-04-28 01:26:06
值的笛卡尔乘积中的set_index
+ reindex
。在这里,我将使用pd.date_range
创建日期,以节省一些输入,并确保日期为datetime
import pandas as pd
df['date'] = pd.to_datetime(df.date)
my_dates = pd.date_range('2019-01-01', '2019-02-28', freq='D')
idx = pd.MultiIndex.from_product([my_dates, df.id.unique()], names=['date', 'id'])
df = df.set_index(['date', 'id']).reindex(idx).fillna(0).reset_index()
输出:df
date id clicks conv rev
0 2019-01-01 234 0.0 0.0 0.0
1 2019-01-01 235 0.0 0.0 0.0
...
45 2019-01-23 235 23.0 3.0 30.0
46 2019-01-24 234 56.0 2.0 20.0
47 2019-01-24 235 0.0 0.0 0.0
...
115 2019-02-27 235 0.0 0.0 0.0
116 2019-02-28 234 0.0 0.0 0.0
117 2019-02-28 235 0.0 0.0 0.0
https://stackoverflow.com/questions/55883057
复制相似问题