如何与自定义numpy数据类型交互

2024-06-02 07:43:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试将一些点添加到一起,而自定义数据类型的行为不符合ndarray的要求。下面是我尝试使用的代码:

self.center = np.dtype([('x', np.uint16), ('y', np.uint16)])

nd0 = np.array((1, 2))
nd1 = np.array((3, 4))
print(nd0 + nd1)

c0 = np.array((1, 2), dtype=self.center)
c1 = np.array((3, 4), dtype=self.center)
print(c0 + c1)

第二个print产生一个错误:

TypeError: ufunc 'add' did not contain a loop with signature matching types 
dtype([('x', '<u2'), ('y', '<u2')]) 
dtype([('x', '<u2'), ('y', '<u2')]) 
dtype([('x', '<u2'), ('y', '<u2')])

创建一个自定义函数来处理惟一的dtype是标准实践吗?c0c1属于numpy.void类型,而nd0nd1属于numpy.ndarray。我试图用numpy.asarray进行强制转换,但仍然无法将两者相加。你知道吗

我想平均两个物体的中心。center命名字段嵌套在另一个命名数组中,我认为这样做更容易:

new_center = (pop[i]['center'] + pop[j]['center']) / 2.0

而不是:

new_center = (pop[i][0] + pop[j][0]) / 2.0

便于阅读和维护。你知道吗


Tags: selfnumpynparraypopcenterprintndarray