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


103

给定此数据框,如何仅选择“ 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

结果应该是这样的:

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

Answers:


177

请尝试以下操作:

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

9
或者,df.loc[df['Col2'].isnull()]如果.loc是您喜欢的东西
亚历山大

2
问:如何取反,即“列中的数据不为空”?答:通过使用.notnull()运算符。
sk

10

@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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.