Skip to main content
 首页 » 编程设计

Python/Pandas之从数据框中删除所有列,其中 > 50% 的行的值为 0

2024年10月01日6jyk

我正在使用 Python 和 Pandas。我想从我的数据框中删除每一列,其中超过 50% 的行在该特定列中的值为 0。

举个例子:

import pandas as pd 
 
# defining a dataframe 
data = [['Alex',10, 173, 0, 4000],['Bob',12, 0, 0, 4000], ['Clarke',13, 0, 0, 0]] 
# naming the columns 
df = pd.DataFrame(data,columns=['Name','Age', 'Height', 'Score', 'Income']) 
 
# printing the dataframe 
print(df) 

我设法制作了一个表格,显示有多少行每列的值为 0 以及百分比。但我觉得我走错了路。有人可以帮忙吗?

# make a new dataframe and count the number of values = zero per column 
zeroValues = df.eq(0).sum(axis=0) 
zeroValues = zeroValues.to_frame() 
 
# name the column 
zeroValues.columns = ["# of zero values"] 
 
# add a column that calculates the  percentage of values = zero 
zeroValues["zeroValues %"] = ((zeroValues["# of zero values"] * 100) /  
len(df.index)) 
 
# print the result 
print(zeroValues) 

请您参考如下方法:

使用DataFrame.mean首先获取 0 值的百分比,然后使用 loc 进行过滤 - 需要小于或等于 0.5 的所有值:

zeroValues = df.eq(0).mean() 
print (zeroValues) 
Name      0.000000 
Age       0.000000 
Height    0.666667 
Score     1.000000 
Income    0.333333 
dtype: float64 
 
print (zeroValues <= 0.5) 
Name       True 
Age        True 
Height    False 
Score     False 
Income     True 
dtype: bool 
 
df = df.loc[:, zeroValues <= 0.5] 
print (df) 
     Name  Age  Income 
0    Alex   10    4000 
1     Bob   12    4000 
2  Clarke   13       0 

一行解决方案:

df = df.loc[:, df.eq(0).mean().le(.5)] 
print (df) 
     Name  Age  Income 
0    Alex   10    4000 
1     Bob   12    4000 
2  Clarke   13       0