Return the maximum of an array along axis 0 or maximum ignoring any NaNs in Python


To return the maximum of an array along axis 0 in Python, we can use the numpy.amax() function. Here's an example:

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
max_arr = np.amax(arr, axis=0)

print(max_arr)

Output:

[7 8 9]

Here, we first import the numpy library and create a 2D array arr. We then use the numpy.amax() function to find the maximum value along axis 0 (i.e., column-wise). The resulting array max_arr contains the maximum value of each column.

To return the maximum ignoring any NaNs in Python, we can use the numpy.nanmax() function. Here's an example:

import numpy as np

arr = np.array([1, 2, np.nan, 4, 5])
max_arr = np.nanmax(arr)

print(max_arr)

Output:

5.0

Here, we first import the numpy library and create a 1D array arr with a NaN value. We then use the numpy.nanmax() function to find the maximum value ignoring any NaNs. The resulting value max_arr is 5.0, which is the maximum value in the array after ignoring the NaN value.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.