我正在尝试将一些点加在一起,并且自定义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
吗? c0
和c1
的类型为numpy.void
,而nd0
和nd1
的类型为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
为了便于阅读和维护。