我正在使用 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
这是为什么?
此外,笔记本显示创建的另一个对象:
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 上工作。 .
最佳答案
列名称中存在问题空格
。
print (data.columns)
Index(['Timestamp', ' Open', ' High', ' Low', ' Last', ' Volume',
' NumberOfTrades', ' BidVolume', ' AskVolume'],
dtype='object')
您可以strip
这个空格:
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'))
如果您不想删除空格,请在列名称中添加空格:
print (ticks[' Price'].resample('1min', how='ohlc'))
但更好的是使用 Resampler.ohlc
,如果 pandas
版本高于 0.18.0
:
print (ticks.Price.resample('1min').ohlc())
关于python - Pandas 时间序列重新采样的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37610893/