Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove rows from a dataframe based on another

I have been try my level best to compare two data frames in a specific manner but not successful. I hope experts over here can help with solution.

Below is my problem description: I have two dataframes.

Data frame #1 looks like this.

df1:
pid  name  age
121  John   36
132  Mary   26
132   Jim   46
145   Kim   50

Dataframe#2 looks like below

df2:
pid  name  age
121  John   32
132   Tom   28
132 Susan   40
155   Kim   50

I want to compare both df's in such a way that those rows in df2 which don't have the same pid's in df1 should be deleted.

My new data frame #2 should look like below

df2:
pid  name  age
121  John   32
132   Tom   28
132 Susan   40

Highly appreciate your help on this.

like image 857
Jithesh Erancheri Avatar asked Jan 16 '26 19:01

Jithesh Erancheri


1 Answers

You could use isin as in

df2[df2.pid.isin(df1.pid)]

which will return only the rows of df2 whose pid is in df1.

like image 137
Ami Tavory Avatar answered Jan 19 '26 10:01

Ami Tavory



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!