首页 > 解决方案 > 以每小时间隔插入 15 分钟的日期时间

问题描述

我有一个包含 3 列的数据框,其中第一列是日期时间。

看起来像这样

Datetime            Level1   Level2
2016-02-24 01:00    12       15
2016-02-24 02:00    14       13
2016-02-24 03:00    8        12

现在我想在每小时值之间添加 15 分钟的间隔值。但是,Level1 和 Level2 的值与其前一小时相同。它应该如下所示:

Datetime            Level1   Level2
2016-02-24 01:00    12       15
2016-02-24 01:15    12       15
2016-02-24 01:30    12       15
2016-02-24 01:45    12       15
2016-02-24 02:00    14       13
2016-02-24 02:15    14       13
2016-02-24 02:30    14       13
2016-02-24 02:45    14       13
2016-02-24 03:00    8        12
2016-02-24 03:15    8        12
2016-02-24 03:30    8        12
2016-02-24 03:45    8        12

我想不出如何正确地做到这一点。

标签: pythonpandasdatetime

解决方案


将日期时间设置为索引(在转换为日期时间之后),并使用带有前向填充的 asfreq 方法用以前的值填充空值:

#thanks to @a_guest for the cleaned sample data

df = pd.DataFrame(
    data=[['2016-02-24 01:00', 12, 15],
          ['2016-02-24 02:00', 14, 13],
          ['2016-02-24 03:00',  8, 12]],
    columns=['Datetime', 'Level1', 'Level2']
)
df['Datetime'] = pd.to_datetime(df['Datetime'])

df = df.set_index('Datetime')

df.asfreq('15min',method='pad')

                 Level1 Level2
Datetime        
2016-02-24 01:00:00 12  15
2016-02-24 01:15:00 12  15
2016-02-24 01:30:00 12  15
2016-02-24 01:45:00 12  15
2016-02-24 02:00:00 14  13
2016-02-24 02:15:00 14  13
2016-02-24 02:30:00 14  13
2016-02-24 02:45:00 14  13
2016-02-24 03:00:00 8   12

注意:您的问题说时间间隔为 15 分钟,您的最新时间是下午 3 点,而不是下午 4 点,正如您的数据中共享的那样。


推荐阅读