Parker de Waal - 1 year ago 50

Python Question

While trying to subtract to fields within a structured numpy array, the following error occurs:

`In [8]: print serPos['pos'] - hisPos['pos']`

---------------------------------------------------------------------------

TypeError

Traceback (most recent call last) <ipython-input-8-8a22559cfb2d> in <module>()

----> 1 print serPos['pos'] - hisPos['pos']

TypeError: ufunc 'subtract' did not contain a loop with signature matching types

dtype([('x', '<f8'), ('y', '<f8'), ('z', '<f8')])

dtype([('x', '<f8'), ('y', '<f8'), ('z', '<f8')])

dtype([('x', '<f8'), ('y', '<f8'), ('z', '<f8')])

Given the standard float dtype, why would I be unable to perform this subtraction?

To reproduce these conditions, the following example code is provided:

`import numpy as np`

raw = np.dtype([('residue', int),

('pos', [('x', float),

('y', float),

('z', float)])])

serPos = np.empty([0,2],dtype=raw)

hisPos = np.empty([0,2],dtype=raw)

serPos = np.append(serPos, np.array([(1,(1,2,3))], dtype=raw))

hisPos = np.append(hisPos, np.array([(1,(1,2,3))], dtype=raw))

print serPos['pos'], hisPos['pos'] # prints fine

print serPos['pos'] - hisPos['pos'] # errors with ufunc error

Any suggestions would be greatly appreciated!

Answer Source

The `dtype`

for `serPos['pos']`

is compound

```
dtype([('x', '<f8'), ('y', '<f8'), ('z', '<f8')])
```

subtraction (and other such operations) has not been defined for compound dtype. It doesn't work for the `raw`

dtype either.

You could subtract the individual fields

```
serPos['pos']['x']-hisPos['pos']['x']
```

I think we can also `view`

`serPos['pos']`

as a 2d array (3 columns) and subtract that form. But I need to test the syntax.