在有条件的情况下将HDF5文件读取到pandas数据帧

2024-06-25 23:50:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个巨大的HDF5文件,我想把它的一部分加载到pandas数据框中来执行一些操作,但是我对过滤一些行很感兴趣。

我可以用一个例子来更好地解释:

原始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数据框中,但只加载where A==1 or 3 or 4

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

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

我不知道如何在这里包含where条件。


Tags: or文件数据store命令pandasdfetc
1条回答
网友
1楼 · 发布于 2024-06-25 23:50:48

hdf5文件必须以^{} 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)
网友
2楼 · 发布于 2024-06-25 23:50:48

您可以使用pandas.read_hdfhere)和可选参数where来完成此操作。
对于exampleread_hdf('store_tl.h5', 'table', where = ['index>2'])

相关问题 更多 >