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

时间:2022-10-06 07:41:40

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

2 个解决方案

#1


37  

Try the following:

请尝试以下方法:

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

#2


4  

@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

#1


37  

Try the following:

请尝试以下方法:

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

#2


4  

@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