给定此数据帧,如何仅选择那些"Col2"等于的行NaN
?
In [56]: df = pd.DataFrame([range(3), [0, np.NaN, 0], [0, 0, np.NaN], range(3), range(3)], columns=["Col1", "Col2", "Col3"])
In [57]: df
Out[57]:
0 1 2
0 0 1 2
1 0 NaN 0
2 0 0 NaN
3 0 1 2
4 0 1 2
Run Code Online (Sandbox Code Playgroud)
结果应该是这个:
Out[57]:
0 1 2
1 0 NaN 0
Run Code Online (Sandbox Code Playgroud)
qbz*_*ker 115
请尝试以下方法:
df[df['Col2'].isnull()]
Run Code Online (Sandbox Code Playgroud)
小智 12
如果您想选择至少具有一个 NaN 值的行,那么您可以使用isna
+ any
on axis=1
:
df[df.isna().any(axis=1)]
Run Code Online (Sandbox Code Playgroud)
如果要选择具有一定数量 NaN 值的行,则可以使用isna
+ sum
on axis=1
+ gt
。例如,以下命令将获取至少包含 2 个 NaN 值的行:
df[df.isna().sum(axis=1)>1]
Run Code Online (Sandbox Code Playgroud)
如果你想限制检查特定的列,你可以先选择它们,然后检查:
df[df[['Col1', 'Col2']].isna().any(axis=1)]
Run Code Online (Sandbox Code Playgroud)
如果要选择包含所有 NaN 值的行,可以使用isna
+ all
on axis=1
:
df[df.isna().all(axis=1)]
Run Code Online (Sandbox Code Playgroud)
如果您想选择没有 NaN 值的行,您可以notna
+ all
on axis=1
:
df[df.notna().all(axis=1)]
Run Code Online (Sandbox Code Playgroud)
这相当于:
df[df['Col1'].notna() & df['Col2'].notna() & df['Col3'].notna()]
Run Code Online (Sandbox Code Playgroud)
如果有很多列,这可能会变得乏味。相反,您可以使用functools.reduce
链接运算&
符:
import functools, operator
df[functools.reduce(operator.and_, (df[i].notna() for i in df.columns))]
Run Code Online (Sandbox Code Playgroud)
或者numpy.logical_and.reduce
:
import numpy as np
df[np.logical_and.reduce([df[i].notna() for i in df.columns])]
Run Code Online (Sandbox Code Playgroud)
如果您正在寻找使用 过滤某些列中没有 NaN 的行,您可以通过使用参数query
来实现:engine='python'
df.query('Col2.notna()', engine='python')
Run Code Online (Sandbox Code Playgroud)
NaN!=NaN
或者使用像@MaxU这样的事实- 停止针对 UA 的战争
df.query('Col2==Col2')
Run Code Online (Sandbox Code Playgroud)
@qbzenker提供了最惯用的IMO方法
以下是一些替代方案:
In [28]: df.query('Col2 != Col2') # Using the fact that: np.nan != np.nan
Out[28]:
Col1 Col2 Col3
1 0 NaN 0.0
In [29]: df[np.isnan(df.Col2)]
Out[29]:
Col1 Col2 Col3
1 0 NaN 0.0
Run Code Online (Sandbox Code Playgroud)