Python:NumPy .sum()
The .sum() method returns the sum of array elements over a given axis. It can compute the sum of all elements or along specific axes in multi-dimensional arrays.
Syntax
ndarray.sum(axis=None, dtype=None, out=None, keepdims=False, initial=0, where=True)
Parameters:
axis(int or tuple of ints, optional): Axis or axes along which to compute the sum. Default isNone, which sums over all elements.dtype(data-type, optional): Type of the returned array and of the accumulator. If not specified, defaults to the data type of the array.out(ndarray, optional): Alternative output array to place the result.keepdims(bool, optional): IfTrue, keeps the reduced dimensions with size 1. Default isFalse.initial(scalar, optional): Starting value for the sum. Default is 0.where(array_like of bool, optional): Elements to include in the sum. Default isTrue.
Return value:
Returns an ndarray containing the sum of elements. If axis is None, returns a scalar. Otherwise, returns an array with reduced dimensions.
Example 1: Sum of All Elements
In this example, the .sum() method calculates the total of all elements in the array:
import numpy as nparr = np.array([[1, 2, 3], [4, 5, 6]])result = arr.sum()print(result)
The above code returns the following output:
21
Example 2: Sum Along Specific Axis
In this example, the .sum() method computes sums along specific axes, by columns (axis=0) and by rows (axis=1):
import numpy as nparr = np.array([[1, 2, 3], [4, 5, 6]])# Sum along axis 0 (columns)col_sum = arr.sum(axis=0)print("Column sums:", col_sum)# Sum along axis 1 (rows)row_sum = arr.sum(axis=1)print("Row sums:", row_sum)
The above code returns the following output:
Column sums: [5 7 9]Row sums: [ 6 15]
Here, axis=0 sums each column, and axis=1 sums each row.
Codebyte Example: Using Initial Value and where Parameter
In this example, the .sum() method demonstrates how to use an initial value for the sum and how to include elements using the where parameter:
Note: For integer arrays, large sums may overflow. Use
dtype=np.int64orfloatfor safe accumulation.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:NumPy on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours