【问题标题】:how to fill a time series dataframe until end of month如何填充时间序列数据框直到月底
【发布时间】:2020-10-20 15:33:13
【问题描述】:

我有一个数据框,其中索引是日期(每天,跳过周末)。这些数据是从 API 下载的,用于进一步的财务分析,但是分析/代码仅在日期索引中的最后一天是月底时运行,如果不是,我希望代码找到月底并填充数据框使用每列的最后一个可用值,将今天的日期到月底的日期。

所以我有:

     Date          Value
      ...         ...
  2020-06-23       7
  2020-06-24       7.1
  2020-06-25       7
  2020-06-26       7.3 (assume today)

我想要的是:

     Date          Value
      ...         ...
  2020-06-23       7
  2020-06-24       7.1
  2020-06-25       7
  2020-06-26       7.3 
  2020-06-29       7.3 
  2020-06-30       7.3

跳过周末。谢谢。路易吉

【问题讨论】:

  • 对不起我的错误,我编辑了

标签: python-3.x pandas dataframe time-series python-datetime


【解决方案1】:

使用DataFrame.reindex 转换为月末日期的最大日期时间,然后使用boolean indexingDatetimeIndex.weekday 删除周末:

df['Date'] = pd.to_datetime(df['Date'])
df = df.set_index('Date')

idx = pd.date_range(df.index.min(), df.index.max().to_period('M').to_timestamp('M'))
df = df.reindex(idx, method='ffill')
df = df[df.index.weekday < 5]
print (df)
            Value
2020-06-23    7.0
2020-06-24    7.1
2020-06-25    7.0
2020-06-26    7.3
2020-06-29    7.3
2020-06-30    7.3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-16
    • 2018-07-24
    • 2021-12-05
    • 2021-08-11
    • 2018-08-13
    • 1970-01-01
    • 2013-01-13
    • 1970-01-01
    相关资源
    最近更新 更多