Check if a Value is Infinity or NaN in Python

One of the most important aspects of any programming language is the ability to handle numbers, including values that may be infinite or undefined. In Python, the concepts of infinity and NaN (Not a Number) are important to understand, as they are often encountered in mathematical calculations and data analysis.

Understanding Infinity in Python

Infinity is a mathematical concept that represents a number larger than any finite number. In Python, infinity is represented by float('inf') for positive infinity and float('-inf') for negative infinity.

Using math.isinf() to Check for Infinity

The math.isinf() function returns True if the given value is infinity and False otherwise ?

import math

# Check positive infinity
x = float('inf')
print(f"Is {x} infinity?", math.isinf(x))

# Check negative infinity
y = float('-inf')
print(f"Is {y} infinity?", math.isinf(y))

# Check regular number
z = 10.5
print(f"Is {z} infinity?", math.isinf(z))
Is inf infinity? True
Is -inf infinity? True
Is 10.5 infinity? False

Understanding NaN (Not a Number)

NaN represents an undefined or unrepresentable value, often resulting from operations like 0/0 or math.sqrt(-1). An important property of NaN is that it is not equal to any value, including itself.

Using math.isnan() to Check for NaN

The math.isnan() function returns True if the given value is NaN ?

import math

# Check NaN value
x = float('nan')
print(f"Is {x} NaN?", math.isnan(x))

# Check regular number
y = 42
print(f"Is {y} NaN?", math.isnan(y))

# Important: NaN is not equal to itself!
nan1 = float('nan')
nan2 = float('nan')
print(f"nan1 == nan2:", nan1 == nan2)
print(f"Both are NaN:", math.isnan(nan1) and math.isnan(nan2))
Is nan NaN? True
Is 42 NaN? False
nan1 == nan2: False
Both are NaN: True True

Checking with NumPy Arrays

NumPy provides vectorized versions of these functions that work on entire arrays ?

import numpy as np

# Array with mixed values
data = np.array([1, 2, np.inf, -np.inf, np.nan, 42])

print("Original array:", data)
print("Infinity check:", np.isinf(data))
print("NaN check:", np.isnan(data))
print("Finite check:", np.isfinite(data))
Original array: [ 1.  2. inf -inf nan 42.]
Infinity check: [False False  True  True False False]
NaN check: [False False False False  True False]
Finite check: [ True  True False False False  True]

Checking with Pandas DataFrames

Pandas provides methods to detect infinity and NaN values in DataFrames ?

import pandas as pd
import numpy as np

# Create DataFrame with special values
df = pd.DataFrame({
    'A': [1, 2, np.inf, 4],
    'B': [5, np.nan, 7, 8],
    'C': [9, 10, 11, -np.inf]
})

print("DataFrame:")
print(df)
print("\nInfinity check:")
print(df.isin([np.inf, -np.inf]))
print("\nNaN check:")
print(df.isna())
DataFrame:
     A    B     C
0  1.0  5.0   9.0
1  2.0  NaN  10.0
2  inf  7.0  11.0
3  4.0  8.0  -inf

Infinity check:
       A      B      C
0  False  False  False
1  False  False  False
2   True  False  False
3  False  False   True

NaN check:
       A      B      C
0  False  False  False
1  False   True  False
2  False  False  False
3  False  False  False

Handling Special Values

When working with data that might contain infinity or NaN values, use appropriate functions to handle them ?

import numpy as np

# Array with special values
data = np.array([1, 2, np.nan, 4, np.inf])

# Calculate mean ignoring NaN values
mean_value = np.nanmean(data[np.isfinite(data)])
print(f"Mean of finite values: {mean_value}")

# Count finite values
finite_count = np.sum(np.isfinite(data))
print(f"Count of finite values: {finite_count}")

# Replace infinity with a large number
cleaned_data = np.where(np.isinf(data), 999, data)
print(f"Data with inf replaced: {cleaned_data}")
Mean of finite values: 2.3333333333333335
Count of finite values: 3
Data with inf replaced: [  1.   2.  nan   4. 999.]

Comparison of Methods

Function Purpose Module Works on Arrays?
math.isinf() Check for infinity math No
math.isnan() Check for NaN math No
np.isinf() Check for infinity numpy Yes
np.isnan() Check for NaN numpy Yes
np.isfinite() Check for finite values numpy Yes

Conclusion

Understanding how to detect infinity and NaN values is crucial for robust numerical computing in Python. Use math.isinf() and math.isnan() for single values, or their NumPy counterparts for arrays. Remember that NaN values are never equal to themselves, so always use the appropriate checking functions.

Updated on: 2026-03-27T16:39:12+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements