python - 从 HDF5 获取表索引的最有效方法

标签 python hdf5 pytables h5py hdf

我有一个包含 pandas Series/DataFrame 表的 HDF5 文件。我需要获取存储在 HDF 键下的表的(pandas)索引,但不一定是整个表:

我可以想到两种(实际上相同的)获取索引的方法:

import pandas as pd

hdfPath = 'c:/example.h5'
hdfKey = 'dfkey'
# way 1:
with pd.HDFStore(hdfPath) as hdf:
    index = hdf[hdfKey].index

# way 2:
index = pd.read_hdf(hdfPath, hdfKey)

然而,对于大约 2000 行的 Pandas 系列,这需要 0.6 秒:

%timeit pd.read_hdf(hdfPath, hdfKey).index
1 loops, best of 3: 605 ms per loop

有没有办法只获取 HDF 中表的索引?

最佳答案

HDFStore 对象有一个select_column 方法,可以让您获取索引。请注意,它将返回一个以索引作为值的系列。

with pd.HDFStore(hdfPath) as hdf:
    index = hdf.select_column(hdfKey, 'index').values

关于python - 从 HDF5 获取表索引的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32740083/

相关文章:

delphi - 从 C 头文件自动创建 Delphi/Freepascal 接口(interface)单元

python - 使用 for 循环时如何查找 CSV 文件中的行中是否存在列表中的任何元素

python - 将 HDF5 用于大型阵列存储(而不是平面二进制文件)是否具有分析速度或内存使用优势?

c - 如何在Mac OS X的C程序中包含hdf5头文件?

python - 从 HDF5 文件读取和写入 numpy 数组

python - Pandas _metadata of DataFrame 持久化错误

python - Pandas HDFStore 表不接受多索引列

Python列表: index out of range?

python3 的 csv.DictReader 没有按预期按分隔符拆分记录

在 Pandas 数据帧上使用 'slicer' 和 'where' 等效项的 Pythonic 方式