【发布时间】:2017-04-15 06:26:33
【问题描述】:
所以,我是 Pandas 包的新手。 我正在对 ETF 的策略进行一些回测,我需要对 Pandas Dataframe 进行大量查询。
假设我是这两个 DataFrame,df 和 df1,唯一的区别是: df 有日期时间索引,而 df1 有时间戳作为列和整数索引
In[104]: df.head()
Out[104]:
high low open close volume openInterest
2007-04-24 09:31:00 148.28 148.12 148.23 148.15 2304400 341400
2007-04-24 09:32:00 148.21 148.14 148.14 148.19 2753500 449100
2007-04-24 09:33:00 148.24 148.13 148.18 148.14 2863400 109900
2007-04-24 09:34:00 148.18 148.12 148.13 148.16 3118287 254887
2007-04-24 09:35:00 148.17 148.14 148.16 148.16 3202112 83825
In[105]: df1.head()
Out[105]:
dates high low open close volume openInterest
0 2007-04-24 09:31:00 148.28 148.12 148.23 148.15 2304400 341400
1 2007-04-24 09:32:00 148.21 148.14 148.14 148.19 2753500 449100
2 2007-04-24 09:33:00 148.24 148.13 148.18 148.14 2863400 109900
3 2007-04-24 09:34:00 148.18 148.12 148.13 148.16 3118287 254887
4 2007-04-24 09:35:00 148.17 148.14 148.16 148.16 3202112 83825
所以我稍微测试一下查询速度:
In[100]: %timeit df1[(df1['dates'] >= '2015-11-17') & (df1['dates'] < '2015-11-18')]
%timeit df.loc[(df.index >= '2015-11-17') & (df.index < '2015-11-18')]
%timeit df.loc['2015-11-17']
100 loops, best of 3: 4.67 ms per loop
100 loops, best of 3: 3.14 ms per loop
1 loop, best of 3: 259 ms per loop
令我惊讶的是,使用 Pandas 内置的逻辑实际上是最慢的:
df.loc['2015-11-17']
有谁知道这是为什么? 有没有关于查询 Pandas DataFrame 的最有效方法的文档或博客?
【问题讨论】:
标签: python datetime pandas dataframe