【问题标题】:Enlarging date range of dataframe扩大数据框的日期范围
【发布时间】:2018-10-24 03:54:38
【问题描述】:

我有一个由这段代码生成的数据框:

df_ = pd.DataFrame([['2018-02-05', '2018-02-11', '2018-02-12'], [77, 77, 77]]).transpose()
df_.set_index(keys = 0, inplace = True)

我想基于df_ 创建一个跨越以下日期范围的数据框

start_date = pd.to_datetime('2018-02-01')
end_date = start_date + pd.DateOffset(months=1) - pd.DateOffset(days=14)
index_ = pd.date_range(start_date, end_date)

df_ 中的缺失值应该用零填充。他们是一种快速的方法吗,无需将index_ 转换为数据框,然后应用pd.mergepd.concat 之类的东西?

谢谢,如果您需要更多信息,请告诉我。

【问题讨论】:

    标签: python pandas merge concatenation


    【解决方案1】:

    如果index_ 和原始df.index 中的所有值都是唯一的,我认为需要转换索引to_datetime 然后使用reindex

    df_.index = pd.to_datetime(df_.index)
    df = df_.reindex(index_, fill_value=0)
    print (df)
                 1
    2018-02-01   0
    2018-02-02   0
    2018-02-03   0
    2018-02-04   0
    2018-02-05  77
    2018-02-06   0
    2018-02-07   0
    2018-02-08   0
    2018-02-09   0
    2018-02-10   0
    2018-02-11  77
    2018-02-12  77
    2018-02-13   0
    2018-02-14   0
    2018-02-15   0
    

    【讨论】:

      猜你喜欢
      • 2018-02-20
      • 1970-01-01
      • 1970-01-01
      • 2020-05-19
      • 2015-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多