【问题标题】:Filling in missing data using "ffill"使用“填充”填充缺失的数据
【发布时间】:2021-05-17 13:40:04
【问题描述】:

我有以下数据

4/23/2021   493107
4/26/2021   485117
4/27/2021   485117
4/28/2021   485117
4/29/2021   485117
4/30/2021   485117
5/7/2021    484691

我希望它如下所示:

4/23/2021   493107
4/24/2021    485117
4/25/2021    485117
4/26/2021   485117
4/27/2021   485117
4/28/2021   485117
4/29/2021   485117
4/30/2021   485117
5/1/2021    484691
5/2/2021    484691
5/3/2021    484691
5/4/2021    484691
5/5/2021    484691
5/6/2021    484691
5/7/2021    484691

所以它使用下面的日期来填写缺失的数据。我尝试了以下代码:

 df['Date']=pd.to_datetime(df['Date'].astype(str), format='%m/%d/%Y')   
 df.set_index(df['Date'], inplace=True)    
 df = df.resample('D').sum().fillna(0)
 df['crude'] = df['crude'].replace({ 0:np.nan})
 df['crude'].fillna(method='ffill', inplace=True)

但是,这会导致获取上面的数据并得到以下结果:

4/23/2021   493107
4/24/2021   493107
4/25/2021   493107
4/26/2021   485117
4/27/2021   485117
4/28/2021   485117
4/29/2021   485117
4/30/2021   485117
5/1/2021    485117
5/2/2021    485117
5/3/2021    485117
5/4/2021    485117
5/5/2021    485117
5/6/2021    485117
5/7/2021    969382

这与我需要的输出不匹配。

【问题讨论】:

  • 您的预期输出看起来像 'bfill' 而不是 'ffill'。
  • 因为 OP 是 backward fill 而不是 forward

标签: python pandas dataframe missing-data ffill


【解决方案1】:

将数据框的索引设置为Date,然后使用asfreq将数据框的索引与每日频率一致/重新索引,提供填充方法作为反向填充

df.set_index('Date').asfreq('D', method='bfill')

             crude
Date              
2021-04-23  493107
2021-04-24  485117
2021-04-25  485117
2021-04-26  485117
2021-04-27  485117
2021-04-28  485117
2021-04-29  485117
2021-04-30  485117
2021-05-01  484691
2021-05-02  484691
2021-05-03  484691
2021-05-04  484691
2021-05-05  484691
2021-05-06  484691
2021-05-07  484691

【讨论】:

    【解决方案2】:

    尝试将 0 替换为 bfill 而不是 ffill

    import pandas as pd
    
    df = pd.DataFrame({
        'crude': {'4/23/2021': 493107, '4/26/2021': 485117,
                  '4/27/2021': 485117, '4/28/2021': 485117,
                  '4/29/2021': 485117, '4/30/2021': 485117,
                  '5/7/2021': 484691}
    })
    df.index = pd.to_datetime(df.index)
    
    df = df.resample('D').sum()
    
    df['crude'] = df['crude'].replace(0, method='bfill')
    
    print(df)
    

    df:

                 crude
    2021-04-23  493107
    2021-04-24  485117
    2021-04-25  485117
    2021-04-26  485117
    2021-04-27  485117
    2021-04-28  485117
    2021-04-29  485117
    2021-04-30  485117
    2021-05-01  484691
    2021-05-02  484691
    2021-05-03  484691
    2021-05-04  484691
    2021-05-05  484691
    2021-05-06  484691
    2021-05-07  484691
    

    【讨论】:

      猜你喜欢
      • 2020-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-02
      • 1970-01-01
      • 2021-10-31
      • 2012-10-25
      相关资源
      最近更新 更多