Python Practice › NumPy Programs › Program 76

Drop rows with NaN

EasyNumPy Programs · 76 of 100

Write a NumPy program to remove rows that contain NaN.

Advertisement
Input
[[4, nan, 8], [2, 4, 6]]
Output
[[2. 4. 6.]]

Approach

  1. Keep rows where no element is NaN.

Solution

Python
import numpy as npa = np.array([[4, np.nan, 8], [2, 4, 6]])print(a[~np.isnan(a).any(axis=1)])
Output
[[2. 4. 6.]]

Line by line

Line 3

isnan(a).any(axis=1) is True for rows with a NaN; ~ inverts it.

Learn the concept

New to this topic? Read the lesson, then come back.

More numpy programs

← All 100 NumPy Programs

Leave a Comment