numpy.sum() in Python

numpy.sum() function in Python returns the sum of array elements along with the specified axis. So to get the sum of all element by rows or by columns numpy.sum() function is used.

Basic Syntax

numpy.sum(arr, axis, dtype, out)

And the parameters are:

ParameterDescription
arrThis is an input array
axis`[Optional]` axis = 0 indicates sum along columns and if axis = 1 indicates sum along rows. If not specifies then assumes the array is flattened
dtype`[Optional]` It is the type of the returned array and the accumulator in which the array elements are summed.
out`[Optional]` Alternate output array in which to place the result.

Return Value

It returns the sum of array elements along with the specified axis. And if the axis is not given then it will return `scalar` value.

Examples

Following are the examples of numpy.sum() function in Python.

Example 1: 1 dimensional array

The output should be:

Sum of items : 90.299999999999997
Is np.sum(items).dtype == np.uint : False
Is np.sum(items).dtype == np.float : True
Sum of items with dytype:uint8 : 90
Sum of items with dtype:float32 : 90.300003

Example 2: 2 dimensional array

The output should be:

Sum of items : ‘, 489.30000000000001
Is np.sum(items).dtype == np.uint : False
Is np.sum(items).dtype == np.float : True
Sum of items with dytype:uint8 : 233
Sum of items with dtype:float32 : 489.29999

Example 3: axis

The output should be:

Sum of items : 489.30000000000001
Sum of items with axis = 0 : [ 60. , 110. , 44.3, 108. , 167. ]
Sum of items with axis = 1 : [ 90.3, 298. , 75. , 26. ]