完成按熊猫中另一列分组的日期系列并填充缺失的行

我有具有特定 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)


斯蒂芬大帝
浏览 102回答 1
1回答

芜湖不芜

您可以MultiIndex.from_product使用pd.date_range:dates = pd.date_range(df["sale_month"].min(), df["sale_month"].max(), freq="MS")s = pd.MultiIndex.from_product([df["ID"].unique(), reversed(dates)],names=df.columns[:2])df = df.set_index(["ID","sale_month"]).reindex(s).reset_index()df["attribute1"] = df.groupby('ID')["attribute1"].transform("first")print (df)    ID sale_month attribute1  attribute20    1 2020-06-01       blue         1.01    1 2020-05-01       blue         2.02    1 2020-04-01       blue         3.03    1 2020-03-01       blue         4.04    2 2020-06-01     yellow         NaN5    2 2020-05-01     yellow         5.06    2 2020-04-01     yellow         4.07    2 2020-03-01     yellow         3.08    3 2020-06-01      green         NaN9    3 2020-05-01      green         7.010   3 2020-04-01      green         8.011   3 2020-03-01      green         NaN
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python