Python 如何在特定列中选择带有 NaN 的行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43831539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:25:37  来源:igfitidea点击:

How to select rows with NaN in particular column?

pythonpandas

提问by Dinosaurius

Given this dataframe, how to select only those rows that have "Col2" equal to NaN?

给定这个数据框,如何只选择那些“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

The result should be this one:

结果应该是这样的:

Out[57]: 
   0   1   2
1  0 NaN   0

回答by qbzenker

Try the following:

请尝试以下操作:

df[df['Col2'].isnull()]

回答by MaxU

@qbzenker provided the most idiomatic method IMO

@qbzenker 提供了最惯用的方法 IMO

Here are a few alternatives:

这里有一些替代方案:

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