How to drop nan in NumPy array

You can drop nan in the NumPy array with the following code. If you want to learn Python, I highly recommend reading This Book.

How to drop nan in NumPy array
How to drop nan in NumPy array

Method 1

import numpy as np

# Original Numpy Array
a = np.array([1, 2, np.nan, 4, np.nan])

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

# Display New Array
print(a)

Output

[1. 2. 4.]

Method 2

import numpy as np

# Original Numpy Array
a = np.array([1, 2, np.nan, 4, np.nan])

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

# Display New Array
print(a)

Output

[1. 2. 4.]

Method 3

import pandas as pd
import numpy as np

# Original Numpy Array
a = np.array([1, 2, np.nan, 4, np.nan])

# Drop nan
a = a[~pd.isnull(a)]

# Display New Array
print(a)

Output

[1. 2. 4.]

People are also reading:

Best Python Books

What is Computer Vision? Examples, Applications, Techniques

Books for Machine Learning (ML)

Free Learning Resources

Leave a Comment

Your email address will not be published.