HOWTO · NumPy

How to Remove Nan Values From a NumPy Array

Learn how to remove nan values from a NumPy array in Python

On this page

To remove NaN elements from a NumPy array, build a mask that is true for values that are not NaN, then use that mask to select the elements. For a NumPy array, array[~np.isnan(array)] is the concise form.

Remove NaN Values Using logical_not() and isnan() Functions in NumPy

np.isnan(array) returns a boolean array with True where an element is NaN. np.logical_not() reverses those values, so the resulting mask is True for ordinary numbers. Boolean indexing keeps the matching elements in their original order. The ~ operator is the shorter equivalent for this NumPy boolean array.

This example applies both forms and also shows what happens when the input contains only NaNs or no NaNs:

import numpy as np

values = np.array([1.0, np.nan, 3.0])
without_nan = values[np.logical_not(np.isnan(values))]
without_nan_short = values[~np.isnan(values)]
all_nan = np.array([np.nan, np.nan])
no_nan = np.array([1, 2, 3])
print(without_nan)
print(without_nan_short)
print(all_nan[~np.isnan(all_nan)])
print(no_nan[~np.isnan(no_nan)])
[1. 3.]
[1. 3.]
[]
[1 2 3]

The two masks produce the same filtered values. An all-NaN input produces an array with no elements, while an input without NaNs is returned unchanged. See the official documentation for np.logical_not() and np.isnan().

Remove NaN Values Using the isfinite() Function in NumPy

np.isfinite(array) creates a mask that is true for finite numbers. Indexing with it removes NaNs, but it also removes positive and negative infinity. Use this function when you want only finite values; for a NaN-only filter that should retain infinities, use the inverted np.isnan() mask above. Read the official np.isfinite() documentation for its behavior with numeric types.

Remove NaN Values Using math.isnan()

Python’s standard-library math.isnan() checks one scalar value at a time. First import it with import math. For a one-dimensional numeric array, a list comprehension can build a boolean mask: keep = [not math.isnan(value) for value in values], followed by filtered = values[keep]. This approach iterates over each array element in Python, whereas the NumPy functions operate on the array. It is intended for a one-dimensional input; iterating a multidimensional array yields subarrays rather than scalar numbers.

Remove NaN Values Using pandas.isnull()

If pandas is already part of your project, import it with import pandas as pd; pd.isnull() identifies missing values and can supply the inverted mask: filtered = values[~pd.isnull(values)]. This is a pandas function, not a NumPy method, and avoids adding a pandas installation solely for this task. Its missing-value detection also covers pandas’ other missing markers when those values occur in supported data structures. See the existing pandas isnull() reference.