将时间序列数据以相等的间隔存入df

时间:2019-02-13 11:51:34

标签: python dataframe time-series

我有一个带有时间序列数据的DataFrame,如下所示:

Date                Value
2019-02-10 00:00:00 9661
2019-02-10 00:00:19 9654
2019-02-10 00:45:20 9659
2019-02-10 01:01:20 9649
2019-02-10 01:30:18 9712

是否有一种简单的方法可以将数据转换为相等的间隔? (精确到每15分钟一次)

每个时间步将获得该步内值的平均值

1 个答案:

答案 0 :(得分:1)

我认为您需要resamplemean

print (df.index)
DatetimeIndex(['2019-02-10 00:00:00', '2019-02-10 00:00:19',
               '2019-02-10 00:45:20', '2019-02-10 01:01:20',
               '2019-02-10 01:30:18'],
              dtype='datetime64[ns]', name='Date', freq=None)

df = df.resample('15Min').mean()
print (df)
                      Value
Date                       
2019-02-10 00:00:00  9657.5
2019-02-10 00:15:00     NaN
2019-02-10 00:30:00     NaN
2019-02-10 00:45:00  9659.0
2019-02-10 01:00:00  9649.0
2019-02-10 01:15:00     NaN
2019-02-10 01:30:00  9712.0

对于缺少的时间间隔,请获取错误的值,因此如有必要,请使用dropna将其删除:

df = df.resample('15Min').mean().dropna(how='all')
print (df)
                      Value
Date                       
2019-02-10 00:00:00  9657.5
2019-02-10 00:45:00  9659.0
2019-02-10 01:00:00  9649.0
2019-02-10 01:30:00  9712.0
相关问题