首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >h5py:分配或广播到结构化数组中的2x2列

h5py:分配或广播到结构化数组中的2x2列
EN

Stack Overflow用户
提问于 2021-05-09 04:07:58
回答 1查看 47关注 0票数 1

我有一个记录数组,有2×2个固定大小的项,有10行,因此列是10×2x2。我想给整个列分配一个常量。Numpy数组将正确广播标量值,但这在h5py中不起作用。

代码语言:javascript
运行
复制
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

事实上,我找不到一种不广播的方式来分配这个列:

代码语言:javascript
运行
复制
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

甚至没有一个元素行:

代码语言:javascript
运行
复制
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

这里的问题是什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-05-09 13:15:53

代码语言:javascript
运行
复制
In [69]: d = f.create_dataset('test', dtype=dt, shape=(3,))

我们可以设置一个相同大小的数组:

代码语言:javascript
运行
复制
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))])

并将其分配给数据集:

代码语言:javascript
运行
复制
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))])

我们还可以用正确的数据类型创建一个单元素数组,并指定:

代码语言:javascript
运行
复制
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,我们可以使用如下记录和字段进行索引:

代码语言:javascript
运行
复制
In [119]: d[0,'a']
Out[119]: 
array([[0., 1.],
       [2., 3.]], dtype=float32)

其中,as ndarray需要一个双精度索引,如:d[0]['a']

h5py试图模仿ndarray索引,但并不完全相同。我们只需要接受这一点。

编辑

118赋值也可以是

代码语言:javascript
运行
复制
In [207]: d[1,'a']=x

这里的dt只是一个字段,但我认为这应该适用于多个字段。关键是该值必须是一个符合d字段规范的结构化数组。

我刚刚在文档中注意到,他们正试图远离d[1,'a']索引,转而使用d[1]['a']。但对于似乎不起作用的任务--不是错误,只是没有动作。我认为d[1]d['a']是一个副本,相当于数组的高级索引。对于结构化数组,它们是view

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67451714

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档