Python

# Numpy np.sum()

Numpy is one of the most popular and valuable packages in scientific computation using python. It provides tools and objects that facilitate rapid calculation, such as multi-dimensional arrays, matrices, etc.

It also provides easy-to-use functions and utilities for performing complex computations, including sorting, selection, transformations, statistical analysis, etc.

In this tutorial, we will attempt to explain how to use the sum function in Numpy.

## NumPy Sum Function

The numpy.sum() function allows us to calculate the sum of elements in an array over a given axis.

Before diving into the function syntax and usage, let us elaborate on an array axis.

In Numpy, a 2D array is comprised of 2 axes. The first axes run vertically across the rows. This is known as axis 0.

NOTE: In most cases, you will be working along these axes in NumPy. For arrays above 2-dimensions, you can have axes above axis 1.

## NumPy Sum Function Syntax

The syntax of the sum function is as shown below:

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

The function parameters are as shown below:

1. array – refers to the input array from which to sum the elements.
2. axis – defines the axes along which the sum function is applied. By default, the value is None which flattens the array and adds all the elements in the array.
3. dtype – determines the type of the returned array and the accumulator in which the array elements are added. If not specified, the function will use the data type of the input array
4. out – this parameter allows you to set an alternative output array to save the results. The alternative array must be of the appropriate shape as the expected output.
5. keepdims – a Boolean type that allows you to leave the reduced axes as dimensions with size one when true.
6. initial – sets a starting value for the sum.
7. where – specifies which element to include in the sum.

## Function Return Value

The sum function returns an array of the same shape as the input array with the specified axis removed. The function will return a scalar value if the axis is set to None or the input array is 0 dimensional.

## Examples

Let us look at a few examples of using the sum function.

Start by importing numpy as shown:

# import numpy
import numpy as np

Next, create a 1-dimensional array as shown below:

# 1D array
arr = [5, 0.7, 20, 15, 5.1]

To sum all the elements in the array, we can call the sum function and set the axis to None, as shown below:

print(f"Sum of all elements: {np.sum(arr, axis=None)}")

The code above should return:

Sum of all elements: 45.800000000000004

To specify a custom return type, we can use the dtype parameter as shown below:

print(f"Sum of all elements: {np.sum(arr, axis=None, dtype=np.int32)}")

In this case, we tell NumPy to return the sum as a 32-bit signed integer. The output is as shown:

Sum of all elements: 45

## Example 2

Let us demonstrate how to use the sum function on a 2-dimensional array.

Start by creating a 2D array as shown:

# 2D array
arr = [[ 3,  .2,  4,  8],
[ 10,  .45,  3,  16],
[27,  9,  6,  3],
[64, .16,  .4,  1]]

To add all elements in the array, run the sum function with the axis parameter set to None as shown below:

print(f"sum: {np.sum(arr, axis=None)}")

This should return:

sum: 155.20999999999998

To add elements along the 0 axis, we can do:

print(f"sum (axis 0): {np.sum(arr, axis=0)}")

The code above should return an array with the sum of values along the 0 axis as shown:

sum (axis 0): [104.     9.81  13.4   28.  ]

The function will take the elements along the 0 axis as:

64 + 27 + 10 +3 = 104
.2 + .45 + 9 + .16 = 9.81
4 + 6 + 3 + .4 = 13.4
8 +16 + 3  + 1 = 28
// combine the above elements into an array as
[104 9.81 13.4 28]

You can also perform an additional along with the columns by specifying the axis is 1. An example is as shown:

print(f"sum (axis 1): {np.sum(arr, axis=1)}")

In this case, the sum function performs the addition across the columns and returns an array as shown:

sum (axis 1): [15.2  29.45 45.   65.56]

We can also tell the sum function to keep the dimensions by setting the keepdims parameter to true.

An example is as shown below:

print(f"sum (axis 1): {np.sum(arr, axis=1, keepdims=True)}")

This should return:

sum (axis 1): [[15.2 ]
[29.45]
[45.  ]
[65.56]]

You can also specify an initial sum value added to each element in the output array.

Consider an example shown below:

print(f"sum (axis 1): {np.sum(arr, axis=1, keepdims=True, initial=1)}")

In the code above, we set the initial value to 1. This value is then added to each element of the output array.

This should return:

sum (axis 1): [[16.2 ]
[30.45]
[46.  ]
[66.56]]

## Conclusion

In this article, you gained a deep understanding of using and working with the numpy.sum() function. This function allows you to sum elements of an array along specified axes and return the value.