python - HDFStore.select 比 DataFrame 切片慢一个数量级?

标签 python pandas hdfstore hdf

给定一个带有整数索引和浮点列的简单 DataFrame,以下代码:

store = pd.HDFStore('test.hdf5')
print store.select('df', where='index >= 50000')['A'].mean()

比此代码至少慢 10 倍:

store = pd.HDFStore('test.hdf5')
print store.get('df')['A'][50000:].mean()

表格或固定格式不会产生巨大差异,select() 调用虽然相当于切片,但速度要慢得多。

感谢您的见解!

最佳答案

如果格式是“固定”的,您无法进行选择。这会引发异常(并且访问时间实际上快得多)。也就是说,您可以直接索引固定格式。

In [39]: df = DataFrame(np.random.randn(1000000,10))

In [40]: df.to_hdf('test.h5','df',mode='w',format='table')

In [41]: def f():
    df = pd.read_hdf('test.h5','df')
    return df.loc[50001:,0]
   ....: 

In [42]: def g():
    df = pd.read_hdf('test.h5','df')
    return df.loc[df.index>50000,0]
   ....: 

In [43]: def h():
    return pd.read_hdf('test.h5','df',where='index>50000')[0]
   ....: 

In [44]: f().equals(g())
Out[44]: True

In [46]: f().equals(h())
Out[46]: True

In [47]: %timeit f()
10 loops, best of 3: 159 ms per loop

In [48]: %timeit g()
10 loops, best of 3: 127 ms per loop

In [49]: %timeit h()
1 loops, best of 3: 499 ms per loop

肯定会慢一些。但你正在做更多的工作。这是比较 bool 索引器与整个数组。如果您阅读整个框架,那么它有很多优点(例如缓存、局部性)。

当然,如果您只是选择一个连续的切片,那么就这样做

In [59]: def i():
    return pd.read_hdf('test.h5','df',start=50001)[0]
   ....: 

In [60]: i().equals(h())
Out[60]: True

In [61]: %timeit i()
10 loops, best of 3: 86.6 ms per loop

关于python - HDFStore.select 比 DataFrame 切片慢一个数量级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27769516/

相关文章:

python - 如何将 Pandas DataFrame 存储为 HDF5 PyTables 表(或 CArray、EArray 等)?

python - Pandas HDFStore : Saving and Retrieving a Series with Hierarchical Period Index

python - 如何在 Python 中使用 R 通过 Django 返回一个 R 图?

python - 无法弄清楚 Selenium - 无法找到元素

python - Python 中的“For”循环行为

python - pandas 聚合中的自定义函数非常慢

python - Pandas :删除重复但连续的行并将第一行保留在组中

python - 我如何将 NaNs 归因为 means() 但通过多索引

python - Pandas HDFStore 从嵌套列中选择

python - 根据索引将数据帧除以另一个数据帧