Open In App

numpy.nanprod() in Python

Last Updated : 01 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

numpy.nanprod() function computes the product of array elements over a given axis while treating NaN (Not a Number) values as 1 (i.e., ignoring them in the product). Example:

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

Output
8.0

Explanation: np.nanprod() ignores the NaN and returns the product of 1.0 * 2.0 * 4.0 = 8.0.

Syntax

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

Parameters:

  • a: Input array to compute the product over.
  • axis: Axis or axes along which the product 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 method returns the product of array elements (ignoring NaNs), optionally over the specified axis.

Examples

Example 1: Applying along rows using axis=1

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

Output
[2. 3.]

Explanation:

  • Row 0: 1 * 2 = 2
  • Row 1: np.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.nanprod(a, axis=1, keepdims=True)
print(res)

Output
[[2.]
 [3.]]

Explanation: The result keeps the original shape along the reduced axis (columns become 1-column).

Example 3: Specifying data type with dtype

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

Output
6.0

Explanation: Converts computation to float64 and computes 1 * 2 * 3 = 6.


Next Article

Similar Reads