Skip to main content
 首页 » 编程设计

Python pandas 使用 read_hdf 和 HDFStore.select 从 HDF5 文件中读取特定值

2024年10月25日11haluo1

所以我用一个看起来像这样的简单数据集创建了 hdf5 文件

>>> pd.read_hdf('STORAGE2.h5', 'table') 
   A  B 
0  0  0 
1  1  1 
2  2  2 
3  3  3 
4  4  4 

使用这个脚本

import pandas as pd 
import scipy as sp 
from pandas.io.pytables import Term 
 
store = pd.HDFStore('STORAGE2.h5') 
 
df_tl = pd.DataFrame(dict(A=list(range(5)), B=list(range(5)))) 
 
df_tl.to_hdf('STORAGE2.h5','table',append=True) 

我知道我可以使用选择列

x = pd.read_hdf('STORAGE2.h5', 'table',  columns=['A']) 

或

x = store.select('table', where = 'columns=A') 

我如何选择“A”列中等于 3 的所有值或特定值或“A”列中带有字符串(如“foo”)的索引?在 Pandas 数据框中,我会使用 df[df["A"]==3] 或 df[df["A"]=='foo']

另外,如果我使用 read_hdf() 或 store.select() 是否会影响效率?

请您参考如下方法:

您需要指定 data_columns=(您也可以使用 True 来使所有列都可搜索)

(仅供引用,mode='w' 将重新启动文件,这只是我的示例)

In [50]: df_tl.to_hdf('STORAGE2.h5','table',append=True,mode='w',data_columns=['A']) 
 
In [51]: pd.read_hdf('STORAGE2.h5','table',where='A>2') 
Out[51]:  
   A  B 
3  3  3 
4  4  4