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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With