Check if a Variable Is NaN in Python

I’ve frequently encountered the challenge of detecting NaN (Not a Number) values in datasets. NaN values often appear in data science, machine learning, and data processing tasks, especially when working with real-world data that can be messy or incomplete.

Identifying NaN values correctly in Python is crucial because they can silently break your calculations or lead to incorrect results.

In this guide, I’ll share practical methods to check if a variable is NaN in Python, complete with full code examples. Whether you work with plain Python, NumPy, or Pandas, this tutorial covers what you need to know.

What Is NaN in Python and Why It Matters?

NaN stands for “Not a Number.” It represents undefined or missing numerical data in floating-point calculations. In Python, NaN is a special floating-point value defined by the IEEE 754 standard.

For example, dividing zero by zero or taking the square root of a negative number in floating-point math can produce NaN. Also, in datasets, missing values are often encoded as NaN.

It’s important to detect NaN because:

  • NaN values propagate silently through calculations.
  • They can cause errors or misleading statistics.
  • Handling NaN properly improves data quality and model accuracy.

Method 1: Use math.isnan() in Python

The built-in math module provides the isnan() function to check if a variable is NaN. This method works only with float values.

import math

value = float('nan')

if math.isnan(value):
    print("The variable is NaN")
else:
    print("The variable is not NaN")

You can refer to the screenshot below to see the output.

nan python

This method is simple and effective for basic Python scripts, but it does not support checking NaN in arrays or non-float types.

Method 2: Use numpy.isnan() for Arrays and Scalars

When working with numerical data, especially arrays, NumPy’s isnan() function is a powerful tool. It works on both single values and entire arrays.

import numpy as np

# Check a single value
value = np.nan
print(np.isnan(value))  # Output: True

# Check an array
arr = np.array([1, 2, np.nan, 4])
nan_mask = np.isnan(arr)
print(nan_mask) 

You can refer to the screenshot below to see the output.

nan in python

Using numpy.isnan() is my go-to method when processing large datasets or working with scientific computing in Python.

Method 3: Using Pandas isna() or isnull() for DataFrames

Pandas is widely used in data analysis and machine learning projects. It provides isna() and isnull() functions to detect NaN values in Series or DataFrames.

import pandas as pd
import numpy as np

data = {'A': [1, 2, np.nan], 'B': [4, np.nan, 6]}
df = pd.DataFrame(data)

print(df.isna())

You can refer to the screenshot below to see the output.

python nan

These functions return boolean masks that help filter or clean your data efficiently.

Method 4: Check NaN with Comparison Tricks (Not Recommended)

Some developers try to detect NaN by comparing a variable to itself because NaN is not equal to itself. While this works, it’s less readable and not recommended.

value = float('nan')

if value != value:
    print("Variable is NaN")
else:
    print("Variable is not NaN")

This method works because NaN is the only value in Python where x != x evaluates to True. However, I prefer using explicit functions like math.isnan() or numpy.isnan() for clarity.

Practical Example: Clean a Dataset with NaN Values in Python

Imagine you have a dataset with missing values marked as NaN and want to filter them out before training a machine learning model.

import pandas as pd
import numpy as np

data = {
    'Age': [25, np.nan, 30, 22, np.nan],
    'Salary': [50000, 60000, np.nan, 52000, 58000]
}

df = pd.DataFrame(data)
print("Original Data:")
print(df)

# Drop rows with any NaN values
clean_df = df.dropna()
print("\nData after dropping NaN values:")
print(clean_df)

# Alternatively, fill NaN with a default value
filled_df = df.fillna({'Age': df['Age'].mean(), 'Salary': df['Salary'].mean()})
print("\nData after filling NaN values:")
print(filled_df)

This example shows how detecting and handling NaN helps prepare your data for reliable analysis or modeling.

Tips for Handling NaN in Python Projects

  • Always check for NaN before performing calculations to avoid silent errors.
  • Use NumPy or Pandas functions for efficient NaN detection in arrays and DataFrames.
  • Avoid manual comparison tricks; prefer built-in functions for readability.
  • When working with machine learning libraries like scikit-learn or Keras, clean NaN values beforehand to prevent training errors.

Detecting NaN values in Python is a fundamental skill for any developer working with data. Using the right tools makes your code more reliable and your data pipelines more robust.

Mastering NaN detection in Python improves your data processing workflows and prevents common pitfalls. Keep practicing these methods to write cleaner, more reliable Python code!

You may also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.