How to work with HDF file (fixed format, multiple keys) as a pandas dataframe?(如何使用HDF文件(固定格式,多个密钥)作为 pandas 数据帧?)
问题描述
我得到了一个使用PANDA创建的20 GB HDF5文件,但不幸的是,它是以固定格式(而不是表)编写的,每一列都写为一个单独的键。这对于快速加载一个功能非常有效,但它不支持方便的面向表格的过程(例如,统计分析或绘图)。
尝试将文件作为一个整体加载时出现以下错误:
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)
这篇关于如何使用HDF文件(固定格式,多个密钥)作为 pandas 数据帧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!