我有一个记录数组,有2×2个固定大小的项,有10行,因此列是10×2x2。我想给整个列分配一个常量。Numpy数组将正确广播标量值,但这在h5py中不起作用。
import numpy as np
import h5py
dt=np.dtype([('a',('f4',(2,2)))])
# h5py array
h5a=h5py.File('/tmp/t1.h5','w')['/'].require_dataset('test',dtype=dt,shape=(10,))
# numpy for comparison
npa=np.zeros((10,),dtype=dt)
h5a['a']=np.nan
# ValueError: changing the dtype of a 0d array is only supported if the itemsize is unchanged
npa['a']=np.nan
# numpy: broadcasts, OK
事实上,我找不到一种不广播的方式来分配这个列:
h5a['a']=np.full((10,2,2),np.nan)
# ValueError: When changing to a larger dtype, its size must be a divisor of the total size in bytes of the last axis of the array
甚至没有一个元素行:
h5a['a',0]=np.full((2,2),np.nan)
# ValueError: When changing to a larger dtype, its size must be a divisor of the total size in bytes of the last axis of the array
这里的问题是什么?
发布于 2021-05-09 13:15:53
In [69]: d = f.create_dataset('test', dtype=dt, shape=(3,))
我们可以设置一个相同大小的数组:
In [90]: x=np.ones(3,dt)
In [91]: x[:]=2
In [92]: x
Out[92]:
array([([[2., 2.], [2., 2.]],), ([[2., 2.], [2., 2.]],),
([[2., 2.], [2., 2.]],)], dtype=[('a', '<f4', (2, 2))])
并将其分配给数据集:
In [93]: d[:]=x
In [94]: d
Out[94]: <HDF5 dataset "test": shape (3,), type "|V16">
In [95]: d[:]
Out[95]:
array([([[2., 2.], [2., 2.]],), ([[2., 2.], [2., 2.]],),
([[2., 2.], [2., 2.]],)], dtype=[('a', '<f4', (2, 2))])
我们还可以用正确的数据类型创建一个单元素数组,并指定:
In [116]: x=np.array((np.arange(4).reshape(2,2),),dt)
In [117]: x
Out[117]: array(([[0., 1.], [2., 3.]],), dtype=[('a', '<f4', (2, 2))])
In [118]: d[0]=x
使用h5py
,我们可以使用如下记录和字段进行索引:
In [119]: d[0,'a']
Out[119]:
array([[0., 1.],
[2., 3.]], dtype=float32)
其中,as ndarray
需要一个双精度索引,如:d[0]['a']
h5py
试图模仿ndarray
索引,但并不完全相同。我们只需要接受这一点。
编辑
118赋值也可以是
In [207]: d[1,'a']=x
这里的dt
只是一个字段,但我认为这应该适用于多个字段。关键是该值必须是一个符合d
字段规范的结构化数组。
我刚刚在文档中注意到,他们正试图远离d[1,'a']
索引,转而使用d[1]['a']
。但对于似乎不起作用的任务--不是错误,只是没有动作。我认为d[1]
或d['a']
是一个副本,相当于数组的高级索引。对于结构化数组,它们是view
。
https://stackoverflow.com/questions/67451714
复制相似问题