微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python – 在Pandas中删除超过60%“空”值的列

我有一个这样的数据帧:

import pandas as pd
data = {
    'c1': ['Test1','Test2','NULL','Test3',' ','Test4','Test4','Test1',"Test3"],
    'c2': [' ','Test1',' ','NULL',' ','NULL','NULL','NULL','NULL'],
    'c3': [0,0,0,0,0,1,5,0,0],
    'c4': ['NULL', 'Test2', 'Test1','Test1', 'Test2', 'Test2','Test1','Test1','Test2']
}
df = pd.DataFrame(data)
df

数据框如下所示:

    c1      c2      c3      c4
0   Test1           0       NULL
1   Test2   Test1   0       Test2
2   NULL            0       Test1
3   Test3   NULL    0       Test1
4                   0       Test2
5   Test4   NULL    1       Test2
6   Test4   NULL    5       Test1
7   Test1   NULL    0       Test1
8   Test3   NULL    0       Test2

我想删除所有超过60%“空”值的列. “空”意味着在我的情况下,值是例如:”,’NULL’或0.有字符串(c1,c2,c4)以及整数(c3).

结果应该是仅包含列c1和c4的数据框.

    c1      c4
0   Test1   NULL
1   Test2   Test2
2   NULL    Test1
3   Test3   Test1
4           Test2
5   Test4   Test2
6   Test4   Test1
7   Test1   Test1
8   Test3   Test2

我不知道如何处理这个问题.只有我想到的东西才是这样的

df.loc[:, (df != 0).any(axis=0)]

删除所有值为0,’NULL’等所有列.

解决方法:

使用DataFrame.isin检查所有格式,然后得到阈值的平均值,并使用loc来过滤boolean indexing

print (df.isin([' ','NULL',0]))
      c1     c2     c3     c4
0  False   True   True   True
1  False  False   True  False
2   True   True   True  False
3  False   True   True  False
4   True   True   True  False
5  False   True  False  False
6  False   True  False  False
7  False   True   True  False
8  False   True   True  False

print (df.isin([' ','NULL',0]).mean())
c1    0.222222
c2    0.888889
c3    0.777778
c4    0.111111
dtype: float64

df = df.loc[:, df.isin([' ','NULL',0]).mean() < .6]
print (df)
      c1     c4
0  Test1   NULL
1  Test2  Test2
2   NULL  Test1
3  Test3  Test1
4         Test2
5  Test4  Test2
6  Test4  Test1
7  Test1  Test1
8  Test3  Test2

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐