【问题标题】:Fill missing dates填写缺失的日期
【发布时间】:2018-06-24 21:37:57
【问题描述】:

我的数据框包含来自不同区域和不同日期的温度读数

我想为每个温度为零的位置添加缺失的日期

例如:

df=pd.DataFrame({"area_id":[1,1,1,2,2,2,3,3,3],
                 "reading_date":["13/1/2017","15/1/2017"
                                 ,"16/1/2017","22/3/2017","26/3/2017"
                                 ,"28/3/2017","15/5/2017"
                                 ,"16/5/2017","18/5/2017"],
                 "temp":[12,15,22,6,14,8,30,25,33]})

如下所示,填补每个区域的日期空白(按零)的最有效方法是什么

非常感谢。

【问题讨论】:

    标签: python pandas date datetime dataframe


    【解决方案1】:

    用途:


    df['reading_date'] = pd.to_datetime(df['reading_date'])
    
    df = (df.set_index('reading_date')
            .groupby('area_id')
            .resample('d')['temp']
            .asfreq()
            .fillna(0)
            .reset_index())
    print (df)
        area_id reading_date  temp
    0         1   2017-01-13  12.0
    1         1   2017-01-14   0.0
    2         1   2017-01-15  15.0
    3         1   2017-01-16  22.0
    4         2   2017-03-22   6.0
    5         2   2017-03-23   0.0
    6         2   2017-03-24   0.0
    7         2   2017-03-25   0.0
    8         2   2017-03-26  14.0
    9         2   2017-03-27   0.0
    10        2   2017-03-28   8.0
    11        3   2017-05-15  30.0
    12        3   2017-05-16  25.0
    13        3   2017-05-17   0.0
    14        3   2017-05-18  33.0
    

    【讨论】:

      【解决方案2】:

      使用reindex。定义一个自定义函数来处理重新索引操作,并在groupby.apply 中调用它。

      def reindex(x):
          # Thanks to @jezrael for the improvement.
          return x.reindex(pd.date_range(x.index.min(), x.index.max()), fill_value=0)
      

      接下来,先将reading_date转换为日期时间,使用pd.to_datetime,

      df.reading_date = pd.to_datetime(df.reading_date)
      

      现在,执行groupby。

      df = (
          df.set_index('reading_date')
            .groupby('area_id')
            .temp
            .apply(reindex)
            .reset_index()
      )
      
      df.columns = ['area_id', 'reading_date', 'temp']
      

      df
      
          area_id reading_date  temp
      0         1   2017-01-13  12.0
      1         1   2017-01-14   0.0
      2         1   2017-01-15  15.0
      3         1   2017-01-16  22.0
      4         2   2017-03-22   6.0
      5         2   2017-03-23   0.0
      6         2   2017-03-24   0.0
      7         2   2017-03-25   0.0
      8         2   2017-03-26  14.0
      9         2   2017-03-27   0.0
      10        2   2017-03-28   8.0
      11        3   2017-05-15  30.0
      12        3   2017-05-16  25.0
      13        3   2017-05-17   0.0
      14        3   2017-05-18  33.0
      

      【讨论】:

        猜你喜欢
        • 2018-10-05
        • 2019-06-26
        • 1970-01-01
        • 1970-01-01
        • 2018-07-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多