The Numpy `sum()`

function in Python is used to compute the sum/total of array elements along a specified axis or all axes if none is specified. 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 the NumPy `sum()`

function, the different arguments it takes, and its usage with 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 the NumPy sum() function.

```
# Quick examples of numpy sum function
# 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`

– This is the input array or object that you want to calculate the sum of.`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 reduced axes 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

To get the sum of a 1-D NumPy array, you can use the `numpy.sum()`

function. For instance, `arr`

is a 1-dimensional NumPy array containing the values `[14, 17, 19, 22]`

. The `np.sum(arr)`

calculates the sum of all these values, and the result is then printed to the console.

```
# Import numpy
import numpy as np
# Create a numpy array
arr = np.array([14, 17, 19, 22])
print("Original array:", arr)
# Get the sum of an array
sum = np.sum(arr)
print("Sum of the 1-D array:", sum)
```

Yields below output.

You can use a similar approach for 1-D arrays of any length and with different values. The `numpy.sum()`

function is versatile and can handle various numeric data types.

### 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]])
print("Original array:\n", arr)
# Get the Sum of all the elements in an array
sum = np.sum(arr)
print("Sum of the 2-D array along all axes:\n",sum)
```

Yields below output.

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

If you want to get the sum of each column in a 2-D NumPy array, you can use the `numpy.sum()`

function with the `axis`

parameter set to `0`

. This will sum the elements along each column.

In the below example, `axis=0`

specifies that the sum should be calculated along the first axis (which is the vertical axis, corresponding to columns). The result is an array containing the sum of each column.

```
# Get the sum of each column element
# Along axis = 0
sum = np.sum(arr, axis=0)
print("Sum of each column:\n",sum)
# Output:
# Sum of each column:
# [66 76]
```

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

Similarly, to get the sum of each row in a 2-D NumPy array, you can use the `numpy.sum()`

function with the `axis`

parameter set to `1`

. This will sum the elements along each row.

In the below example, `axis=1`

specifies that the sum should be calculated along the second axis (which is the horizontal axis, corresponding to rows). The result is an array containing the sum of each row.

```
# Get the sum of each row element
# Along axis = 1
sum = np.sum(arr, axis=1)
print("Sum of each row:\n", sum)
# Output:
# Sum of each row:
# [26 36 29 51]
```

## 6. Specify the Type of the Return Value

To get the sum of each row in a 2-D NumPy array with a specified data type. For example, `dtype=float`

specifies that the resulting sum should be of type float for each row. This can be useful when you want to ensure a specific type for the result.

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 of each row with data type specified:\n", sum)
# Output:
# Sum of each row with data type specified:
# [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 of each row with initial value specified:\n", sum)
# Output:
# Sum of each row with initial value specified:
# [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
```

## Frequently Asked Questions

**What does numpy.sum() do?**

The `numpy.sum()`

is a function in the NumPy library that calculates the sum of array elements along specified axes or all axes if none is specified. It’s a versatile function commonly used for numerical computations.

**How to calculate the sum of all elements in a 1-D array?**

To calculate the sum of all elements in a 1-D NumPy array, you can use the `numpy.sum()`

function without specifying the `axis`

parameter.

**How to calculate the sum of each column in a 2-D array?**

To calculate the sum of each column in a 2-D NumPy array, you can use the `numpy.sum()`

function with the `axis`

parameter set to `0`

. This specifies that the sum should be calculated along the first axis, which corresponds to columns

**Can I specify the data type of the sum?**

You can specify the data type of the sum when using the `numpy.sum()`

function by using the `dtype`

parameter. This allows you to set the desired data type for the result.

**How to handle NaN values in the array?**

To handle NaN (Not a Number) values in the array when calculating the sum, you can use the `numpy.nansum()`

function. This function is designed to calculate the sum while ignoring NaN values.

**What if I want to add an initial value to the sum?**

If you want to add an initial value to the sum when using `numpy.sum()`

, you can utilize the `initial`

parameter. This parameter allows you to specify a value that is added to the sum of array elements.

## 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 the specified axis, datatype, and initial value with examples. Also, learn what happens if you have NaN values in the array and how to overcome this by using `nansum()`

function.

Happy Learning!!

## Related Articles

- How to use median() in NumPy
- NumPy percentile() Function
- How to Use NumPy pad() in Python
- Python NumPy Array Copy
- How to Convert NumPy Array to List
- How to transpose() NumPy Array in Python
- How to Use NumPy random.normal() In Python?
- How to Use NumPy logspace() in Python
- How to Use NumPy random seed() in Python
- How to Use Numpy random.rand() in Python
- How to Use NumPy random.randn() in Python?
- How to Use NumPy random.randint() in Python