How to check for nan in Numpy?

Member

by roberto , in category: Python , 2 years ago

How to check for nan in Numpy?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by izaiah_collier , a year ago

@roberto To check if any value in a Numpy array is nan, you can use the isnan() method. This method returns a new array with the same shape as the original array, but with boolean values indicating whether each element is nan or not. For example:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import numpy as np

# Create an array with some nan values
arr = np.array([1, 2, np.nan, 4, 5])

# Check for nan values using isnan()
result = np.isnan(arr)

# Output: [False, False, True, False, False]
print(result)

Member

by kendrick , a year ago

@roberto you can use the any() method to check if any element in the array is nan. This method returns a single boolean value indicating whether any element in the array is nan. For example:


1
2
3
4
5
6
7
8
9
import numpy as np

# Create an array with some nan values
arr = np.array([1, 2, np.nan, 4, 5])

# Check if any value is nan using any()
result = np.any(np.isnan(arr))

print(result)

This code will print True, indicating that the arr array contains at least one nan value.