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.
import numpy as np
arr = np.array([[ 1 , 2 , 3 , 4 , 5 ],
[ 5 , 6 , 7 , 8 , 9 ],
[ 2 , 1 , 5 , 7 , 8 ],
[ 2 , 9 , 3 , 1 , 0 ]])
sum_2d = arr. sum (axis = 0 )
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'
.
import numpy as np
arr = np.array([[ 1 , 2 , 3 , 4 , 5 ],
[ 5 , 6 , 7 , 8 , 9 ],
[ 2 , 1 , 5 , 7 , 8 ],
[ 2 , 9 , 3 , 1 , 0 ]])
sum_2d = np.einsum( 'ij->j' , arr)
print ( "Column wise sum is :\n" , sum_2d)
|
Output :
Column wise sum is :
[10 18 18 20 22]
Last Updated :
02 Sep, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...