Return the maximum of an array or maximum ignoring any NaNs in Python
Last Updated :
29 Dec, 2022
In this article, we will cover how to return the maximum of an array or maximum by ignoring any NaNs in Python using NumPy.
Example
Input: [ -1. -2. nan 1000.]
Output: 1000.0
Explanation: maximum value of the array ignoring nans.
One approach to use the built-in Python function max(), along with the filter() function and the math.isnan() function from the math module to ignore any NaN values in the array.
Here is an example of how this can be done
Python3
import math
def ignore_nan(arr):
return max(filter(lambda x: not math.isnan(x), arr))
# Example usage
arr = [-1, -2, float('nan'), 1000]
result = ignore_nan(arr)
print(result) # Output: 1000
This approach first filters out any NaN values from the array using the filter() function, which applies the function provided as the first argument (in this case, math.isnan()) to each element in the array and returns a new iterator with only the elements for which the function returns True. The max() function is then applied to this filtered iterator to find the maximum value.
The numpy.nanmax() method from NumPy returns the highest value or the maximum value in an array or the highest value along an axis, ignoring any NaNs.
Syntax: numpy.nanmax(a, axis=None, out=None)
Parameters:
- a: array like object.
- axis: by default None.
- out : by default None.
Return: maximum array value(a scalar value if axis is none)or array with maximum value along specified axis.
Example 1:
In this example, the NumPy package is imported. An array is created using numpy.array() method which contains nan and other values and np.nanmax() returns the maximum value of the array ignoring nans. The shape, datatype, and dimensions of the array can be found by .shape, .dtype, and .ndim attributes.
Python3
import numpy as np
# Creating an array
array = np.array([-1, -2 , np.nan, 1000])
print(array)
# shape of the array is
print("Shape of the array is : ",array.shape)
# dimension of the array
print("The dimension of the array is : ",array.ndim)
# Datatype of the array
print("Datatype of our Array is : ",array.dtype)
# computing the maximum or array ignoring Nans
print(np.nanmax(array))
Output:
[ -1. -2. nan 1000.]
Shape of the array is : (4,)
The dimension of the array is : 1
Datatype of our Array is : float64
1000.0
Example 2:
In case our array contains np.inf or positive infinity np.nanmax() method returns inf.
Python3
import numpy as np
# Creating an array
array = np.array([-1, -2 , np.inf,np.nan, 1000])
print(array)
# shape of the array is
print("Shape of the array is : ",array.shape)
# dimension of the array
print("The dimension of the array is : ",array.ndim)
# Datatype of the array
print("Datatype of our Array is : ",array.dtype)
# computing the maximum or array ignoring Nans
print(np.nanmax(array))
Output:
[ -1. -2. inf nan 1000.]
Shape of the array is : (5,)
The dimension of the array is : 1
Datatype of our Array is : float64
inf
Example 3:
If all the elements in the array are nan, then the method raises a runtime warning saying "RuntimeWarning: All-NaN slice encountered".
Python3
import numpy as np
# Creating an array
array = np.array([np.nan, np.nan])
print(array)
# shape of the array is
print("Shape of the array is : ",array.shape)
# dimension of the array
print("The dimension of the array is : ",array.ndim)
# Datatype of the array
print("Datatype of our Array is : ",array.dtype)
# computing the maximum or array ignoring Nans
print(np.nanmax(array))
Output:
[nan nan]
Shape of the array is : (2,)
The dimension of the array is : 1
Datatype of our Array is : float64
nan
RuntimeWarning: All-NaN slice encountered
Similar Reads
Find the maximum and minimum element in a NumPy array An array can be considered as a container with the same types of elements. Python has its array module named array. We can simply import the module and create our array. But this module has some of its drawbacks. The main disadvantage is we can't create a multidimensional array. And the data type mu
4 min read
Return the cumulative product of array elements over axis 0 treating NaNs as one in Python In this article, we will discuss how to find the result of the power to which the negative input value is raised with Python and NumPy. ExampleInput: [[10. nan][nan 20.]] Output: [ 10. 10. 10. 200.] Explanation: The cumulative product of array elements over a given axis.NumPy.nancumprod method The n
3 min read
Return the infinity Norm of the matrix in Linear Algebra using NumPy in Python In this article, we will how to return the infinity Norm of the matrix in Linear Algebra in Numpy using Python. numpy.linalg.norm() method The numpy.linalg.norm() method returns the matrix's infinite norm in Python linear algebra. This function can return one of eight possible matrix norms or an inf
3 min read
Calculate the difference between the maximum and the minimum values of a given NumPy array along the second axis Let's see how to calculate the difference between the maximum and the minimum values of a given NumPy array along the second axis. Here, the Second axis means row-wise. So firstly for finding the row-wise maximum and minimum elements in a NumPy array we are using numpy.amax() and numpy.amin() functi
2 min read
Python map function to find row with maximum number of 1's Given a boolean 2D array, where each row is sorted. Find the row with the maximum number of 1s. Examples: Input: matrix = [[0, 1, 1, 1], [0, 0, 1, 1], [1, 1, 1, 1], [0, 0, 0, 0]] Output: 2 We have existing solution for this problem please refer Find the row with maximum number of 1's. We can solve t
1 min read
Find Maximum of two numbers in Python Finding the maximum of two numbers in Python helps determine the larger of the two values. For example, given two numbers a = 7 and b = 3, you may want to extract the larger number, which in this case is 7. Let's explore different ways to do this efficiently.Using max()max() function is the most opt
2 min read
How to Get the maximum value from the Pandas dataframe in Python? Python Pandas max() function returns the maximum of the values over the requested axis. Syntax: dataframe.max(axis) where, axis=0 specifies columnaxis=1 specifies rowExample 1: Get maximum value in dataframe row To get the maximum value in a dataframe row simply call the max() function with axis set
2 min read
Python - Maximum sum of elements of list in a list of lists In this problem, we need to find the maximum sum of elements in a list of lists. A list of lists is a collection of sub-lists and each sub-list contains individual elements. The problem is to find the maximum sum among all the sub-lists. Let's explore various ways to solve this problem.Using sum() w
3 min read
Python | Pandas series.cummax() to find Cumulative maximum of a series Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Series.cummax() is used to find Cumulative maximum of a series. In cumulative m
3 min read
Python | Max/Min value in Nth Column in Matrix Sometimes, while working with Python Matrix, we may have a problem in which we require to find the minimum and maximum value of a particular column. This can have a possible application in day-day programming and competitive programming. Let's discuss certain ways in which this task can be performed
7 min read