Michael
Michael

Reputation: 13914

Removing a Row with Missing Values in Numpy Array

I have a numpy array (type numpy.ndarray) where a few rows have missing values (all missing values to be precise). How do I remove a row from the array if it contains missing values?

Upvotes: 0

Views: 2509

Answers (1)

Roger Fan
Roger Fan

Reputation: 5045

Use np.isfinite in combination with np.any or np.all with the axis argument.

a = np.round(np.random.normal(size=(5, 3)), 1)
a[1, 2] = np.nan
a[2] = np.nan

print(a)
print(a[np.all(np.isfinite(a), axis=1)])  # Removes rows with any non-finite values.
print(a[np.any(np.isfinite(a), axis=1)])  # Removes rows that are all non-finite.

Upvotes: 3

Related Questions