温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - Storing a list of strings to a HDF5 Dataset from Python using VL format
h5py hdf5 python

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

发布于 2020-03-27 10:25:49

我希望下面的代码能工作,但不能。

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]

注意:我的问题来自从Python将字符串列表存储到HDF5数据集的答案,但是我不认为它是该问题的重复。

查看更多

查看更多

提问者
mhwombat
被浏览
294
teegaar 2019-07-03 21:23

您几乎做到了,缺少的细节将传递dtypenp.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