Pandas : How to check specific column's value isn't in other columns?

Question:

Example df:

   A B C
0  1 9 0
1  5 7 5
2  8 6 8

Check C column’s value isn’t in column A or B? And create a new column(D) for the result.
Expect Output:

   A B C D
0  1 9 0 0
1  5 7 5 1
2  8 6 8 1

If can find column C’s value in column A or B reture 1 otherwise reture 0.

Asked By: smelling lady

||

Answers:

This is an example of code that you can do :

#Creation of your df
df = pd.DataFrame(columns=["A","B","C"])
df["A"]=[1,5,8]
df["B"]=[9,7,6]
df["C"]=[0,5,8]

# Answer of your question :

col_D = []

for val in df["C"].values:
    if val in df["A"].values or val in df["B"].values:
        col_D.append(1)
    else:
       col_D.append(0) 
       
df["D"] = col_D

Answered By: Said Amz

For a vectorial solution, use comparison with eq and aggregation with any, then convert the resulting booleans to integers with astype:

df['D'] = df[['A', 'B']].eq(df['C'], axis=0).any(axis=1).astype(int)

output:

   A  B  C  D
0  1  9  0  0
1  5  7  5  1
2  8  6  8  1
Answered By: mozway
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.