You pull your monthly sales report, run a quick average, and the result looks weird. You scroll through the data and see those annoying NaN values mixed in with real numbers. Your chart is broken, and your summary numbers no longer make sense.
NaN means “Not a Number” and usually appears when your data has missing or invalid values. In real projects, this happens all the time when you read CSV files, combine Excel sheets, hit APIs, or analyze sensor readings. Before you do any real analysis, you must remove or handle these NaN values cleanly.
In this article, I’ll show you 5 ways to remove NaN from an array in Python.
Our sample dataset for all methods
To keep things simple, we’ll use the same example throughout this article:
- Imagine you track monthly website visits for a year.
- Some months are missing because of tracking issues.
- Those missing months show up as NaN.
Here’s the base data we’ll work with in every method:
import math
import numpy as np
import pandas as pd
# Monthly website visits (in thousands)
# Some months are missing (NaN)
visits = [10.5, float('nan'), 12.3, 9.8, float('nan'), 15.0, 14.2, float('nan')]
print(visits)
# Sample output:
# [10.5, nan, 12.3, 9.8, nan, 15.0, 14.2, nan]
I executed the above example code and added the screenshot below.

We’ll convert or reuse this visits data in every approach.
Method 1 – Pure Python list comprehension (no extra libraries)
Use this method if you want a simple way to remove NaN from a regular Python list and you don’t want to rely on external libraries. This is great for quick scripts and small datasets.
Step 1: Create your list with NaN values
import math
import numpy as np
import pandas as pd
# Monthly website visits (in thousands) with NaN values
visits = [10.5, float('nan'), 12.3, 9.8, float('nan'), 15.0, 14.2, float('nan')]
print("Original visits:", visits)
# Sample output:
# Original visits: [10.5, nan, 12.3, 9.8, nan, 15.0, 14.2, nan]
Step 2: Filter out NaN using list comprehension
import math
import numpy as np
import pandas as pd
visits = [10.5, float('nan'), 12.3, 9.8, float('nan'), 15.0, 14.2, float('nan')]
clean_visits = [x for x in visits if not (isinstance(x, float) and math.isnan(x))]
print("Clean visits:", clean_visits)
# Sample output:
# Clean visits: [10.5, 12.3, 9.8, 15.0, 14.2]
I executed the above example code and added the screenshot below.

How does this code work?
- visits is a regular Python list that includes NaN created using float(‘nan’).
- The list comprehension loops through each x in visits.
- isinstance(x, float) checks if the value is a float. This prevents errors if you later have strings or integers in the list.
- math.isnan(x) returns True only for NaN floats.
- The not ( … ) condition keeps only values that are not NaN, so you end up with a clean clean_visits list.Pro Tip: Use this pure Python method when your data is still in a list and you have a small to medium dataset. It’s slower than NumPy for huge arrays but has zero extra dependencies.
Method 2 – Use NumPy and boolean indexing (fast for numeric arrays)
Use this method if you already work with NumPy arrays or large numeric data. NumPy is a popular Python library for numeric computing and works much faster than pure Python lists on big arrays.
Step 1: Convert the list to a NumPy array
import math
import numpy as np
import pandas as pd
visits = [10.5, float('nan'), 12.3, 9.8, float('nan'), 15.0, 14.2, float('nan')]
visits_array = np.array(visits)
print("Original NumPy array:", visits_array)
# Sample output:
# Original NumPy array: [10.5 nan 12.3 9.8 nan 15. 14.2 nan]
Step 2: Remove NaN using np.isnan and boolean indexing
import math
import numpy as np
import pandas as pd
visits = [10.5, float('nan'), 12.3, 9.8, float('nan'), 15.0, 14.2, float('nan')]
visits_array = np.array(visits)
clean_visits_array = visits_array[~np.isnan(visits_array)]
print("Clean NumPy array:", clean_visits_array)
# Sample output:
# Clean NumPy array: [10.5 12.3 9.8 15. 14.2]
I executed the above example code and added the screenshot below.

How does this code work?
- np.array(visits) converts the list to a NumPy array, which is optimized for numeric operations.
- np.isnan(visits_array) returns a boolean array where True marks positions with NaN.
- ~np.isnan(visits_array) flips the booleans, so True means “not NaN”.
- visits_array[condition] is called boolean indexing. It keeps only the elements where the condition is True, so NaN values are removed.Pro Tip: Use this approach for heavy data analysis, scientific code, or machine learning pipelines where performance matters. Boolean indexing in NumPy is very fast for large arrays.
Method 3 – Use NumPy isfinite to remove NaN and infinities
Sometimes your data has not only NaN but also infinite values like inf or -inf from bad calculations (for example, division by zero). This method removes NaN and infinite values in one shot.
Step 1: Build a NumPy array with NaN and inf
import math
import numpy as np
import pandas as pd
# Monthly website visits with NaN and inf values
visits = [10.5, float('nan'), 12.3, np.inf, 9.8, float('nan'), 15.0, -np.inf, 14.2]
visits_array = np.array(visits)
print("Original array with NaN and inf:", visits_array)
# Sample output:
# Original array with NaN and inf: [10.5 nan 12.3 inf 9.8 nan 15. -inf 14.2]
Step 2: Filter using np.isfinite
import math
import numpy as np
import pandas as pd
visits = [10.5, float('nan'), 12.3, np.inf, 9.8, float('nan'), 15.0, -np.inf, 14.2]
visits_array = np.array(visits)
clean_visits_array = visits_array[np.isfinite(visits_array)]
print("Clean array (finite values only):", clean_visits_array)
# Sample output:
# Clean array (finite values only): [10.5 12.3 9.8 15. 14.2]
How does this code work?
- np.isfinite(visits_array) returns True for values that are real numbers (not NaN, not inf, not -inf).
- You again use boolean indexing with visits_array[mask] to keep only finite values.
- The result is an array where problematic special values are removed, ready for statistics or plotting.Pro Tip: Use np.isfinite when your numeric data may contain NaN and infinity from calculations. This keeps only “safe” numbers for downstream data analysis.
Method 4 – Use pandas Series and dropna (great for real-world data)
Use this method if your data comes from CSV files, Excel, or databases and you already use pandas. Pandas is a powerful data analysis library that works on Series (1D) and DataFrames (2D tables).
Step 1: Create a pandas Series from your visits data
pythonimport math
import numpy as np
import pandas as pd
visits = [10.5, float('nan'), 12.3, 9.8, float('nan'), 15.0, 14.2, float('nan')]
visits_series = pd.Series(visits, name="monthly_visits")
print("Original pandas Series:")
print(visits_series)
# Sample output:
# Original pandas Series:
# 0 10.5
# 1 NaN
# 2 12.3
# 3 9.8
# 4 NaN
# 5 15.0
# 6 14.2
# 7 NaN
# Name: monthly_visits, dtype: float64
Step 2: Use dropna to remove NaN from the Series
pythonimport math
import numpy as np
import pandas as pd
visits = [10.5, float('nan'), 12.3, 9.8, float('nan'), 15.0, 14.2, float('nan')]
visits_series = pd.Series(visits, name="monthly_visits")
clean_visits_series = visits_series.dropna()
print("Series after dropna():")
print(clean_visits_series)
# Sample output:
# Series after dropna():
# 0 10.5
# 2 12.3
# 3 9.8
# 5 15.0
# 6 14.2
# Name: monthly_visits, dtype: float64
How does this code work?
- pd.Series(visits) wraps your list into a pandas Series, which behaves like a labeled column.
- dropna() is a pandas method that removes any entries that are NaN (or None by default).
- Notice that the index values (0, 2, 3, 5, 6) are preserved. You can reset them later if you want a clean index.Pro Tip: Use pandas.Series.dropna when you join data from multiple sources and quickly want to remove missing rows. You can later chain it with .reset_index(drop=True) if you want continuous index values. [LINK: How to Use dropna in pandas (With Examples)]
Method 5 – Remove NaN from a 2D NumPy array (drop rows with NaN)
In many real projects, your data is tabular: each row is a month, and each column is a metric (visits, signups, revenue, etc.). This method shows how to remove entire rows that contain NaN values from a 2D NumPy array.
Step 1: Create a 2D NumPy array with NaN rows
We’ll pretend each row is a month with two metrics: visits and ad_clicks.
import math
import numpy as np
import pandas as pd
# Rows: months, Columns: [visits, ad_clicks]
data = [
[10.5, 120],
[float('nan'), 100],
[12.3, float('nan')],
[9.8, 90],
[float('nan'), float('nan')],
[15.0, 150],
[14.2, 140],
]
visits_matrix = np.array(data, dtype=float)
print("Original 2D array:")
print(visits_matrix)
# Sample output:
# Original 2D array:
# [[10.5 120. ]
# [ nan 100. ]
# [12.3 nan]
# [ 9.8 90. ]
# [ nan nan]
# [15. 150. ]
# [14.2 140. ]]
Step 2: Remove rows that contain any NaN
import math
import numpy as np
import pandas as pd
data = [
[10.5, 120],
[float('nan'), 100],
[12.3, float('nan')],
[9.8, 90],
[float('nan'), float('nan')],
[15.0, 150],
[14.2, 140],
]
visits_matrix = np.array(data, dtype=float)
rows_without_nan = visits_matrix[~np.isnan(visits_matrix).any(axis=1)]
print("2D array after removing rows with NaN:")
print(rows_without_nan)
# Sample output:
# 2D array after removing rows with NaN:
# [[ 10.5 120. ]
# [ 9.8 90. ]
# [ 15. 150. ]
# [ 14.2 140. ]]
How does this code work?
- np.isnan(visits_matrix) creates a boolean array with True wherever there is a NaN in the matrix.
- .any(axis=1) checks each row and returns True if that row contains at least one NaN.
- ~np.isnan(…).any(axis=1) flips the result, so True now means “row has no NaN values”.
- You use this boolean mask to select only complete rows from visits_matrix.Pro Tip: This pattern is very useful when preparing data for machine learning, as many models require rows to be free of NaN values. For very large arrays, consider using pandas.DataFrame.dropna if you need more flexible rules.
Things to Keep in Mind
- Check your data type: np.isnan works on numeric NumPy arrays, but it throws errors on arrays with strings or mixed types. Use isinstance checks or pandas for mixed data.
- NaN is not equal to itself: Expressions like x == float(‘nan’) always return False. Use math.isnan, np.isnan, or pd.isna to test for NaN values.
- Empty lists and arrays: Removing NaN from an empty list or array returns another empty object. Always check length before doing operations like the average of a list or sum to avoid confusing results.
- Preserving vs. resetting index: pandas.Series.dropna() keeps the original index. If you need a clean index, call reset_index(drop=True) afterward.
- Float precision issues: NaN is different from rounding errors. Removing NaN will not fix tiny float differences like 0.30000000000004. Use rounding if you need cleaner numbers.
- Library versions: Stick to modern Python 3 and recent versions of NumPy and pandas. Function names like np.isnan, np.isfinite, and Series.dropna are stable, but behavior in edge cases might differ across very old versions.
You saw five practical ways to remove NaN from an array in Python using pure lists, NumPy, and pandas, from simple 1D lists to 2D data. For quick scripts or small lists, use the pure Python list comprehension; for large numeric arrays, prefer NumPy methods, and for real-world tabular data, pandas.dropna is usually the best choice. I hope you found this article helpful.
You may also read:
- Save an Array to a File in Python
- Use Python Array Index -1
- Find the Number of Elements in a Python Array
- Sort an Array in Python

Bijay Kumar is an experienced Python and AI professional who enjoys helping developers learn modern technologies through practical tutorials and examples. His expertise includes Python development, Machine Learning, Artificial Intelligence, automation, and data analysis using libraries like Pandas, NumPy, TensorFlow, Matplotlib, SciPy, and Scikit-Learn. At PythonGuides.com, he shares in-depth guides designed for both beginners and experienced developers. More about us.