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
| Parameter | Type | Description |
|---|---|---|
a | array_like | Input array containing numbers. If not an array, it is converted. |
axis | int, tuple of int, or None, optional | Axis along which the maximum is computed. Default is to compute the maximum of the entire array. |
out | ndarray, optional | Optional output array where the result is stored. Must have the same shape as the expected output. |
keepdims | bool, optional | If True, retains reduced dimensions with size one for broadcasting. |
initial | scalar, optional | Specifies the minimum value of an output element. Required when computing on an empty slice. |
where | array_like of bool, optional | Elements 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
