Python 如何删除缺少至少20%值的列

Python 如何删除缺少至少20%值的列,python,pandas,machine-learning,Python,Pandas,Machine Learning,是否有一种有效的方法来删除缺失值至少为20%的列 假设我的数据帧如下所示: A B C D 0 sg hh 1 7 1 gf 9 2 hh 10 3 dd 8 4 6 5 y 8` 删除列后,dataframe如下所示: A

是否有一种有效的方法来删除缺失值至少为20%的列

假设我的数据帧如下所示:

   A      B      C      D
0  sg     hh     1      7
1  gf                   9
2  hh                   10
3  dd                   8
4                       6 
5  y                    8`
删除列后,dataframe如下所示:

   A       D
0  sg      7
1  gf      9
2  hh      10
3  dd      8
4          6 
5  y       8`

您可以在
上使用
布尔索引
,其中
notnull
值的计数大于
80%

df.loc[:, pd.notnull(df).sum()>len(df)*.8]
这在许多情况下都很有用,例如,删除值数量大于
1
的列:

df.loc[:, (df > 1).sum() > len(df) *. 8]
或者,对于
.dropna()
案例,您还可以指定
.dropna()
thresh
关键字,如@EdChum所示:

df.dropna(thresh=0.8*len(df), axis=1)
后者将略快一些:

df = pd.DataFrame(np.random.random((100, 5)), columns=list('ABCDE'))
for col in df:
    df.loc[np.random.choice(list(range(100)), np.random.randint(10, 30)), col] = np.nan

%timeit df.loc[:, pd.notnull(df).sum()>len(df)*.8]
1000 loops, best of 3: 716 µs per loop

%timeit df.dropna(thresh=0.8*len(df), axis=1)
1000 loops, best of 3: 537 µs per loop
您可以调用并传递
thresh
值,以删除不符合阈值条件的列:

In [10]:    
frac = len(df) * 0.8
df.dropna(thresh=frac, axis=1)

Out[10]:
     A   D
0   sg   7
1   gf   9
2   hh  10
3   dd   8
4  NaN   6
5    y   8

可以使用df.isnull(),它将返回相同大小的布尔df/序列。求结果每列的行数之和,然后除以总行数?然后适当地删除列。在上述两种方法中,哪一种效率更高?
。dropna()
会更快一些。