Abh*_*har 2 python machine-learning pandas
是否有一种有效的方法来删除至少有20%缺失值的列?
假设我的数据框如下:
A B C D
0 sg hh 1 7
1 gf 9
2 hh 10
3 dd 8
4 6
5 y 8`
Run Code Online (Sandbox Code Playgroud)
删除列后,数据框如下所示:
A D
0 sg 7
1 gf 9
2 hh 10
3 dd 8
4 6
5 y 8`
Run Code Online (Sandbox Code Playgroud)
Ste*_*fan 10
您可以使用boolean indexing在columns那里的计notnull数值越大则80%:
df.loc[:, pd.notnull(df).sum()>len(df)*.8]
Run Code Online (Sandbox Code Playgroud)
这在许多情况下都很有用,例如,删除值大于的列数1:
df.loc[:, (df > 1).sum() > len(df) *. 8]
Run Code Online (Sandbox Code Playgroud)
另外,对于.dropna()情况下,你还可以指定thresh的关键字.dropna()通过@EdChum所示:
df.dropna(thresh=0.8*len(df), axis=1)
Run Code Online (Sandbox Code Playgroud)
后者会稍快一些:
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
Run Code Online (Sandbox Code Playgroud)