Calculating the sum of all columns of a 2D NumPy array
Let us see how to calculate the sum of all the columns of a 2 dimensional NumPy array.
Example :
Input : [[1, 2, 3, 4, 5], [5, 6, 7, 8, 9], [2, 1, 5, 7, 8], [2, 9, 3, 1, 0]] Output : [10, 18, 18, 20, 22] Input : [[5, 4, 1, 7], [0, 9, 3, 5], [3, 2, 8, 6]] Output : [8, 15, 12, 18]
Approach 1 : We will be using the sum()
method. We will pass parameter axis = 0
to get the sum columns wise.
# importing numpy import numpy as np # initialize the 2-d array arr = np.array([[ 1 , 2 , 3 , 4 , 5 ], [ 5 , 6 , 7 , 8 , 9 ], [ 2 , 1 , 5 , 7 , 8 ], [ 2 , 9 , 3 , 1 , 0 ]]) # calculating column wise sum sum_2d = arr. sum (axis = 0 ) # displaying the sum print ( "Column wise sum is :\n" , sum_2d) |
Output :
Column wise sum is : [10 18 18 20 22]
Approach 2 : We can also use the numpy.einsum()
method, with parameter 'ij->j'
.
# importing numpy import numpy as np # initialize the 2-d array arr = np.array([[ 1 , 2 , 3 , 4 , 5 ], [ 5 , 6 , 7 , 8 , 9 ], [ 2 , 1 , 5 , 7 , 8 ], [ 2 , 9 , 3 , 1 , 0 ]]) # calculating column wise sum sum_2d = np.einsum( 'ij->j' , arr) # displaying the sum print ( "Column wise sum is :\n" , sum_2d) |
Output :
Column wise sum is : [10 18 18 20 22]