【发布时间】:2021-09-12 12:51:35
【问题描述】:
我正在尝试读取一个 .h5 文件 data.h5,它有 2 个数据集,“数据”和“元数据”。 'metaData' 包含一个 157x1 的字典,如下所示:
然后,我正在尝试编写一个新的 .h5 文件,其中包含 3 列:字典中每个变量的数字、名称(字典的第一列)和单位(字典的最后一列)。这是代码:
import numpy as np
import h5py as h5
hdf = h5.File('data.h5','r')
data1 = hdf.get('Data')
data2 = hdf.get('metaData')
dataset1 = np.array(data1)
dataset2 = np.array(data2)
#dictionary
hdfdic = dict(hdf['metaData'])
dic = hdfdic.get('dictionary')
dictionary = np.array(dic)
#write new h5 file
with h5.File('telemetry.h5', 'w') as var:
dt = np.dtype( [('n°', int), ('Variable name', 'S10'), ('Unit', 'S10')] )
dset = var.create_dataset( 'data', dtype=dt, shape = (len(dictionary),))
dset['n°'] = np.arange(len(dictionary))
dset['Variable name'] = [val[1] for val in dictionary[:][0][0]]
dset['Unit'] = [val[2] for val in dictionary[:][0][-1]]
data = dset[:]
print(data)
我得到错误:
Traceback (most recent call last):
File "c:/Users/user/Desktop/new/code.py", line 28, in <module>
dset['Variable name'] = [val[1] for val in dictionary[:][0][0]]
File "h5py\_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
File "h5py\_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
File "C:\Users\user\Anaconda3\envs\py38\lib\site-packages\h5py\_hl\dataset.py", line 707, in __setitem__
for fspace in selection.broadcast(mshape):
File "C:\Users\user\Anaconda3\envs\py38\lib\site-packages\h5py\_hl\selections.py", line 299, in broadcast
raise TypeError("Can't broadcast %s -> %s" % (target_shape, self.mshape))
TypeError: Can't broadcast (4,) -> (157,)
有什么问题?
【问题讨论】:
-
dictionary是一个 numpy 数组。用[:]对其进行索引没有任何作用。您可能想使用dictionary[:,0,0]。但这只是猜测,因为我对此了解不多。
标签: python numpy unicode hdf5 h5py