How can I sum the rows and columns of a NumPy array?

You can sum the rows and columns of a NumPy array using the np.sum() function. This function takes an array as an argument and returns the sum of all the elements in the array. You can specify the axis as 0 for the column or 1 for the row to get the sum of each row or column. Alternatively, you can use the np.sum(array, axis=None) to get the sum of all elements in the array.


You can use the following methods to sum the rows and columns of a 2D NumPy array:

Method 1: Sum Rows of NumPy Array

arr.sum(axis=1)

Method 2: Sum Columns of NumPy Array

arr.sum(axis=0) 

The following examples show how to use each method in practice with the following 2D NumPy array:

import numpy as np

#create NumPy array
arr = np.arange(18).reshape(6,3)

#view NumPy array
print(arr)

[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]
 [12 13 14]
 [15 16 17]]

Example 1: Sum Rows of NumPy Array

We can use the following syntax to sum the rows of a NumPy array:

import numpy as np

#calculate sum of rows in NumPy array
arr.sum(axis=1)

array([ 3, 12, 21, 30, 39, 48])

The resulting array shows the sum of each row in the 2D NumPy array.

For example:

  • The sum of values in the first row is 0 + 1 + 2 = 3.
  • The sum of values in the first row is 3 + 4 + 5 = 12.
  • The sum of values in the first row is 6 + 7 + 8 = 21.

And so on.

Example 2: Sum Columns of NumPy Array

We can use the following syntax to sum the columns of a NumPy array:

import numpy as np

#calculate sum of columns in NumPy array
arr.sum(axis=0)

array([45, 51, 57])

For example:

  • The sum of values in the first column is 0+3+6+9+12+15 = 45.
  • The sum of values in the first row is 1+4+7+10+13+16 = 51.
  • The sum of values in the first row is 2+5+8+11+14+17 = 57.

Note: You can find the complete documentation for the NumPy sum() function .

The following tutorials explain how to perform other common operations in NumPy:

x