导入HDF5文件时列未被识别的解决方法咨询
解决HDF5结构化数据集在Vaex和Pandas中的列识别问题
问题背景
尝试导入一个未知写入细节的HDF5文件,通过h5ls -v查看文件结构如下:
$ h5ls -v file.hdf5/DataSet Opened "file.hdf5" with sec2 driver. DataSet Dataset {5026/Inf} Attribute: Species scalar Type: 12-byte null-terminated ASCII string Attribute: Tuning scalar Type: 8-byte null-terminated ASCII string Location: 1:800 Links: 1 Chunks: {1} 88 bytes Storage: 442288 logical bytes, 442288 allocated bytes, 100.00% utilization Type: struct { "Scan" +0 native double "col6" +8 native double "col5" +16 native double "col10" +24 native double "col7" +32 native double "col8" +40 native double "col1" +48 native double "col2" +56 native double "col4" +64 native double "col9" +72 native double "col3" +80 native double } 88 bytes
使用Vaex时,所有数据被归入单一DataSet列,无法识别单独字段;使用Pandas执行pd.read_hdf('file.hdf5')则抛出ValueError。
Vaex 处理方案
Vaex默认将结构化HDF5数据集识别为单一列,需手动展开结构化字段:
import vaex as vx # 打开HDF5文件 df = vx.open('file.hdf5') # 获取结构化列的所有字段名 struct_fields = df['DataSet'].dtype.names # 遍历字段,将每个字段转为单独列 for field in struct_fields: df[field] = df['DataSet'][field] # 查看包含所有单独列的DataFrame df
执行后,Scan、col1至col10都会成为独立列。
Pandas 处理方案
Pandas的read_hdf仅兼容自身写入的HDF5格式,需借助h5py读取结构化数据后转换为DataFrame:
import h5py import pandas as pd # 读取HDF5文件中的结构化数据集 with h5py.File('file.hdf5', 'r') as h5_file: dataset = h5_file['DataSet'][:] # 将结构化数组直接转为DataFrame df = pd.DataFrame(dataset) # 查看结果 df
此方法会自动解析所有结构化字段为DataFrame的列。
内容的提问来源于stack exchange,提问作者luki
相关产品推荐
相关产品推荐

