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

Time:09-26

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.

CodePudding user response:

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

CodePudding user response:

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

  • Related