过滤pandas导入上的pytables表

时间:2013-09-26 18:54:47

标签: python pandas pytables

我有一个用pytables创建的数据集,我试图将其导入到pandas数据帧中。我无法将where过滤器应用于read_hdf步骤。我在熊猫'0.12.0'

我的样本pytables数据:

import tables
import pandas as pd
import numpy as np

class BranchFlow(tables.IsDescription):
    branch = tables.StringCol(itemsize=25, dflt=' ')
    flow = tables.Float32Col(dflt=0)

filters = tables.Filters(complevel=8)
h5 = tables.openFile('foo.h5', 'w')
tbl = h5.createTable('/', 'BranchFlows', BranchFlow, 
            'Branch Flows', filters=filters, expectedrows=50e6) 

for i in range(25):
    element = tbl.row
    element['branch'] = str(i)
    element['flow'] = np.random.randn()
    element.append()
tbl.flush()
h5.close()

我可以将其导入数据帧:

store = pd.HDFStore('foo.h5')
print store
print pd.read_hdf('foo.h5', 'BranchFlows').head()

显示:

In [10]: print store
<class 'pandas.io.pytables.HDFStore'>
File path: foo.h5
/BranchFlows            frame_table [0.0.0] (typ->generic,nrows->25,ncols->2,indexers->[index],dc->[branch,flow])

In [11]: print pd.read_hdf('foo.h5', 'BranchFlows').head()
  branch      flow
0      0 -0.928300
1      1 -0.256454
2      2 -0.945901
3      3  1.090994
4      4  0.350750

但我无法让过滤器在流列上工作:

pd.read_hdf('foo.h5', 'BranchFlows', where=['flow>0.5'])

<snip traceback>

TypeError: passing a filterable condition to a non-table indexer [field->flow,op->>,value->[0.5]]

1 个答案:

答案 0 :(得分:3)

从PyTables直接创建的表中读取只允许您直接读取(整个)表。您必须使用pandas工具(表格式)编写它以使用pandas选择机制(因为pandas需要的元数据不存在 - 可以完成,但需要一些工作)。

因此,请像上面一样阅读您的表格,然后创建一个新表格,并指明表格格式。见here for docs

In [6]: df.to_hdf('foo.h5','BranchFlowsTable',data_columns=True,table=True)

In [24]: with pd.get_store('foo.h5') as store:
    print(store)
   ....:     
<class 'pandas.io.pytables.HDFStore'>
File path: foo.h5
/BranchFlows                 frame_table [0.0.0] (typ->generic,nrows->25,ncols->2,indexers->[index],dc->[branch,flow])
/BranchFlowsTable            frame_table  (typ->appendable,nrows->25,ncols->2,indexers->[index],dc->[branch,flow])    

In [7]: pd.read_hdf('foo.h5','BranchFlowsTable',where='flow>0.5')
Out[7]: 

   branch      flow
14     14  1.503739
15     15  0.660297
17     17  0.685152
18     18  1.156073
20     20  0.994792
21     21  1.266463
23     23  0.927678