首页 > 解决方案 > 检查多列的值是否相同(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)

标签: pythonpandassimilarity

解决方案


的经典案例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

推荐阅读