python - 检查多列的值是否相同(python)
问题描述
我有一个二进制数据框,我想检查特定行中的所有值是否都具有值 1。例如,我有以下数据框。由于第 0 行和第 2 行在 col1 到 col3 中都包含值 1,因此结果应该为 1,如果不是,则应该为 0。
import pandas as pd
d = {'col1': [1, 0,1,0], 'col2': [1, 0,1, 1], 'col3': [1,0,1,1], 'outcome': [1,0,1,0]}
df = pd.DataFrame(data=d)
由于我自己的数据框要大得多,我正在寻找一种比以下更优雅的方式,有什么想法吗?
def similar(x):
if x['col1'] == 1 and x['col2'] == 1 and x['col3'] == 1:
return 1
else:
''
df['outcome'] = df.apply(similar, axis=1)
解决方案
的经典案例all
。
(iloc
只是在那里无视你当前的结果 col,如果你没有它,你可以使用它df == 1
。)
df['outcome'] = (df.iloc[:,:-1] == 1).all(1).astype(int)
col1 col2 col3 outcome
0 1 1 1 1
1 0 0 0 0
2 1 1 1 1
3 0 1 1 0
推荐阅读
- python - TypeError:如果没有指定评分,则传递的估计器应该有一个'score'方法
- flutter - 如何在 Flutter 的 ListView 中添加复选框?
- java - SpannableStringBuilder 不显示来自 Firebase (Kotlin) 的每个数据的图像跨度
- html - 颤振:bottomNavigationBar无法使用WebView在html页面之间切换
- javascript - 如何更新表格而不在每个按钮单击时添加新表格?
- python - 有什么办法可以让这个功能更快
- php - Laravel 收到 403 禁止错误“您无权访问此资源”。
- python - 为什么 MATPLOTLIB 图表在发出命令后没有关闭?
- php - 如何使用 PHP 连接到 PostgreSQL 数据库?
- kotlin - 为什么普通函数需要用 viewModelScope.launch 包装?