How do I remove NaN values from a NumPy array?

nan, numpy, python

Solution

To remove NaN values from a NumPy array `x`:

x = x[~numpy.isnan(x)]

Explanation

The inner function `numpy.isnan` returns a boolean/logical array which has the value `True` everywhere that `x` is not-a-number. Since we want the opposite, we use the logical-not operator `~` to get an array with `True`s everywhere that `x` is a valid number.

Lastly, we use this logical array to index into the original array `x`, in order to retrieve just the non-NaN values.

Problem

How do I remove NaN values from a NumPy array? ``` [1, 2, NaN, 4, NaN, 8] ⟶ [1, 2, 4, 8] ```

Original source

Related problems