Open In App

numpy.nansum() in Python

Last Updated : 30 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

numpy.nansum() function computes the sum of array elements over a given axis, treating NaN (Not a Number) values as zero. This is useful when you want to ignore missing or undefined values in your computation.

For Example:

Python
import numpy as np
a = np.array([1.0, 2.0, np.nan, 4.0])
res = np.nansum(a)
print(res)

Output
7.0

Explanation: np.nansum() ignores the NaN and returns the sum of 1.0 + 2.0 + 4.0 = 7.0.

Syntax

numpy.nansum(a, axis=None, dtype=None, keepdims=<no value>)

Parameters:

  • a: Input array to compute the sum over.
  • axis: Axis or axes along which the sum is computed; default is all elements.
  • dtype: Desired data type of the returned array.
  • keepdims: If True, retains reduced dimensions with size one.

Returns: This function returns the sum of array elements (ignoring NaNs), optionally over the specified axis.

Examples of numpy.nansum()

Example 1: Applying along rows using axis=1

Python
import numpy as np
a = np.array([[1, 2], [np.nan, 3]])
res = np.nansum(a, axis=1)
print(res)

Output
[3. 3.]

Explanation:

  • Row 0: 1 + 2 = 3
  • Row 1: NaN is ignored, so 3 is returned

Example 2: Using keepdims=True

Python
import numpy as np
a = np.array([[1, 2], [np.nan, 3]])
res = np.nansum(a, axis=1, keepdims=True)
print(res)

Output
[[3.]
 [3.]]

Explanation: The result keeps the original shape along the reduced axis (1-column instead of reducing to 1D array).

Example 3: Specifying data type with dtype

Python
import numpy as np
a = np.array([1, 2, 3], dtype=np.int32)
res = np.nansum(a, dtype=np.float64)
print(res)

Output
6.0

Explanation: Computation is done in float64 and the result is the sum 1 + 2 + 3 = 6.


Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy