How to remove NaN values in Python
In this article, we will learn how to remove NaN values from a Python NumPy array.
NaN values are those values that do not have a specific value associated with it.
To remove Nan values from NumPy arrays, we are using numpy.isnan()
and numpy.logical_not()
functions.
numpy.isnan()
– give true for all the indexes where the value is Nan.numpy.logical_not()
– perform the logical not operation
import numpy as np temp = np.array([1, 6, 3, np.nan, 2, np.nan, 9, 7, np.nan]) # remove nan values new = temp[np.logical_not(np.isnan(temp))] print('Original array: ', temp) print('After removing Nan values: ', new) # this same method can be applied # on n-dimensional arrays print() # 2-D array td = np.array([[1, 2, np.nan], [np.nan, 8, np.nan], [5, np.nan, 3]]) tdn = td[np.logical_not(np.isnan(td))] print("Original 2D array: ", td) print("After removing Nan values: ", tdn)
Output:
Original array: [ 1. 6. 3. nan 2. nan 9. 7. nan] After removing Nan values: [1. 6. 3. 2. 9. 7.] Original 2D array: [[ 1. 2. nan] [nan 8. nan] [ 5. nan 3.]] After removing Nan values: [1. 2. 8. 5. 3.]
Subscribe
Login
Please login to comment
0 Discussion