Pandas重新采样错误:仅适用于DatetimeIndex、TimedeltaIndex或PeriodIndex。

56

使用 pandas 的 resample 函数将 tick 数据转换为 OHLCV 时,会遇到重新采样错误。

我们应该如何解决这个错误?

enter image description here

# Resample data into 30min bins
bars = data.Price.resample('30min', how='ohlc')
volumes = data.Volume.resample('30min', how='sum')

这会产生错误:

TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Int64Index'
2个回答

74

将索引中的整数时间戳转换为DatetimeIndex:

data.index = pd.to_datetime(data.index, unit='s')

这将整数解释为自纪元以来的秒数。


例如,给定

data = pd.DataFrame(
    {'Timestamp':[1313331280, 1313334917, 1313334917, 1313340309, 1313340309], 
     'Price': [10.4]*3 + [10.5]*2, 'Volume': [0.779, 0.101, 0.316, 0.150, 1.8]})
data = data.set_index(['Timestamp'])
#             Price  Volume
# Timestamp                
# 1313331280   10.4   0.779
# 1313334917   10.4   0.101
# 1313334917   10.4   0.316
# 1313340309   10.5   0.150
# 1313340309   10.5   1.800

data.index = pd.to_datetime(data.index, unit='s')
产量
                     Price  Volume
2011-08-14 14:14:40   10.4   0.779
2011-08-14 15:15:17   10.4   0.101
2011-08-14 15:15:17   10.4   0.316
2011-08-14 16:45:09   10.5   0.150
2011-08-14 16:45:09   10.5   1.800

然后

ticks = data.ix[:, ['Price', 'Volume']]
bars = ticks.Price.resample('30min').ohlc()
volumes = ticks.Volume.resample('30min').sum()

可以计算:

In [368]: bars
Out[368]: 
                     open  high   low  close
2011-08-14 14:00:00  10.4  10.4  10.4   10.4
2011-08-14 14:30:00   NaN   NaN   NaN    NaN
2011-08-14 15:00:00  10.4  10.4  10.4   10.4
2011-08-14 15:30:00   NaN   NaN   NaN    NaN
2011-08-14 16:00:00   NaN   NaN   NaN    NaN
2011-08-14 16:30:00  10.5  10.5  10.5   10.5

In [369]: volumes
Out[369]: 
2011-08-14 14:00:00    0.779
2011-08-14 14:30:00      NaN
2011-08-14 15:00:00    0.417
2011-08-14 15:30:00      NaN
2011-08-14 16:00:00      NaN
2011-08-14 16:30:00    1.950
Freq: 30T, Name: Volume, dtype: float64

2
由于它是为时序数据设计的,因此正如错误提示所说,仅当索引为日期时间、时间增量或周期时,resample()才能正常工作。以下是这种错误可能出现的几种常见方式。
但是,您也可以使用on=参数来使用列作为分组器,而不需要具有日期时间索引。
df['Timestamp'] = pd.to_datetime(df['Timestamp'], unit='s')
bars = df.resample('30min', on='Timestamp')['Price'].ohlc()
volumes = df.resample('30min', on='Timestamp')['Volume'].sum()

res1


如果您有一个多级索引的数据框,其中一个索引是日期时间,则可以使用level=将该级别选择为分组器。
volumes = df.resample('30min', level='Timestamp')['Volume'].sum()

res2


您还可以使用resample.agg来传递多个方法。

resampled = df.resample('30min', on='Timestamp').agg({'Price': 'ohlc', 'Volume': 'sum'})

res3


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接