Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas: how to check if a column value is in other columns in the same row

Tags:

python

pandas

I have a pandas data frame in the following format:

col1 col2 col3 col4 col5
A    A    B    Z    X
B    A    Z    Z    X
A    A    C    Z    X
C    A    C    D    X
D    A    B    D    X

How can I filter the rows where the value in col1 is in col2, col3 or col4 (disregarding col5)?

I tried among other things:

df = df[df[['col2', 'col3', 'col4']].isin(['col1'])]

but get an empty data frame.

The expected output would be:

col1 col2 col3 col4 col5
A    A    B    Z    X
A    A    C    Z    X
C    A    C    D    X
D    A    B    D    X
like image 749
Marc Avatar asked Dec 07 '25 15:12

Marc


1 Answers

Check if any of the values are equal (eq) the value in column 1. DataFrame.eq supports an axis argument.

m = df[['col2', 'col3', 'col4']].eq(df['col1'], axis=0).any(1)
df[m]

  col1 col2 col3 col4 col5
0    A    A    B    Z    X
2    A    A    C    Z    X
3    C    A    C    D    X
4    D    A    B    D    X
like image 179
ALollz Avatar answered Dec 10 '25 05:12

ALollz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!