【问题标题】:Dataframe: Add new rows for missing dates [duplicate]数据框:为缺少的日期添加新行[重复]
【发布时间】:2021-10-20 16:58:01
【问题描述】:

我有以下 pandas df,以日期为索引:

              S&P500    Europe     Japan
Date                                    
2002-12-23  0.247683  0.245252  0.203916
2002-12-24  0.241855  0.237858  0.200971
2002-12-26  0.237095  0.230614  0.197621
2002-12-27  0.241104  0.250323  0.191855

我需要为每个缺失的日期添加新行(考虑到 df 的第一个日期和最后一个日期之间的日期)。对于新行,列中的值应向前填充。这是预期的输出(正在添加 2002-12-25):

              S&P500    Europe     Japan
Date                                    
2002-12-23  0.247683  0.245252  0.203916
2002-12-24  0.241855  0.237858  0.200971
2002-12-25  0.241855  0.237858  0.200971
2002-12-26  0.237095  0.230614  0.197621
2002-12-27  0.241104  0.250323  0.191855

我创建了第一个和最后一个日期之间所有日期的列表:

min_date=df.index.min()
max_date=df.index.max()
date_list=pd.date_range(min_date,max_date-timedelta(days=1),freq='d')

有没有办法检查“date_list”的哪些日期不在 df 索引中并相应地添加行?新行的列应该用 NaN 填充,以便我以后可以向前填充它们。 谢谢

【问题讨论】:

    标签: python pandas dataframe date


    【解决方案1】:

    你可以使用.reindex + .ffill():

    min_date = df.index.min()
    max_date = df.index.max()
    date_list = pd.date_range(min_date, max_date, freq="D")
    
    df = df.reindex(date_list).ffill()
    print(df)
    

    打印:

                  S&P500    Europe     Japan
    2002-12-23  0.247683  0.245252  0.203916
    2002-12-24  0.241855  0.237858  0.200971
    2002-12-25  0.241855  0.237858  0.200971
    2002-12-26  0.237095  0.230614  0.197621
    2002-12-27  0.241104  0.250323  0.191855
    

    或者:使用method=参数

    df = df.reindex(date_list, method="ffill")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-06
      • 1970-01-01
      • 1970-01-01
      • 2016-08-11
      • 2020-05-16
      • 1970-01-01
      • 1970-01-01
      • 2021-04-06
      相关资源
      最近更新 更多