2015-10-31 55 views
6

我有一个巨大的HDF5文件,我想加载它的一部分在一个熊猫DataFrame中执行一些操作,但我有兴趣过滤一些行。用条件读取HDF5文件到熊猫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 

我所试图做的是加载此,正是因为它是一个熊猫据帧,但只有where A==1 or 3 or 4

到现在为止,我可以只使用加载整个HDF5:

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

我看不到如何在这里包含where条件。

回答

6

hdf5文件必须在table format被写入 为了可查询与pd.read_hdfwhere参数(相对于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) 
+0

感谢unutbu,对这个很好的答案只是一些评论。我明白,在答案开始时,你以表格格式将df写入h5。然而,我的脚本的输入是已经保存的h5,我怎么知道它是否在正确的格式? – codeKiller

+0

如果你的'h5'文件不是'table'格式,那么使用带'where'参数的'pd.read_hdf'会引发'TypeError:当从固定格式读取时不能通过where规范...'。如果'h5'文件是''表'格式的'A'没有被指定为'data_column',那么你会得到'ValueError:通过where表达式:A [1,3,4]包含一个无效变量参考...'。 – unutbu

+0

我不知道将h5文件从'fixed'转换为'table'格式或者添加'data_columns'的快捷方式。据我所知,你必须将整个'h5'文件读入一个DataFrame(或者使用'chunksize'参数以chunks的形式读取),然后写出或附加到另一个'h5'文件中'表格式。 – unutbu

1

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

+0

谢谢Dean,是否可以包含更复杂的条件?例如,如果我的A列的值为1到100,我想选择一些随机的东西,如[1,3,11,16,27,33,34,44,41,55,68,70,77,81 ,90] ...我在问,因为在主要问题中,我想简化它,但在我的实际情况中,where条件需要更复杂 – codeKiller

+0

找到需要传递给Expr的文档其中:http://nullege.com/codes/search/pandas.computation.pytables.Expr?fulldoc=1(这可能会有帮助,但我没有看到通过遏制过滤的选项) –

+0

好的,非常感谢 – codeKiller