Trusted answers to developer questions

What is numpy.sum() in Python?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

Python’s numpy.sum() computes the sum of an array over a specified axis.

Syntax

numpy.sum() is declared as follows:

numpy.sum(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)

In the syntax above, a is the non-optional parameter, and the rest are optional parameters.

Parameters

numpy.sum() takes the following non-optional parameter:

  • a [array-like] - input array that contains the elements to be added.

numpy.sum() takes the following optional parameters:

  • axis [None, int, tuples of int] - axis along which we want the sum to be computed. If the axis is None, it will sum all the elements of the input array. If the axis is negative, the sum is computed from the last to the first axis. An axis with a value of 0 will compute the sum along the column, and an axis with a value of 1 will compute the sum along the row.

  • out [ndarray] - represents the location into which the output is stored.

  • dytpe [dtype] - represents the returned array type and the accumulator in which the elements are summed. By default, the dtype of the input array is used.

  • keepdims [boolean] - true value ensures that the reduced axes are left as dimensions with size one in the output. This ensures that the output is broadcasted correctly against the input array. If a non-default value is passed, keepdims will be passed through to the sum() method of sub-classes of ndarray. In the case of the default value, this will not be done.

  • initial [scalar] - minimum value of the output element.

  • where [array_like of bool] - represents the elements to compare for the minimum.

Return value

numpy.sum() returns an array with the same shape as the input array, with the specified axis removed.

  • If a is a zero-dimensional array, a scalar is returned.

  • If axis is None, a scalar is returned.

  • If an output array is specified in the out parameter, a reference to out is returned.

Examples

The following example outputs the sum of the array arr where the axis parameter is not specified:

Press + to interact
import numpy as np
arr = np.array([1,2,5,6,0])
print(np.sum(arr))

The example below outputs the sum of the array arr1 where axis is specified as 0 and 1.

Press + to interact
import numpy as np
arr1 = np.array([[2,4,5], [7,10,1]])
#Sum along the columns
print(np.sum(arr1, axis = 0))
#Sum along the rows
print(np.sum(arr1, axis = 1))

RELATED TAGS

numpy
python

CONTRIBUTOR

Umme Ammara
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?