How to Use NumPy Sum() in Python

  • Post author:
  • Post category:NumPy / Python
  • Post last modified:January 27, 2023
Spread the love

NumPy sum() function in python is used to return the sum/total of all elements over a given array. This function takes several arguments, among use dtype argument to specify the returned data type and use the initial argument to specify the initial value to consider for the sum.

Using this function you can do the following.

  • Get the sum of all array elements of the given array,
  • Get the sum of each row over a specified axis, and
  • Get the sum of each column of a given array.

In this article, I will explain the syntax of numpy sum() function, the different arguments it takes, and its usage by examples like how to calculate the sum values of the given array. For more examples of NumPy, refer to NumPy Tutorial

1. Quick Examples of NumPy Sum Function

If you are in a hurry, below are some quick examples of how to use NumPy sum() function.


# Below are the quick examples

# Example 1: # Create a numpy array
# Get the sum of an array 
arr = np.array([14, 17, 19, 22])
sum = np.sum(arr)

# Example 2: Create 2-D numpy array
# Get the Sum of all the elements in an array            
arr = np.array([[12, 14], [17, 19],[13, 16],[24, 27]])
sum = np.sum(arr)

# Example 3: Get the sum of each column element along axis = 0
sum = np.sum(arr, axis=0)

# Example 4: Get the sum of each row element along axis = 1
sum = np.sum(arr, axis=1)

# Example 5: Get the sum of an array to specify data type 
sum = np.sum(arr, axis=1, dtype=float)

# Example 6: Specify an initial value for the sum
sum = np.sum(arr, axis=1, initial=15)

# Example 7: Get the sum using nansum()
arr = np.array([[2, 3], [4, np.nan]])
arr1 = np.nansum(arr)

2. Syntax of sum()

The following is the syntax of the sum() function.


# Syntax of sum()
numpy.sum(array, axis=None, dtype=None, out=None, keepdims=, initial=)

2.1 Parameters of sum()

Below are the parameters of the sum() function.

  • array – Input array, in which the elements to be calculated as a sum.
  • axis – Axis or axes along which a sum is performed. The default, axis=None, it sums all of the elements of the input array. If the axis is negative the counts start from the last to the first axis. axis = 0 means along the column and axis = 1 means working along the row.
  • dtype – You can use dtype to specify the returned output data type.
  • out – Alternative output array in which to place the result. The array must have the same dimensions as the expected output. Default is None.
  • keepdims – The keepdims is a boolean parameter. If this is set to True, the axes which are reduced are left in the result as dimensions with size one.
  • initial – The initial parameter provides the Starting value for the sum.

2.2 Return Value of sum()

It returns an array, it contains the sum of elements of the input array along with the specified axis. If the axis = None then it will return a scalar value.

3. Usage of NumPy sum() Function

The sum() function in NumPy package of Python is used to calculate the total of all elements, the total of each row, and the total of each column of a given array.

3.1 Get the Sum of 1-D Array

Let’s see how to calculate the sum of all elements of the 1-dimensional array, In order to do so first, let’s initialize the 1-D NumPy array using numpy.array() and pass this array as input to the sum().


import numpy as np

# Create a numpy array
arr = np.array([14, 17, 19, 22])

# Get the sum of an array 
sum = np.sum(arr)
print(sum)

# Output
# 72

3.2 Get the Sum of 2-D Array

Let’s compute the sum of all the elements of the 2-D array. When using the 2-D array, it considers all values in the array to calculate the sum and returns a scalar value. It considers axis=None by default. Note that it doesn’t calculate the sum of each row or the sum of each column instead calculates the sum of all values.


# Create 2-D numpy array
arr = np.array([[12, 14], [17, 19],[13, 16],[24, 27]])

# Get the Sum of all the elements in an array            
sum = np.sum(arr)
print("Sum of all the elements is :", sum)

# Output
# Sum of all the elements is : 142

4. Get the Sum of Each Column of 2-D Array

In order to calculate the sum for each column of NumPy array, specify the axis = 0 . This gets you to sum along the column axis when you have a 2-dimensional array. This returns the ndarray of size equal to the number of columns in your array.


# Get the sum of each column element along axis = 0
sum = np.sum(arr, axis=0)
print(sum)

# Output
# [66 76]

5 Get the Sum of Each Row of 2-D Array

Similarly, to calculate the sum for each row, specify the axis = 1. This gets you to sum along the rows axis. This returns the ndarray of size equal to the number of rows in your array.


# Get the sum of each row element along axis = 1
sum = np.sum(arr, axis=1)
print(sum)

# Output
# [26 36 29 51]

6. Specify the Type of the Return Value

By default, the return type of NumPy sum() will be equal to the type of your input array elements. In our above examples, we have arrays of type int hence, the result is also in int type. Let’s change this by specifying the dtype argument. Using this argument you can specify the return type of the sum() function.

The following example calculates the sum for each row and returns the sum in float type.


# Get the sum of an array to specify data type 
sum = np.sum(arr, axis=1, dtype=float)
print(sum)

# OutPut
# [26. 36. 29. 51.]

7. Consider Initial Value to NumPy sum()

You can also start the sum with an initial value other than zero by using the initial argument. When used initial argument, the sum() starts with this initial value and adds all elements to it to get the final sum/total value.


# Specify an initial value for the sum
sum = np.sum(arr, axis=1, initial=15)
print(sum)

# Output
# [41 51 44 66]

8. Get the Sum using np.NaN

If you have NaN values in your array, applying the sum() function results in nan output. To overcome this use nansum() function, nansum() is used to calculate the sum of the array ignoring the nan values. This function is also used to sum all elements, the sum of each row, and the sum of each column of a given array by ignoring NaN values.


# Get the sum using nansum()
arr = np.array([[2, 3], [4, np.nan]])
arr1 = np.nansum(arr)
print(arr1)

# Output :
# 9.0

7. Conclusion

In this article, I have explained how to use the Python NumPy sum function(). Use this function to compute the sum of the array elements along with specified axis, datatype, and initial value with examples. And also learn what happens if you have NaN values in the array and how to overcome this by using nansum() function.

Happy Learning!!

References

Leave a Reply

You are currently viewing How to Use NumPy Sum() in Python