pandas - 如果此列中的所有值都是特定值,则从数据框中删除列
问题描述
数据样本:
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
这两行既不给出结果也不产生错误
解决方案
用于df.all()
返回True/False
条件是否满足 fromdf.eq()
和 invert True
to False
,反之亦然 invert ~
,最后在 的帮助下过滤True
列df.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
推荐阅读
- c# - 使用 C# HttpClient 在两个请求之间保持 PHP 会话处于活动状态
- android - 尝试在空对象引用上调用虚拟方法 'void android.view.MotionEvent.setLocation(float, float)'
- variables - 具有两个条件读取变量的 For 循环
- python - 在 Pygame 中缩放图像/矩形
- python - 将文件转换为 pandas 数据框并逐行访问元素
- regex - 如何regex_replace找到的每个实例?
- javascript - base64到图像转换和使用php上传实时服务器
- ios - 如何使用cordova或ionic v1在iOS/iphone中将“返回”按钮自定义为“完成”
- plc - CODESYS 能否用于硬件 PLC 的开发(即非模拟)?
- c# - 文本可见性第二次无法正常工作