python - Pandas 时间序列重新采样的问题

标签 python csv pandas dataframe resampling

我正在使用 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/

相关文章:

python - 为什么在显式关闭 stdout 时会出现 ValueError?

python - 在服务器运行时通过 django-admin 添加自定义权限

python - TensorFlow - nn.max_pooling 极大地增加了内存使用量

python - 在 excel 中写入 csv 文件时,特殊字符无法正确显示

python - 通过应用涉及相同行元素的函数来更新数据框的元素

python - 连接数据帧单标签行选择返回多行

python - 如何在 pyplot 中绘制每个 x 值的 y 轴平均值

ios - SwiftCSV 错误查找 .csv 文件

BASH:在特定 CSV 列中查找最大值

python - 如何将 Pandas Dataframe 转换为所需的 Json 格式