Get Sum of NumPy Array in Python – np.sum() Function (3 Examples)
In this tutorial, I’ll illustrate how to use the np.sum function to get the sum of an array in Python programming.
Setting up the Examples
import numpy # Import numpy |
import numpy # Import numpy
x = np.array([[8, 2, 1, 7, 7, 5], # Constructing a NumPy array in Python [4, 10, 5, 9, 1, 4]]) print(x) # [[ 8 2 1 7 7 5] # [ 4 10 5 9 1 4]] |
x = np.array([[8, 2, 1, 7, 7, 5], # Constructing a NumPy array in Python [4, 10, 5, 9, 1, 4]]) print(x) # [[ 8 2 1 7 7 5] # [ 4 10 5 9 1 4]]
Example 1: Calculate Sum of All Array Values in Python
print(np.sum(x)) # Computing the sum of all values # 63 |
print(np.sum(x)) # Computing the sum of all values # 63
Example 2: Calculate Sum by Array Rows in Python
print(np.sum(x, axis = 1)) # Computing the sum by rows # [30 33] |
print(np.sum(x, axis = 1)) # Computing the sum by rows # [30 33]
Example 3: Calculate Sum by Array Columns in Python
print(np.sum(x, axis = 0)) # Computing the sum by columns # [12 12 6 16 8 9] |
print(np.sum(x, axis = 0)) # Computing the sum by columns # [12 12 6 16 8 9]