我有具有特定 ID 的数据集。对于特定的 ID,我想完成日期系列。因此,例如:如果我在数据集中的最大日期为:'2020-06-01'(YYYY-MM-DD) 和最小日期为:'2020-03-01' 如何在填写时填写缺失的行属性列的值
ID sale_month attribute1 attribute2
0 1 2020-06-01 blue 1
1 1 2020-05-01 blue 2
2 1 2020-04-01 blue 3
3 1 2020-03-01 blue 4
4 2 2020-05-01 yellow 5
5 2 2020-04-01 yellow 4
6 2 2020-03-01 yellow 3
7 3 2020-05-01 green 7
8 3 2020-04-01 green 8
我想实现这一点:
ID sale_month attribute1 attribute2
0 1 2020-06-01 blue 1
1 1 2020-05-01 blue 2
2 1 2020-04-01 blue 3
3 1 2020-03-01 blue 4
4 2 2020-06-01 yellow 6
5 2 2020-05-01 yellow 5
6 2 2020-04-01 yellow 4
7 2 2020-03-01 yellow 3
8 3 2020-06-01 green 6
9 3 2020-05-01 green 7
10 3 2020-04-01 green 8
11 3 2020-03-01 green 9
当没有基于 ID 的分组时,我可以通过在日期列上建立索引然后重新索引并使用插值来填充值来做到这一点。我如何在此处使用分组列执行此操作?而且,我可以对不同的列使用不同的插值方法吗?例如,复制attribute1,但在 中进行线性插值attribute2。
要复制数据框:
df = pd.DataFrame({'ID': [1, 1, 1, 1, 2, 2, 2, 3, 3],
'sale_month' : ['2020-06-01', '2020-05-01', '2020-04-01', '2020-03-01', '2020-05-01', '2020-04-01', '2020-03-01', '2020-05-01', '2020-04-01'],
'attribute1': [ 'blue', 'blue', 'blue', 'blue', 'yellow', 'yellow', 'yellow', 'green', 'green'],
'attribute2' : [1, 2, 3, 4, 5, 4, 3, 7, 8 ]})
df.sale_month = pd.to_datetime(df.sale_month)
芜湖不芜
相关分类