检查多个列的值是否相同(python)

Check if values of multiple columns are the same (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)

试试这个:

df['outcome'] = df.apply(lambda x: 1 if df['col1']==1 and df['col2']==1 and df['col3']==1 else '', 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

这更通用,也适用于任何其他值。只需将第二个 == 1 替换为 == <your value>.

df['outcome'] = 0
df.loc[df.loc[(df.iloc[:,:-1].nunique(axis=1) == 1) \
    & (df.iloc[:,:-1] == 1).all(axis=1)].index, 'outcome'] = 1

要检查多个列是否具有相同的值,您可以运行这样:

df[['col1','col2','col3']].apply(lambda d: len(set(d)) == 1, axis=1).nunique() == 1

更好,

df.T.duplicated(['col1','col2','col3'])