使用 VL 格式将字符串列表从 Python 存储到 HDF5 数据集

Storing a list of strings to a HDF5 Dataset from Python using VL format

我希望下面的代码可以工作,但它没有。

import h5py
import numpy as np

with h5py.File('file.hdf5','w') as hf:
    dt = h5py.special_dtype(vlen=str)
    feature_names = np.array(['a', 'b', 'c'])
    hf.create_dataset('feature names', data=feature_names, dtype=dt)

我收到错误消息 TypeError: No conversion path for dtype: dtype('<U1')。下面的代码确实有效,但使用 for 循环复制数据对我来说似乎有点笨拙。 有更直接的方法吗?我希望能够将字符串序列直接传递给 create_dataset 函数。

import h5py
import numpy as np

with h5py.File('file.hdf5','w') as hf:
    dt = h5py.special_dtype(vlen=str)
    feature_names = np.array(['a', 'b', 'c'])
    ds = hf.create_dataset('feature names', (len(feature_names),), dtype=dt)

    for i in range(len(feature_names)):
        ds[i] = feature_names[i]

注意:我的问题来自 this answer to Storing a list of strings to a HDF5 Dataset from Python,但我不认为它与该问题重复。

您几乎做到了,缺少的细节是将 dtype 传递给 np.array

import h5py                                                                                                                                                                                                
import numpy as np            

with h5py.File('file.hdf5','w') as hf: 
     dt = h5py.special_dtype(vlen=str) 
     feature_names = np.array(['a', 'b', 'c'], dtype=dt) 
     hf.create_dataset('feature names', data=feature_names)

PS:对我来说这看起来像是一个错误 - create_dataset 忽略给定的 dtype 并且不将其应用于给定的 data.