Pandas 时间序列重采样问题

Issues with Pandas Timeseries Resample

我正在使用 python 3.5.1 和 Pandas 0.18.0 并尝试使用此 notebook 修改金融报价数据,因为我对这些练习很感兴趣:

我在使用某些命令时遇到问题,想知道这是否是由于 python 和 pandas 的版本所致?

例如:

这是我正在阅读的文件以及相关输出:

data = pd.read_csv('test30dayes2tickforpython.csv',index_col=0,        header=0,parse_dates={"Timestamp" : [0,1]})
data.dtypes
Out[80]:
 Open              float64
 High              float64
 Low               float64
 Last              float64
 Volume              int64
 NumberOfTrades      int64
 BidVolume           int64
 AskVolume           int64
dtype: object

当我尝试创建另一个这样的对象时:

ticks = data.ix[:, ['High','Volume']]
ticks

我得到 NaN 值:

    High    Volume
Timestamp       
2015-12-27 23:00:25.000 NaN NaN
2015-12-27 23:01:11.000 NaN NaN

但如果我使用列引用而不是名称,它会起作用:

ticks = data.ix[:, [1,4]]
ticks


High    Volume
Timestamp       
2015-12-27 23:00:25.000 2045.25 1
2015-12-27 23:01:11.000 2045.50 2

这是为什么?

另外,notebook 显示了另一个创建的对象:

bars = ticks.Price.resample('1min', how='ohlc')
bars

当我尝试这个时,我得到了这个错误:

bars = ticks.High.resample('60min', how='ohlc')
bars

1 bars = ticks.High.resample('60min', how='ohlc')
AttributeError: 'DataFrame' object has no attribute 'High'

如果我不调用 High 列,它会起作用:

bars = ticks.resample('60min', how='ohlc')
bars

FutureWarning: how in .resample() is deprecated the new syntax is .resample(...).ohlc()

High    Volume
open    high    low close   open    high    low close
Timestamp                               
2015-12-27 23:00:00 2045.25 2047.75 2045.25 2045.25 1.0 7.0 1.0 5.0

请问正确的命令是什么?

我很感激该笔记本可能不适用于我使用的 Python/Pandas 版本,但作为新手,它对我来说非常有用,所以我想在我的 data 上使用它。

列名称中存在问题 spaces

print (data.columns)
Index(['Timestamp', ' Open', ' High', ' Low', ' Last', ' Volume',
       ' NumberOfTrades', ' BidVolume', ' AskVolume'],
      dtype='object')

您可以 strip 这个 spaces:

data.columns = data.columns.str.strip()
print (data.columns)
Index(['Timestamp', 'Open', 'High', 'Low', 'Last', 'Volume', 'NumberOfTrades',
       'BidVolume', 'AskVolume'],
      dtype='object')

ticks = data.ix[:, ['High','Volume']]
print (ticks.head())
      High  Volume
0  2045.25       1
1  2045.50       2
2  2045.50       2
3  2045.50       2
4  2045.50       2

现在您可以使用:

print (ticks.Price.resample('1min', how='ohlc'))

如果您不想删除 space,请将 space 添加到列名称:

print (ticks[' Price'].resample('1min', how='ohlc'))

但更好的是使用 Resampler.ohlc,如果 pandas 版本高于 0.18.0:

print (ticks.Price.resample('1min').ohlc())