numpy.nansum

numpy.nansum(a, axis=None)

Return the sum of array elements over a given axis treating Not a Numbers (NaNs) as zero.

Parameters:

a : array_like

Array containing numbers whose sum is desired. If a is not an array, a conversion is attempted.

axis : int, optional

Axis along which the sum is computed. The default is to compute the sum of the flattened array.

Returns:

y : ndarray

An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned with the same dtype as a.

See also

numpy.sum
Sum across array including Not a Numbers.
isnan
Shows which elements are Not a Number (NaN).
isfinite
Shows which elements are not: Not a Number, positive and negative infinity

Notes

Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity. If positive or negative infinity are present the result is positive or negative infinity. But if both positive and negative infinity are present, the result is Not A Number (NaN).

Arithmetic is modular when using integer types (all elements of a must be finite i.e. no elements that are NaNs, positive infinity and negative infinity because NaNs are floating point types), and no error is raised on overflow.

Examples

>>> np.nansum(1)
1
>>> np.nansum([1])
1
>>> np.nansum([1, np.nan])
1.0
>>> a = np.array([[1, 1], [1, np.nan]])
>>> np.nansum(a)
3.0
>>> np.nansum(a, axis=0)
array([ 2.,  1.])

When positive infinity and negative infinity are present

>>> np.nansum([1, np.nan, np.inf])
inf
>>> np.nansum([1, np.nan, np.NINF])
-inf
>>> np.nansum([1, np.nan, np.inf, np.NINF])
nan

Previous topic

numpy.sum

Next topic

numpy.cumprod

This Page

Quick search