gpt4 book ai didi

python - H5PY保存复合numpy数组时出现问题

转载 作者:太空宇宙 更新时间:2023-11-03 21:06:58 31 4
gpt4 key购买 nike

在尝试对文件格式进行逆向工程时,我得到了以下最小示例,用于创建复合 numpy 数据类型并将其保存到 HDF5。原始文件似乎存储以下数据类型的数据集。但是,我似乎无法将此类数据集写入文件。

import numpy as np
import h5py

data = ("Many cats".encode(), np.linspace(0, 1, 20))
data_type = [('index', 'S' + str(len(data[0]))), ('values', '<f8', (20,))]

arr = np.array(data, dtype=data_type)
print(arr)

h5f = h5py.File("lol.h5", 'w')
dset = h5f.create_dataset("data", arr, dtype=data_type)
h5f.close()

此代码因错误而崩溃

Traceback (most recent call last): File "test.py", line 13, in dset = h5f.create_dataset("data", arr, dtype=data_type) File "/opt/anaconda3/lib/python3.7/site-packages/h5py/_hl/group.py", line 116, in create_dataset dsid = dataset.make_new_dset(self, shape, dtype, data, **kwds) File "/opt/anaconda3/lib/python3.7/site-packages/h5py/_hl/dataset.py", line 75, in make_new_dset shape = tuple(shape) TypeError: iteration over a 0-d array

如何解决这个问题?

最佳答案

我重组/重新排序了您的代码,使其能够与 h5py 一起使用。下面的代码适用于 1 行。您必须进行调整以使行数成为变量。

import numpy as np
import h5py

data = ("Many cats".encode(), np.linspace(0, 1, 20))
data_type = [('index', 'S' + str(len(data[0]))), ('values', '<f8', (20,))]

arr = np.zeros((1,), dtype=data_type)
arr[0]['index'] = "Many cats".encode()
arr[0]['values'] = np.linspace(0, 1, 20)

h5f = h5py.File("lol.h5", 'w')
dset = h5f.create_dataset("data", data=arr)

h5f.close()

关于python - H5PY保存复合numpy数组时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55335664/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com