Remove NaN or Infinite Values from a NumPy Array

This tutorial will discuss about unique ways to remove nan or infinite values from a numpy array.

Suppose we have an NumPy array which contains certain NaN values or infinite values i.e.

arr = np.array([5, 7, np.nan, 8, np.inf, 16, -np.inf])

Now we want to remove all the NaN and infinite values from this array.

For this, we will pass the number array into the isfinite() function of the numpy module. It will return as a boolean array. Each True value in this boolean array denotes that the corresponding value in the original array is neither NaN or nor infinite. Then we can pass this boolean array into the subscript operator of the number array, it will return as a copy of array after deleting all the NaN and infinite values from the array.

Let’s see the complete example,

import numpy as np

# Create a NumPy Array
arr = np.array([5, 7, np.nan, 8, np.inf, 16, -np.inf])

print(arr)

# Create a boolean mask for the finite values
mask = np.isfinite(arr)

# Use the mask to update numpy array with the
# NaN and infinite values removed
arr = arr[mask]

# Print the numpy array
print(arr)

Output

[  5.   7.  nan   8.  inf  16. -inf]
[ 5.  7.  8. 16.]

Summary

We learned how to delete NaN and infinite values from a NumPy Array in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top