首页 > 解决方案 > 如果此列中的所有值都是特定值,则从数据框中删除列

问题描述

数据样本:

choice   col1  col2  col3
1    100   110   100
2    110   110   100
5    110   110   100
...
50   100   200   300

应该变成:

choice   col1  col2
1    100   110
2    110   110
5    110   110
...
50   100   200

如果除第 50 行之外的所有值均为 100,则尝试删除第 3列。

尝试使用:

df['col3'].all() == 100
or
df['col3'].any() == 100

这两行既不给出结果也不产生错误

标签: pandasdataframe

解决方案


用于df.all()返回True/False条件是否满足 fromdf.eq()和 invert Trueto False,反之亦然 invert ~,最后在 的帮助下过滤Truedf.loc[]

df.loc[:,~df.eq(100).all()]

  id  col1  col2
   1   100   110
   2   110   110
   3   110   110

编辑:每次编辑,您可以尝试使用类似逻辑的自定义函数:

def myfunc(x,choice):
    x=x.set_index('choice')
    cond=x.loc[:,'col3'].drop(choice).eq(100).all()
    if cond:
        return x.drop('col3',1).reset_index()
    else:
        return x.reset_index()
myfunc(df,'50') #if choice column is an integer myfunc(df,50)

  choice   col1   col2
0      1  100.0  110.0
1      2  110.0  110.0
2      5  110.0  110.0
3     50  100.0  200.0

推荐阅读