如果你想选择至少有一个 NaN 值的行,那么你可以在axis=1 上使用isna + any:
df[df.isna().any(axis=1)]
如果要选择具有一定数量 NaN 值的行,则可以在 axis=1 + gt 上使用 isna + sum。例如,以下将获取至少具有 2 个 NaN 值的行:
df[df.isna().sum(axis=1)>1]
如果您想将检查限制在特定列,您可以先选择它们,然后检查:
df[df[['Col1', 'Col2']].isna().any(axis=1)]
如果要选择所有 NaN 值的行,可以在 axis=1 上使用 isna + all:
df[df.isna().all(axis=1)]
如果你想选择没有 NaN 值的行,你可以 notna + all on axis=1:
df[df.notna().all(axis=1)]
这相当于:
df[df['Col1'].notna() & df['Col2'].notna() & df['Col3'].notna()]
如果有很多列,这可能会变得乏味。相反,您可以使用 functools.reduce 链接 & 运算符:
import functools, operator
df[functools.reduce(operator.and_, (df[i].notna() for i in df.columns))]
或numpy.logical_and.reduce:
import numpy as np
df[np.logical_and.reduce([df[i].notna() for i in df.columns])]
如果您正在寻找使用query 过滤某些列中没有NaN 的行,您可以使用engine='python' 参数来实现:
df.query('Col2.notna()', engine='python')
或使用NaN!=NaN 喜欢@MaxU - stop WAR against UA 的事实
df.query('Col2==Col2')