4

I have a multidimensional numpy array that has the shape (5, 6192, 1) so essentially 5 arrays of length 6192 into one array.

How could I add the elements of all the arrays into one array of length 6192 in the following way. For example if the 5 arrays look like

ar1 = [1,2,3...]
ar2 = [1,2,3...]
ar3 = [1,2,3...]
ar4 = [1,2,3...]
ar5 = [1,2,3...]

I want my final array to look like:

ar = [5,10,15,...]

So for each inner array, add the values of each same position into a new value for the final array that is the sum of all the values in this position.

The shape should be, I guess shape(1,6192,1).

1
  • Your input is unclear, do you have a list of lists? list of arrays? multidimensional array? Commented Mar 1, 2022 at 9:43

1 Answer 1

2

IIUC, simply use numpy.sum:

ar1 = [1,2,3]
ar2 = [1,2,3]
ar3 = [1,2,3]
ar4 = [1,2,3]
ar5 = [1,2,3]

arrays = [ar1, ar2, ar3, ar4, ar5]

ar = np.sum(arrays, axis=0)

output: array([ 5, 10, 15])

If really the shapes you describe are correct:

arr = np.array(arrays).reshape((5, 3, 1))
print(arr.shape)
# (5, 3, 1)

ar = np.sum(arr, axis=0)[None,:]

print(ar.shape)
# (1, 3, 1)
Sign up to request clarification or add additional context in comments.

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.