【问题标题】:Issues with Pandas Timeseries ResamplePandas 时间序列重采样的问题
【发布时间】:2016-10-03 07:32:42
【问题描述】:

我正在使用 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 bar = ticks.High.resample('60min', how='ohlc')
AttributeError: 'DataFrame' 对象没有属性 'High'

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

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

FutureWarning:如何在 .resample() 中弃用新语法是 .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 上工作。

【问题讨论】:

    标签: python csv pandas dataframe resampling


    【解决方案1】:

    列名有问题spaces

    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())
    

    【讨论】:

      猜你喜欢
      • 2014-07-24
      • 1970-01-01
      • 1970-01-01
      • 2019-01-18
      • 2015-11-07
      • 1970-01-01
      • 2014-09-29
      • 2012-11-26
      相关资源
      最近更新 更多