You can use the following methods to remove NaN values from a NumPy array:
Method 1: Use isnan()
new_data = data[~np.isnan(data)]
Method 2: Use isfinite()
new_data = data[np.isfinite(data)]
Method 3: Use logical_not()
new_data = data[np.logical_not(np.isnan(data))]
Each of these methods produce the same result, but the first method is the shortest to type out so it tends to be used most often.
The following examples show how to use each method in practice.
Example 1: Remove NaN Values Using isnan()
The following code shows how to remove NaN values from a NumPy array by using the isnan() function:
import numpy as np
#create array of data
data = np.array([4, np.nan, 6, np.nan, 10, 11, 14, 19, 22])
#define new array of data with nan values removed
new_data = data[~np.isnan(data)]
#view new array
print(new_data)
[ 4. 6. 10. 11. 14. 19. 22.]
Notice that the two NaN values have been successfully removed from the NumPy array.
This method simply keeps all of the elements in the array that are not (~) NaN values.
Example 2: Remove NaN Values Using isfinite()
The following code shows how to remove NaN values from a NumPy array by using the isfinite() function:
import numpy as np
#create array of data
data = np.array([4, np.nan, 6, np.nan, 10, 11, 14, 19, 22])
#define new array of data with nan values removed
new_data = data[np.isfinite(data)]
#view new array
print(new_data)
[ 4. 6. 10. 11. 14. 19. 22.]
Notice that the two NaN values have been successfully removed from the NumPy array.
This method simply keeps all of the elements in the array that are finite values.
Since NaN values are not finite, they’re removed from the array.
Example 3: Remove NaN Values Using logical_not()
The following code shows how to remove NaN values from a NumPy array by using the logical_not() function:
import numpy as np
#create array of data
data = np.array([4, np.nan, 6, np.nan, 10, 11, 14, 19, 22])
#define new array of data with nan values removed
new_data = data[np.logical_not(np.isnan(data))]
#view new array
print(new_data)
[ 4. 6. 10. 11. 14. 19. 22.]
Notice that the two NaN values have been successfully removed from the NumPy array.
While this method is equivalent to the previous two, it requires more typing so it’s not used as often.
Additional Resources
The following tutorials explain how to perform other common operations in Python:
Pandas: How to Replace Empty Strings with NaN
Pandas: How to Replace NaN Values with String