【问题标题】:python - Fill in missing dates with respect to a specific attribute in pandaspython - 填写关于熊猫中特定属性的缺失日期
【发布时间】:2017-01-24 14:02:27
【问题描述】:

我的数据如下所示:

id, date, target
1,2016-10-24,22
1,2016-10-25,31
1,2016-10-27,44
1,2016-10-28,12
2,2016-10-21,22
2,2016-10-22,31
2,2016-10-25,44
2,2016-10-27,12

我想在id中填写缺失的日期。 比如id=1的日期范围是2016-10-24~2016-10-28,缺少2016-10-26。而且id=2的日期范围是2016-10-21~2016-10-27,缺少2016-10-23、2016-10-24和2016-10-26。 我要填写缺失的日期,目标值填写为0。

因此,我希望我的数据如下:

id, date, target
1,2016-10-24,22
1,2016-10-25,31
1,2016-10-26,0
1,2016-10-27,44
1,2016-10-28,12
2,2016-10-21,22
2,2016-10-22,31
2,2016-10-23,0
2,2016-10-24,0
2,2016-10-25,44
2,2016-10-26,0
2,2016-10-27,12

有人可以帮帮我吗?

提前致谢。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以将groupbyresample 一起使用-然后是问题fillna-所以首先需要asfreq

    #if necessary convert to datetime
    df.date = pd.to_datetime(df.date)
    df = df.set_index('date')
    df = df.groupby('id').resample('d')['target'].asfreq().fillna(0).astype(int).reset_index()
    print (df)
        id       date  target
    0    1 2016-10-24      22
    1    1 2016-10-25      31
    2    1 2016-10-26       0
    3    1 2016-10-27      44
    4    1 2016-10-28      12
    5    2 2016-10-21      22
    6    2 2016-10-22      31
    7    2 2016-10-23       0
    8    2 2016-10-24       0
    9    2 2016-10-25      44
    10   2 2016-10-26       0
    11   2 2016-10-27      12
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-28
      • 2018-11-10
      • 2018-04-24
      • 2023-03-14
      相关资源
      最近更新 更多