Home > Software design >  Sum the first dimension of a 3D numpy array
Sum the first dimension of a 3D numpy array

Time:10-29

I have the following 3D numpy.array of shape (2,3,3):

import numpy as np

arr = np.array(((((1,2,3),(9,8,7),(6,5,4))),
                (((10,20,30),(90,80,70),(60,50,40)))))

I want to sum the first dimension and get one 2D array of shape (3,3).

Expected output:

array([[11, 22, 33],
       [99, 88, 77],
       [66, 55, 44]])

I know I can iterate over the elements in the first dimension and sum, with something like this:

for el in range(len(arr)):
    if el == 0:
        arr_sum = arr[el]
    else:
        arr_sum  = arr[el]

But there is another option to do this?

Thanks in advance.

CodePudding user response:

You can use, NumPy.sum method.

import numpy as np
arr = np.array(((((1,2,3),(9,8,7),(6,5,4))),(((10,20,30),(90,80,70),(60,50,40)))))

print(np.sum(arr, axis=0))
  • Related