python - 在 pandas 导入上过滤 pytables 表

标签 python pandas pytables

我有一个使用 pytables 创建的数据集,我正在尝试将其导入到 pandas 数据框中。我无法将 where 过滤器应用于 read_hdf 步骤。我在 pandas '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]]

最佳答案

从 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

关于python - 在 pandas 导入上过滤 pytables 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19036380/

相关文章:

python - cx_Oracle LDAP 连接字符串语法

python - 数据框使列代表向量

python - 使用 HDF5 和 Pandas 通过分块读取数据

python - 在 PyTables 中存储和提取 numpy 日期时间

python - 解析 XML Python

python - 验证PE文件的签名

python - 具有多个索引的 Pandas div

python - ggplot2:绘制安德鲁斯曲线

python - Pandas:获取重复的索引

python - 如何在Python中创建一个大的矩阵矩阵?