Compare two arrays and return the element-wise maximum ignoring NaNs in Numpy

NumpyServer Side ProgrammingProgramming

To compare two arrays and return the element-wise maximum ignoring NaNs, use the numpy.fmax() method in Python Numpy. Return value is either True or False.

Compare two arrays and returns a new array containing the element-wise maxima. If one of the elements being compared is a NaN, then the non-nan element is returned. If both elements are NaNs then the first is returned. The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are ignored when possible.

Steps

At first, import the required library −

import numpy as np

Creating two 2D numpy array using the array() method. We have inserted elements with some NaN values −

arr1 = np.array([[6, 9, np.NaN],[25, 11, 21]])
arr2 = np.array([[8, np.NaN, np.NaN],[22, 19, 26]])

Display the arrays −

print("Array 1...\n", arr1)
print("\nArray 2...\n", arr2)

Get the type of the arrays −

print("\nOur Array 1 type...\n", arr1.dtype)
print("\nOur Array 2 type...\n", arr2.dtype)

Get the dimensions of the Arrays −

print("\nOur Array 1 Dimensions...\n",arr1.ndim)
print("\nOur Array 2 Dimensions...\n",arr2.ndim)

Get the shape of the Arrays −

print("\nOur Array 1 Shape...\n",arr1.shape)
print("\nOur Array 2 Shape...\n",arr2.shape)

To compare two arrays and return the element-wise maximum ignoring NaNs, use the numpy.fmax() method in Python Numpy. Return value is either True or False −

print("\nResult (maximum ignoring NaNs)...\n",np.fmax(arr1, arr2))

Example

import numpy as np

# Creating two 2D numpy array using the array() method
# We have inserted elements with some NaN values
arr1 = np.array([[6, 9, np.NaN],[25, 11, 21]])
arr2 = np.array([[8, np.NaN, np.NaN],[22, 19, 26]])

# Display the arrays
print("Array 1...\n", arr1)
print("\nArray 2...\n", arr2)

# Get the type of the arrays
print("\nOur Array 1 type...\n", arr1.dtype)
print("\nOur Array 2 type...\n", arr2.dtype)

# Get the dimensions of the Arrays
print("\nOur Array 1 Dimensions...\n",arr1.ndim)
print("\nOur Array 2 Dimensions...\n",arr2.ndim)

# Get the shape of the Arrays
print("\nOur Array 1 Shape...\n",arr1.shape)
print("\nOur Array 2 Shape...\n",arr2.shape)

# To compare two arrays and return the element-wise maximum ignoring NaNs, use the numpy.fmax() method in Python Numpy
# Return value is either True or False
print("\nResult (maximum ignoring NaNs)...\n",np.fmax(arr1, arr2))

Output

Array 1...
[[ 6. 9. nan]
[25. 11. 21.]]

Array 2...
[[ 8. nan nan]
[22. 19. 26.]]

Our Array 1 type...
float64

Our Array 2 type...
float64

Our Array 1 Dimensions...
2

Our Array 2 Dimensions...
2

Our Array 1 Shape...
(2, 3)

Our Array 2 Shape...
(2, 3)

Result (maximum ignoring NaNs)...
[[ 8. 9. nan]
[25. 19. 26.]]
raja
Updated on 07-Feb-2022 11:13:20

Advertisements