2016-07-12 132 views
2

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

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文件的所有数据,因为这些文件可能很大,我只想确定是否存在某个列。

+0

试试这个:'hdf_store [“表名”] columns' – MaxU

+0

这需要很长的时间才能完成(3GB HDF文件),所以我想这是拉动完整的文件。但它返回列。 – orange

回答

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阵列与所有的列名。

+1

这很聪明!这里是一个熊猫的等价物:'pd.HDFStore('data.h5')。get_node('tablename')。axis0 [:]' – MaxU

0

Pandas 0.20.3和PyTables 3.3.0(HDF文件是使用Pandas创建的)接受的解决方案对我无效。然而,这个工程:

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