【问题标题】:Storing a list of strings to a HDF5 Dataset from Python using VL format使用 VL 格式从 Python 将字符串列表存储到 HDF5 数据集
【发布时间】:2019-08-12 10:24:44
【问题描述】:

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

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 到Storing a list of strings to a HDF5 Dataset from Python,但我不认为它与该问题重复。

【问题讨论】:

  • 定义“直截了当”。您的有效循环几乎是“直截了当”的。
  • @RobertHarvey 我希望有一种 Python 类型可以用于我的可变长度字符串的序列/列表/向量,hp5y 可以直接使用它。
  • ds[:] = feature_names 有效吗?还是data=feature_names.astype(object)?
  • @hpaulj ds[:] = feature_names 有效,但您的第二个选项无效。如果你想把它变成一个答案,我会投赞成票。另外,除非有人想出将列表传递给create_dataset 函数的方法,否则我会接受它。

标签: python hdf5 h5py


【解决方案1】:

您几乎做到了,缺少的细节是将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。

【讨论】:

  • 感谢您的回答,为我节省了几个小时!
猜你喜欢
  • 2014-06-06
  • 2017-11-23
  • 1970-01-01
  • 2021-11-28
  • 2014-10-26
  • 2012-11-22
  • 2013-12-19
  • 1970-01-01
  • 2014-06-11
相关资源
最近更新 更多