0

I want to add two dtype array and get the same dtype type of array:

>>> dtype=[('p', '<i8'), ('l', '<f8')]
>>> v1 = np.array([(22, 3.14), (4, 0.1)], dtype=dtype)
>>> v1
array([(22, 3.14), (4, 0.1)], dtype=[('p', '<i8'), ('l', '<f8')])

>>> v2 = np.array([(11, 3.14), (6, 0.2)], dtype=dtype)
>>> v2
array([(11, 3.14), (6, 0.2)], dtype=[('p', '<i8'), ('l', '<f8')])

I want to get:

>>> array([(33, 6.28), (10, 0.3)], dtype=[('p', '<i8'), ('l', '<f8')])

but I get:

>>> v = v1 + v2
TypeError: unsupported operand type(s) for +: 'numpy.ndarray' and 'numpy.ndarray'

or

>>> v = np.sum(v1, v2)
...
TypeError: cannot perform reduce with flexible type

2 Answers 2

3

Sadly, I don't know of an easier way than computing each column separately:

import numpy as np

dtype=[('p', '<i8'), ('l', '<f8')]
v1 = np.array([(22, 3.14), (4, 0.1)], dtype=dtype)
v2 = np.array([(11, 3.14), (6, 0.2)], dtype=dtype)

v = np.empty_like(v1)
for col in v1.dtype.names:
    v[col] = v1[col] + v2[col]
print(v)
# [(33L, 6.28) (10L, 0.30000000000000004)]

However, if you install pandas and make v1 and v2 DataFrames, then summing is simple:

import pandas as pd
v1 = pd.DataFrame.from_records(v1)
v2 = pd.DataFrame.from_records(v2)
v = v1 + v2
print(v)

yields

    p     l
0  33  6.28
1  10  0.30
Sign up to request clarification or add additional context in comments.

Comments

1

If it's not that important to preserve the structured array:

In [703]: v=array(v1.tolist())+array(v2.tolist())

In [704]: v
Out[704]: 
array([[ 33.  ,   6.28],
       [ 10.  ,   0.3 ]])

otherwise, best way I could come up with is just add column by column as @unutbu mentioned.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.