的hdf5
文件必须在table
format被写入 为了可查询与pd.read_hdf
的where
参数(相对于fixed
格式)。
此外,A
必须declared as a data_column:
df.to_hdf('/tmp/out.h5', 'results_table', mode='w', data_columns=['A'],
format='table')
,或者指定所有的列(可查询)的数据列:
df.to_hdf('/tmp/out.h5', 'results_table', mode='w', data_columns=True,
format='table')
那么你可以使用
pd.read_hdf('/tmp/out.h5', 'results_table', where='A in [1,3,4]')
到选择值列A
为1,3或4的行例如,
import numpy as np
import pandas as pd
df = pd.DataFrame({
'A': [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2],
'B': [0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1],
'C': [34, 32, 35, 34, 31, 34, 29, 34, 12, 34, 32, 34],
'D': [11, 15, 22, 15, 9, 15, 11, 15, 14, 15, 13, 15]})
df.to_hdf('/tmp/out.h5', 'results_table', mode='w', data_columns=['A'],
format='table')
print(pd.read_hdf('/tmp/out.h5', 'results_table', where='A in [1,3,4]'))
产生
A B C D
0 1 0 34 11
2 3 1 35 22
3 4 1 34 15
5 1 0 34 15
7 3 0 34 15
8 4 1 12 14
10 1 0 32 13
如果你有一个很长的值,vals
的名单,那么你可以使用字符串格式化来构成权where
说法:
where='A in {}'.format(vals)
感谢unutbu,对这个很好的答案只是一些评论。我明白,在答案开始时,你以表格格式将df写入h5。然而,我的脚本的输入是已经保存的h5,我怎么知道它是否在正确的格式? – codeKiller
如果你的'h5'文件不是'table'格式,那么使用带'where'参数的'pd.read_hdf'会引发'TypeError:当从固定格式读取时不能通过where规范...'。如果'h5'文件是''表'格式的'A'没有被指定为'data_column',那么你会得到'ValueError:通过where表达式:A [1,3,4]包含一个无效变量参考...'。 – unutbu
我不知道将h5文件从'fixed'转换为'table'格式或者添加'data_columns'的快捷方式。据我所知,你必须将整个'h5'文件读入一个DataFrame(或者使用'chunksize'参数以chunks的形式读取),然后写出或附加到另一个'h5'文件中'表格式。 – unutbu