Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a value in one column is in a list in another column using pd.isin()

I have a DataFrame as below

df = pd.DataFrame({
    'x' : range(0,5),
    'y' : [[0,2],[3,4],[2,3],[3,4],[7,9]]
})

I would like to test for each row of x, if the value is in the list specified by column y

df[df.x.isin(df.y)]

so I would end up with:

enter image description here

Not sure why isin() does not work in this case

like image 839
PingPong Avatar asked Oct 29 '25 18:10

PingPong


1 Answers

df.x.isin(df.y) checks for each element x, e.g. 0, is equal to some of the values of df.y, e.g. is 0 equal to [0,2], no, and so on.

With this, you can just do a for loop:

df[ [x in y for x,y in zip(df['x'], df['y'])] ]
like image 108
Quang Hoang Avatar answered Oct 31 '25 06:10

Quang Hoang



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!