【问题标题】:How to expand a DateTimeIndex with some months before?如何在几个月前扩展 DateTimeIndex?
【发布时间】:2020-10-20 17:39:47
【问题描述】:

对于某些感兴趣的日期,我有一个对应于月底的时间序列:

Date
31-01-2005  0.0
28-02-2006  0.0
30-06-2020  0.0
Name: Whatever, dtype: float64

我想在每个数据点之前使用两个月的样本来扩展此数据框的索引,从而生成以下数据框:

Date
30-11-2004  NaN
31-12-2004  NaN
31-01-2005  0.0
31-12-2005  NaN
31-01-2006  NaN
28-02-2006  0.0
30-04-2020  NaN
31-05-2020  NaN
30-06-2020  0.0
Name: Whatever, dtype: float64

我该怎么做?请注意,我只对结果索引感兴趣。

我天真的尝试是这样做的:

df.index.apply(lambda x: [x - pd.DateOffset(months=2), x - pd.DateOffset(months=1), x])

但是 index 没有 apply 功能。

【问题讨论】:

    标签: python pandas dataframe indexing time-series


    【解决方案1】:

    我认为你需要DataFrame.reindexdate_range

    idx =  [y for x in df.index for y in pd.date_range(x - pd.DateOffset(months=2), x, freq='M')]
    df = df.reindex(pd.to_datetime(idx))
    print (df)
                Whatever
    2004-11-30       NaN
    2004-12-31       NaN
    2005-01-31       0.0
    2005-12-31       NaN
    2006-01-31       NaN
    2006-02-28       0.0
    2020-04-30       NaN
    2020-05-31       NaN
    2020-06-30       0.0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-24
      • 2019-06-01
      • 1970-01-01
      • 2022-12-17
      • 1970-01-01
      相关资源
      最近更新 更多