【问题标题】:Adding index in between two datetime indexes在两个日期时间索引之间添加索引
【发布时间】:2019-09-23 01:19:15
【问题描述】:

数据框:我有一个日期时间索引,但它缺少每天的 17:00。我如何每天添加额外的yyyy-mm-dd 17:00 行?

如果我有,请说:

                price
2017-01-01 16:55  1.2
2017-01-01 17:05  2.3
2017-01-01 17:10  3.4
.
.
.
2019-01-01 16:55  23
2019-01-01 17:05  29
2019-01-01 17:10  20

我想在 17:00 用NaNs 添加行,这样我就有了

2017-01-01 16:55  1.2
2017-01-01 17:00  NaN
2017-01-01 17:05  2.3
2017-01-01 17:10  3.4

【问题讨论】:

    标签: python pandas dataframe datetime time


    【解决方案1】:

    使用reindex:

    from io import StringIO
    # sample data
    s = """date_time,price
    2017-01-01 16:55,1.2
    2017-01-01 17:05,2.3
    2017-01-01 17:10,3.4"""
    
    df = pd.read_csv(StringIO(s))
    df['date_time'] = pd.to_datetime(df['date_time'])
    df = df.set_index('date_time')
    
    # create a date range with the index min and max and set to whatever freq you would like
    new_idx = pd.date_range(df.index.min(), df.index.max(), freq='5T')
    df.reindex(new_idx)
    
                        price
    2017-01-01 16:55:00   1.2
    2017-01-01 17:00:00   NaN
    2017-01-01 17:05:00   2.3
    2017-01-01 17:10:00   3.4
    

    【讨论】:

      【解决方案2】:

      由于你有不同的date,所以这里需要groupby,而我使用的是resample

      df.groupby(df.index.date).apply(lambda x : x.resample('5 min').mean()).reset_index(level=0,drop=True)
      Out[13]: 
                           price
      date_time                 
      2017-01-01 16:55:00    1.2
      2017-01-01 17:00:00    NaN
      2017-01-01 17:05:00    2.3
      2017-01-01 17:10:00    3.4
      

      【讨论】:

        猜你喜欢
        • 2017-11-16
        • 1970-01-01
        • 2014-03-07
        • 2018-02-25
        • 1970-01-01
        • 2020-03-11
        • 2017-05-22
        • 2015-12-08
        • 1970-01-01
        相关资源
        最近更新 更多