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])
The resulting array shows the sum of each column in the 2D NumPy array.
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 here.
Additional Resources
The following tutorials explain how to perform other common operations in NumPy:
How to Find Index of Value in NumPy Array
How to Get Specific Column from NumPy Array
How to Add a Column to a NumPy Array