我有一个 30 分钟时间间隔的 OHLC 数据帧。
2017-04-30 11:00:00-04:00 239.06 239.39 239.04 239.33 28
2017-04-30 11:30:00-04:00 239.01 239.22 238.91 239.03 28
2017-04-30 12:00:00-04:00 239.02 239.28 238.99 239.03 29
2017-04-30 12:30:00-04:00 238.94 239.08 238.84 239.03 28
2017-04-30 13:00:00-04:00 239.01 239.11 238.93 238.94 27
2017-04-30 13:30:00-04:00 238.94 239.08 238.86 239.03 12
我想对每小时柱中的数据进行重新采样,但有没有办法将每小时柱定义为每 30 分钟结束一次,例如 9:30-10:30
与 9:00 -10:00
?
最佳答案
要重新采样到采样周期的偏移量,请使用 base
参数 ( resample )
base : int, default 0
For frequencies that evenly subdivide 1 day, the “origin” of the aggregated intervals. For example, for ‘5min’ frequency, base could range from 0 through 4. Defaults to 0
代码:
df = df.resample('1H', base=0.5).last()
测试代码:
df = pd.read_fwf(StringIO(u"""
Date O H L C
2017-04-30T11:00:00-0400 239.06 239.39 239.04 239.33
2017-04-30T11:30:00-0400 239.01 239.22 238.91 239.03
2017-04-30T12:00:00-0400 239.02 239.28 238.99 239.03
2017-04-30T12:30:00-0400 238.94 239.08 238.84 239.03
2017-04-30T13:00:00-0400 239.01 239.11 238.93 238.94
2017-04-30T13:30:00-0400 238.94 239.08 238.86 239.03"""
), header=1)
df['Date'] = pd.to_datetime(df['Date'])
df = df.set_index('Date')
df = df.resample('1H', base=0.5).last()
print(df)
结果:
O H L C
Date
2017-04-30 14:30:00 239.06 239.39 239.04 239.33
2017-04-30 15:30:00 239.02 239.28 238.99 239.03
2017-04-30 16:30:00 239.01 239.11 238.93 238.94
2017-04-30 17:30:00 238.94 239.08 238.86 239.03
关于python - pandas 使用用户定义的时间间隔重新采样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43709608/