What is the numpy.sum() Method

The numpy.sum() method “calculates the sum of all the elements in a NumPy array” or along a specified axis.


numpy.sum(array, axis=None, dtype=None, out=None)


  1. An array is an array to be summed.
  2. An axis is an axis along which to sum the elements. If the axis is None, the array details are summed together.
  3. The dtype is the data type of the resulting array. If dtype is None, the data type of the resulting array is the same as the data type of the input array.
  4. An out is an output array. If out is not None, the result is stored in out.


import numpy as np

# Sample NumPy array
arr = np.array([[1, 2, 3], [4, 5, 6]])

# Compute the sum of all elements
total_sum = np.sum(arr)
print("\nSum of all elements:", total_sum)

# Compute the sum along axis 0 (rows)
row_sum = np.sum(arr, axis=0)
print("\nSum along axis 0 (rows):", row_sum)

# Compute the sum along axis 1 (columns)
col_sum = np.sum(arr, axis=1)
print("\nSum along axis 1 (columns):", col_sum)


[[1 2 3]
 [4 5 6]]

Sum of all elements: 21

Sum along axis 0 (rows): [5 7 9]

Sum along axis 1 (columns): [ 6 15]

In this code, we created a sample NumPy array.

In the next step, we calculated the sum of all elements, the sum along axis 0 (rows), and the sum along axis 1 (columns) using the numpy.sum() function.

The resulting sums are printed, showing how the sum can be computed using the numpy.sum() function.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.