How to remove nan values from NumPy array

You can remove nan values from the NumPy array with the following methods. If you want to learn Python, I highly recommend reading This Book.

Method 1

# Import the NumPy library as np
import numpy as np

# Initialize the NumPy array
a = np.array([7, np.nan, 8, 0, 5])

# Remove nan values
a = a[np.logical_not(np.isnan(a))]

# Print Array
print(a)

Output:

[7. 8. 0. 5.]

Method 2

# Import the NumPy library as np
import numpy as np

# Initialize the NumPy array
a = np.array([7, np.nan, 8, 0, 5])

# Remove nan values
a = a[~np.isnan(a)]

# Print Array
print(a)

Output:

[7. 8. 0. 5.]

Example: Remove nan values from the Higher Dimensional Array

When you remove the nan values from the higher dimensional array then it will convert into 1D array because shape will be disturbed after removing nan.

# Import the NumPy library as np
import numpy as np

# Initialize the NumPy array
a = np.array([[7, np.nan, 8, 0, 5],
              [0, 5, 2, np.nan, 0],
              [7, 0, 1, 8, np.nan],
              [6, 8, 9, 2, np.nan]])

# Remove nan values
a = a[np.logical_not(np.isnan(a))]

# Print Array
print(a)

Output:

[7. 8. 0. 5. 0. 5. 2. 0. 7. 0. 1. 8. 6. 8. 9. 2.]

Free Learning Resources

Leave a Comment

Your email address will not be published.