How can I check for NaN values?
You can use the isnan() function provided by the math module to check if a value is NaN.
You can use the isnan() function provided by the math module to check if a value is NaN.
Here's an example:
Check for NaN values in Python, using the isnan method
import math
x = float('nan')
if math.isnan(x):
print('x is NaN')
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
You can also call math.isnan() directly on any numeric variable.
Check for NaN values in Python, using the isnan method as a standalone function
import math
x = float('nan')
if math.isnan(x):
print('x is NaN')You can also use the math.isnan() function to check for NaN values in a list or array.
Check for NaN values inside an array in Python, using the isnan method
import math
arr = [1, 2, float('nan'), 3, 4]
for value in arr:
if math.isnan(value):
print('Found a NaN value')Note that math.isnan() only accepts numeric types. Passing non-numeric types (like strings or lists) raises a TypeError. To safely check for NaN in mixed-type collections, verify the type first using isinstance() before calling math.isnan().
Check for NaN values inside an array in Python, using the isnan method along with the isinstance function
import math
value = float('nan')
if isinstance(value, float) and math.isnan(value):
print('Found a NaN value')