我希望下面的代码能工作,但不能。
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数据集的答案,但是我不认为它是该问题的重复。
您几乎做到了,缺少的细节将传递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
。