【问题标题】:Pytables check if column existsPytables 检查列是否存在
【发布时间】:2017-08-13 22:32:05
【问题描述】:

是否可以使用 Pytables(或 Pandas)来检测 hdf 文件的表是否包含某个列?要加载我使用的 hdf 文件:

from pandas.io.pytables import HDFStore
# this doesn't read the full file which is good
hdf_store = HDFStore('data.h5', mode='r')
# returns a "Group" object, not sure if this could be used...
hdf_store.get_node('tablename')

我也可以直接使用 Pytables 而不是 Pandas。目的不是加载 hdf 文件的所有数据,因为这些文件可能很大,我只想确定某个列是否存在。

【问题讨论】:

  • 试试这个:hdf_store['tablename'].columns
  • 这需要很长时间才能完成(3GB hdf 文件),所以我猜它正在拉入完整的文件。但它会返回列。

标签: python pandas pytables


【解决方案1】:

我可能已经找到了解决方案,但不确定 (1) 为何有效以及 (2) 这是否是一个可靠的解决方案。

import tables
h5 = tables.openFile('data.h5', mode='r')
df_node = h5.root.__getattr__('tablename')
# Not sure why `axis0` contains the column data, but it seems consistent
# with the tested h5 files.
columns = df_node.axis0[:]

columns 包含一个包含所有列名的 numpy 数组。

【讨论】:

  • 这很聪明!这是一个等效的熊猫:pd.HDFStore('data.h5').get_node('tablename').axis0[:]
【解决方案2】:

接受的解决方案不适用于 Pandas 0.20.3 和 PyTables 3.3.0(HDF 文件是使用 Pandas 创建的)。但是,这是可行的:

pd.HDFStore('data.hd5', mode='r').get_node('/path/to/pandas/df').table.colnames

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-01
    • 2016-10-30
    • 2013-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多