Pytables检查列是否存在

2024-06-26 00:10:49 发布

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

是否可以使用Pytables(或pandaps)来检测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文件的所有数据,因为这些文件可能很大,我只想确定某个列是否存在。


Tags: 文件thestorefromioimportpandasread
2条回答

我可能已经找到了一个解决方案,但不确定(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数组。在

接受的解决方案对Pandas 0.20.3和PyTables 3.3.0(HDF文件是用Pandas创建的)不起作用。然而,这是有效的:

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

相关问题 更多 >