The numpy.sum() method “calculates the sum of all the elements in a NumPy array” or along a specified axis.
Syntax
numpy.sum(array, axis=None, dtype=None, out=None)
Parameters
- An array is an array to be summed.
- An axis is an axis along which to sum the elements. If the axis is None, the array details are summed together.
- 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.
- An out is an output array. If out is not None, the result is stored in out.
Example
import numpy as np
# Sample NumPy array
arr = np.array([[1, 2, 3], [4, 5, 6]])
print("Array:")
print(arr)
# 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)
Output
Array:
[[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.