Python Practice › NumPy Programs › Program 76
Drop rows with NaN
Write a NumPy program to remove rows that contain NaN.
Input
[[4, nan, 8], [2, 4, 6]]
Output
[[2. 4. 6.]]
Approach
- Keep rows where no element is NaN.
Solution
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.