Skip to main content
 首页 » 编程设计

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

2025年05月04日29mayingbao

我有一个包含 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