如何使用HDF文件(固定格式,多个密钥)作为 pandas 数据帧?多个、密钥、如何使用、格式

2023-09-04 02:27:30 作者:提赋

我得到了一个使用PANDA创建的20 GB HDF5文件,但不幸的是,它是以固定格式(而不是表)编写的,每一列都写为一个单独的键。这对于快速加载一个功能非常有效,但它不支持方便的面向表格的过程(例如,统计分析或绘图)。

尝试将文件作为一个整体加载时出现以下错误:

使用Python中的Pandas工具将多个CSV格式的数据文件合并为一个

ValueError: key must be provided when HDF5 file contains multiple datasets

f=pd.read_hdf('file_path')

ValueError                             Traceback (most recent call last)

384             for group_to_check in groups[1:]:
385                 if not _is_metadata_of(group_to_check, candidate_only_group):

--> 386                     raise ValueError('key must be provided when HDF5 file '
    387                                      'contains multiple datasets.')
    388             key = candidate_only_group._v_pathname

ValueError: key must be provided when HDF5 file contains multiple datasets.
不幸的是,‘key’不接受python列表,所以我不能一次加载所有内容。有没有办法把h5文件从‘固定’转换成‘表’?或者一次性将文件加载到数据帧中?目前,我的解决方案是分别加载每一列,并将其追加到一个空的数据框中。

推荐答案

我不知道按列加载df列的任何其他方法,但您可以使用HDFStore而不是read_hdf自动执行此操作:

with pd.HDFStore(filename) as h5:
    df = pd.concat(map(h5.get, h5.keys()), axis=1)

示例:

#save df as multiple datasets
df = pd.DataFrame({'a': [1,2], 'b': [10,20]})
df.a.to_hdf('/tmp/df.h5', 'a', mode='w', format='fixed')
df.b.to_hdf('/tmp/df.h5', 'b', mode='a', format='fixed')

#read columns and concat to dataframe    
with pd.HDFStore('/tmp/df.h5') as h5:
    df1 = pd.concat(map(h5.get, h5.keys()), axis=1)

#verify
assert all(df1 == df)