The numpy.nansum()
function in NumPy is used to return the sum of elements in a given array over a given axis in such a way that the NaNs
are treated as zeroes.
numpy.nansum(a, axis=None, dtype=None, out=None)
The numpy.nansum()
function takes the following parameter values:
a
(required): This is the input array containing numbers to be computed.axis
(optional): This is the axis along which the product is determined.dtype
(optional): This is the data-type of the output array.out
(optional): This is the alternate array where the result is placed.The numpy.nansum()
function returns an output array with the result.
Let’s look at the code below:
import numpy as np# creating an arrayx = np.array([1, 2, np.nan, 2, np.nan])# Implementing the nansum() functionmyarray = np.nansum(x, axis=0)print(x)print(myarray)
numpy
module.x
, using the array()
method.np.nansum()
function on the array. The result is assigned to a variable, myarray
.x
.myarray
.Note: The output
4
is obtained from the sum of the elements: 1+2+np.nan+2+np.nan = 1+2+0+2+0 = 4. This is becauseNans
values are treated as0
.