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
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

Example 2: Calculate Sum by Array Rows in Python

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]

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top