NumPy nanmax()

The numpy.nanmax() function computes the maximum of an array or along a specified axis while ignoring NaN (Not a Number) values. If all values in a slice are NaN, a RuntimeWarning is raised, and NaN is returned for that slice.

Syntax

</>
Copy
numpy.nanmax(a, axis=None, out=None, keepdims=False, initial=None, where=True)

Parameters

ParameterTypeDescription
aarray_likeInput array containing numbers. If not an array, it is converted.
axisint, tuple of int, or None, optionalAxis along which the maximum is computed. Default is to compute the maximum of the entire array.
outndarray, optionalOptional output array where the result is stored. Must have the same shape as the expected output.
keepdimsbool, optionalIf True, retains reduced dimensions with size one for broadcasting.
initialscalar, optionalSpecifies the minimum value of an output element. Required when computing on an empty slice.
wherearray_like of bool, optionalElements to consider when computing the maximum. Newly added in NumPy 1.22.0.

Return Value

Returns an array with the maximum values, with the specified axis removed. If the input is a scalar, a scalar is returned.


Examples

1. Computing Maximum While Ignoring NaN

In this example, we compute the maximum of an array containing NaN values.

</>
Copy
import numpy as np

# Define an array with NaN values
arr = np.array([3, np.nan, 7, 1, np.nan, 5])

# Compute the maximum while ignoring NaN values
result = np.nanmax(arr)

# Print the result
print("Maximum value ignoring NaN:", result)

Output:

Maximum value ignoring NaN: 7.0