NumPy sum() in Python

Share this article

In NumPy, sum() is a method that adds up all the elements of an array. It is commonly used in numerical computations and data analysis to quickly find the total or sum of elements in arrays, which can be one-dimensional (like a list) or multi-dimensional (like a matrix).

Key Takeaway

numpy.sum() computes the sum of all elements in an array. It allows for flexibility in summing over specific axes in multi-dimensional arrays, making it a versatile tool for data analysis and mathematical operations.

Example

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
total_sum = np.sum(arr)
print(total_sum)  # Output: 15

What it does

numpy.sum() adds up all the values in the array and returns the total. If the array is multi-dimensional, you can specify which axis to sum over.

  • Full array sum: Without specifying an axis, numpy.sum() adds up all elements in the entire array.
  • Axis sum: If you specify an axis, it sums along that axis, which is useful for operations on matrices and higher-dimensional arrays.

Examples

Example 1: Basic usage with a 1D array

import numpy as np

arr = np.array([10, 20, 30, 40])
total = np.sum(arr)
print(total)  # Output: 100

Here, np.sum() adds all the elements in the array [10, 20, 30, 40] and returns 100.

Example 2: Summing elements in a 2D array

import numpy as np

matrix = np.array([[1, 2, 3], [4, 5, 6]])
total = np.sum(matrix)
print(total)  # Output: 21

When using np.sum() on a 2D array (matrix), it adds all the elements: 1 + 2 + 3 + 4 + 5 + 6, resulting in 21.

Example 3: Summing along an axis in a 2D array

import numpy as np

matrix = np.array([[1, 2, 3], [4, 5, 6]])
sum_axis0 = np.sum(matrix, axis=0)
sum_axis1 = np.sum(matrix, axis=1)
print(sum_axis0)  # Output: [5, 7, 9]
print(sum_axis1)  # Output: [6, 15]
  • axis=0 sums down the columns, resulting in [1 + 4, 2 + 5, 3 + 6] which is [5, 7, 9].
  • axis=1 sums across the rows, resulting in [1 + 2 + 3, 4 + 5 + 6] which is [6, 15].

Example 4: Sum with a specific data type

import numpy as np

arr = np.array([1, 2, 3, 4], dtype=np.float32)
total = np.sum(arr, dtype=np.float64)
print(total)  # Output: 10.0

You can specify the data type for the sum to control precision. Here, even though the array is of type float32, the sum is computed as float64 for higher precision.