The sum()
function is used to calculate the sum of array elements along a specified axis or across all axes.
import numpy as np
array1 = np.array([1, 2, 3, 4, 5])
# use sum() to calculate sum of array1 elements
result = np.sum(array1)
print(result)
# Output : 15
sum() Syntax
The syntax of sum()
is:
numpy.sum(array, axis=None, dtype=None, out=None, keepdims=<no value>)
sum() Arguments
The sum()
function takes following arguments:
array
- the input arrayaxis
(optional) - the axis along which the sum is calculateddtype
(optional) - the data type of the returned sumout
(optional) - the output array where the result will be storedkeepdims
(optional) - whether to preserve the input array's dimension (bool
)
sum() Return Value
The sum()
function returns the sum of array elements
Example 1: sum() With 2-D Array
The axis
argument defines how we can find the sum of elements in a 2-D array.
- If
axis
=None
, the array is flattened and the sum of the flattened array is returned. - If
axis
= 0, the sum is calculated column-wise. - If
axis
= 1, the sum is calculated row-wise.
import numpy as np
array = np.array([[10, 17, 25],
[15, 11, 22]])
# return the sum of elements of the flattened array
result1 = np.sum(array)
print('The sum of flattened array: ', result1)
# return the column-wise sum
result2 = np.sum(array, axis = 0)
print('Column-wise sum (axis 0): ', result2)
# return the row-wise sum
result2 = np.sum(array, axis = 1)
print('Row-wise sum (axis 1): ', result2)
Output
The sum of flattened array: 100 Column-wise sum (axis 0): [25 28 47] Row-wise sum (axis 1): [52 48]
Example 2: Use of out Argument in sum()
import numpy as np
array1 = np.array([[10, 17, 25],
[15, 11, 22],
[11, 19, 20]])
# create an empty array
array2= np.array([0, 0, 0])
# pass the 'out' argument to store the result in array2
np.sum(array1, axis = 0, out = array2)
print(array2)
Output
[36 47 67]
Here, after specifying out=array2
, the result of sum of array1 along axis=0
is stored in the array2 array.
Example 3: sum() With keepdims
When keepdims = True
, the dimensions of the resulting array matches the dimension of an input array.
import numpy as np
array1 = np.array([[10, 17, 25],
[15, 11, 22]])
print('Dimensions of original array: ', array1.ndim)
result = np.sum(array1, axis = 1)
print('\n Without keepdims: \n', result)
print('Dimensions of array: ', result.ndim)
# set keepdims to True to retain the dimension of the input array
result = np.sum(array1, axis = 1, keepdims = True)
print('\n With keepdims: \n', result)
print('Dimensions of array: ', result.ndim)
Output
Dimensions of original array: 2 Without keepdims: [52 48] Dimensions of array: 1 With keepdims: [[52] [48]] Dimensions of array: 2
Without keepdims
, the result is simply a one-dimensional array of indices.
With keepdims
, the resulting array has the same number of dimensions as the input array.