如何与自定义numpy dtypes进行交互

时间:2019-03-06 22:12:24

标签: python arrays numpy

我正在尝试将一些点加在一起,并且自定义dtype的行为不像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

为了便于阅读和维护。

0 个答案:

没有答案