0

I'm trying to add some points together and custom dtypes do not behave as ndarrays. The following is code I'm trying to use:

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)

The second print yields an error:

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')])

Is standard practice to create a custom function to handle unique dtype? c0 and c1 are of type numpy.void, whereas nd0 and nd1 are numpy.ndarray. I attempted to cast with numpy.asarray but it still fails to add the two.

I wanted to average the centers of two objects. The center named field is nested in another named array and I thought it'd be easier to do something like:

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

Rather than:

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

for readability and maintenance.

MacAttack
  • 11
  • 4
  • Math functions don't work on structured arrays like this. You can though do the math on the individual fields. – hpaulj Mar 06 '19 at 22:44
  • Structured arrays are most useful when they contain a mix of dtypes, say string labels, plus integer and float values. I don't think they should be used just as a labeling device. – hpaulj Mar 06 '19 at 22:51
  • It is possible to define a structure that has overlapping field definitions, such that 'xy' could access the same two values as 'x' and 'y'. But the syntax for doing that is harder to remember, so I won't try to demonstrate if off hand. – hpaulj Mar 06 '19 at 22:57
  • https://stackoverflow.com/questions/49503565/make-a-numpy-array-with-shape-and-offset-argument-in-another-style demonstrates how to access separate fields as well as their union. And an earlier example: https://stackoverflow.com/questions/26349116/no-binary-operators-for-structured-arrays-in-numpy – hpaulj Mar 06 '19 at 23:35

0 Answers0