python - 有条件地将 HDF5 文件读取到 pandas DataFrame

标签 python pandas hdf5

我有一个巨大的 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,但只是 where A==1 or 3 or 4

到目前为止,我可以使用以下方法加载整个 HDF5:

store = pd.HDFStore('Resutls2015_10_21.h5')
df = pd.DataFrame(store['results_table'])

我不知道如何在此处包含 where 条件。

最佳答案

hdf5 文件必须写入 table format (相对于 fixed 格式)在 为了可以使用 pd.read_hdfwhere 参数进行查询。

此外,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)

关于python - 有条件地将 HDF5 文件读取到 pandas DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33451926/

相关文章:

python - H5py 存储字符串列表列表

python - 谷歌 Colab 错误 : Buffered data was truncated after reaching the output size limit

python - 如何将 Numpy 数组转换为 Panda DataFrame

python - 类型错误 : super() takes at least 1 argument (0 given) error is specific to any python version?

python - 在 Pandas 中传播条件列值

python - 在python中获取系统本地时区

python - 将 .mdb 文件转换为 numpy 或 hdf5

python - 使用带有 DateTimeIndex 项的 select 从 HDFStore 检索 Pandas DataFrame 时缺少一个值

python - crontab启动用pip安装的gunicorn,找不到命令

python - 如何使用Python和Selenium库与深度嵌套的 'input' html对象交互