Python 筛选出特定列中的nan行

Python 筛选出特定列中的nan行,python,pandas,numpy,Python,Pandas,Numpy,给定数据帧df,我想获得一个新的数据帧df2,它在Col2列中不包含nan。这是预期的结果: df2= df = Col1 Col2 Col3 1 nan 4 2 5 4 3 3 nan 我知道可以使用pandas.isnull和dropna,但是如何只指定要应用筛选的特定列?使用: 另一个解决方案-具有: 什么是相同的: df = df[df['Col2'].notnull()] print (df) Col1 Col2 Col3 1 2

给定数据帧
df
,我想获得一个新的数据帧
df2
,它在
Col2
列中不包含
nan
。这是预期的结果: df2=

df =

Col1 Col2 Col3
1    nan  4
2    5    4
3    3    nan
我知道可以使用
pandas.isnull
dropna
,但是如何只指定要应用筛选的特定列?

使用:

另一个解决方案-具有:

什么是相同的:

df = df[df['Col2'].notnull()]
print (df)
   Col1  Col2  Col3
1     2   5.0   4.0
2     3   3.0   NaN
您可以使用以下方法:

或者(在本例中)不太惯用:

或使用方法:

numexpr
解决方案:

In [205]: df.query("Col2 == Col2")
Out[205]:
   Col1  Col2  Col3
1     2   5.0   4.0
2     3   3.0   NaN

使用
numpy
isnan
屏蔽并构造新的数据帧

In [241]: import numexpr as ne

In [242]: col = df.Col2

In [243]: df[ne.evaluate("col == col")]
Out[243]:
   Col1  Col2  Col3
1     2   5.0   4.0
2     3   3.0   NaN

定时
大数据


如果要在删除列之前计算并绘制nan的数量


下面的简单实现是从上面开始的,但显示了过滤掉特定列中的nan行-就地,对于大的数据帧,按列名对nan行进行计数(前后)

数据帧

In [241]: import numexpr as ne

In [242]: col = df.Col2

In [243]: df[ne.evaluate("col == col")]
Out[243]:
   Col1  Col2  Col3
1     2   5.0   4.0
2     3   3.0   NaN
import pandas as pd
import numpy as np

df = pd.DataFrame([[1,np.nan,'A100'],[4,5,'A213'],[7,8,np.nan],[10,np.nan,'GA23']])
df.columns = ['areaCode','Distance','accountCode']
之前:使用nan计算行数(每列):

按列计数:

df.isnull().sum()
df.isnull().sum()
在适当位置删除不需要的行:

areaCode       0
Distance       2
accountCode    1
dtype: int64
之后:使用nan计算行数(每列):

按列计数:

df.isnull().sum()
df.isnull().sum()
数据帧:

areaCode       0
Distance       0
accountCode    1
dtype: int64

请为该解决方案添加时间:
import numexpr as ne;col=df.Col2.values;%timeit df[ne.evaluate(“col==col”)]
?这是一个很好的答案。整洁的
import pandas as pd
import numpy as np

df = pd.DataFrame([[1,np.nan,'A100'],[4,5,'A213'],[7,8,np.nan],[10,np.nan,'GA23']])
df.columns = ['areaCode','Distance','accountCode']
areaCode    Distance    accountCode
1           NaN         A100
4           5.0         A213
7           8.0         NaN
10          NaN         GA23
df.isnull().sum()
areaCode       0
Distance       2
accountCode    1
dtype: int64
df.dropna(subset=['Distance'],inplace=True)
df.isnull().sum()
areaCode       0
Distance       0
accountCode    1
dtype: int64
areaCode    Distance    accountCode
4           5.0         A213
7           8.0         NaN