如何检查3列是否相同,如果值相同,则添加具有该值的新列?

时间:2020-11-02 08:28:25

标签: python dataframe

我有一个看起来像这样的数据框。

index   Column A    Column B    Column C
0        alice       alice       alice
1        nick        nick        john
2        juli        nick        alice

我要签入Column A, Column B and Column C是否相等。如果相等,我想将该值添加为新的Column D。如果不是,请将None添加到Column D

我到目前为止已经做到了。

def func(row):
    if ((row['Column A']) == (row['Column B']) == (row['Column C'])):
        df['Column D'] = df['Column A']
    else:
        df['Column D'] = None

当我使用.. df.apply (lambda row: func(row),axis =1),我没有得到想要的输出。

我有这样的东西。

index   Column A    Column B    Column C    Column D
0      alice        alice       alice        None
1      nick         nick        john         None
2      juli         nick        alice        None

而我希望输出像..

index   Column A    Column B    Column C    Column D
0      alice        alice       alice        alice
1      nick         nick        john         None
2      juli         nick        alice        None

对此有任何帮助吗?

3 个答案:

答案 0 :(得分:1)

使用numpy where

在这里,您将数据框的一个子集进行比较并存储到数组arr中,然后将数组的第一列与其余列进行比较。

import numpy as np
arr = df[['A','B','C']].values
df['D'] = np.where((arr == arr[:, [0]]).all(axis=1),df['A'],None)

def func(row):
    if ((row['A']) == (row['B']) == (row['C'])):
        return row['A']
    else:
        return None

df['D'] = df.apply(lambda row: func(row),axis =1)

答案 1 :(得分:1)

在您的if子句中,您写道:

(row['Column A']) == (row['Column B']) == (row['Column C'])

我不确定这是否是正确的方法。您是否已在下面尝试将此代码作为if子句?

((row['Column A']) == (row['Column B'])) and ((row['Column B']) == (row['Column C']))

答案 2 :(得分:0)

我尝试过 df['Column D'] = np.where((((df['Column A'])==(df['Column B']))& (df['Column B'] == df['Column C'])),df['Column A'],None)

这有效!谢谢大家提出这个想法。