3

We have some arrays of the same shape and want to merge them.

By "merge", I mean output a new array with the sum of each i,j in each of the arrays in each position.

import numpy as np
first = np.array([[1,1],[1,1]])
second = np.array([[2,2],[2,2]])
third = np.array([[3,3],[3,3]])

The result should be:

[[6,6],
[6,6]]

Here's my code...but is there a cleaner way? I can't seem to find a built-in method:

def merge_arrays(arrays):
    output = arrays[0]
    for a in arrays[1:]:
        for i,row in enumerate(a):
            for j,col in enumerate(row):
                output[i,j] += a[i,j]
    return output

merge_arrays([first, second, third])

1 Answer 1

4

It's just output = first + second + third or np.sum([first, second, third], axis=0).

Sign up to request clarification or add additional context in comments.

3 Comments

Damned, you did beat me by seconds since you did know the answer while i had to try it in ipython :D
@KlausWarzecha - I usually get burned when I don't test things out first! (And I actually did this time, too... Forgot the axis=0 when I first typed it.)
@Joe Kington Yes, i saw you editing while i had the simple addition working and was still stumbling over the syntax of np.sum()

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.