使用条件将HDF5文件读入pandas DataFrame

11

我有一个非常大的HDF5文件,我想在pandas DataFrame中加载其中一部分以执行某些操作,但我只想筛选出一些行。

以下是一个示例:

原始的HDF5文件可能看起来像这样:

A    B    C    D
1    0    34   11
2    0    32   15
3    1    35   22
4    1    34   15
5    1    31   9
1    0    34   15
2    1    29   11
3    0    34   15
4    1    12   14
5    0    34   15
1    0    32   13
2    1    34   15
etc  etc  etc  etc
我想要做的是将这个内容完全加载到pandas Dataframe中,但只在A等于1、3或4时加载。
到目前为止,我只能使用以下方法来加载整个HDF5:
store = pd.HDFStore('Resutls2015_10_21.h5')
df = pd.DataFrame(store['results_table'])

我不知道如何在这里加入where条件。

2个回答

12

为了使用pd.read_hdfwhere参数进行查询,hdf5文件必须以table格式(而不是fixed格式)编写。

此外,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的行。例如:

要选择数值列 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)

1
谢谢unutbu,对这个好答案有一些评论。我理解你在回答开始时将df以表格格式写入h5中。然而,我的脚本的输入是已经保存的h5,我怎么知道它是否是正确的格式? - codeKiller
如果您的 h5 文件不是以 table 格式保存的,那么使用带有 where 参数的 pd.read_hdf 将会引发 TypeError: cannot pass a where specification when reading from a Fixed format... 错误。 如果 h5 文件是采用 table 格式保存的,但没有将 A 指定为 data_column,那么你将会得到 ValueError: The passed where expression: A in [1,3,4] contains an invalid variable reference... 的错误提示。 - unutbu
我不知道有什么快速/简便的方法可以将一个fixed格式的h5文件转换为table格式,或者添加data_columns。据我所知,您需要将整个h5文件读入DataFrame中(或者使用chunksize参数分块读取),然后将其写出或附加到另一个以table格式存储的h5文件中。 - unutbu

1
你可以使用 pandas.read_hdf (这里) 来完成,还有一个可选参数 where
例如: read_hdf('store_tl.h5', 'table', where = ['index>2'])

谢谢Dean,是否可能包含更复杂的条件?例如,如果我的A列具有1到100的值,并且我想选择一些随机的值,如[1,3,11,16,27,33,34,44,41,55,68,70,77,81,90] ... 我之所以问这个问题,是因为在主要问题中我希望它容易理解,但在我的实际情况中,“where”条件需要更加复杂。 - codeKiller
找到了您需要传递给where的Expr的文档:http://nullege.com/codes/search/pandas.computation.pytables.Expr?fulldoc=1(尽管我没有看到按包含过滤的选项,但这可能会有所帮助)。 - Dean Fenster

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接