Stacey
Stacey

Reputation: 5087

Remove rows from one data-frame that exist in another

I have two dataframes DfMaster and DfRemove

DfMaster looks like:

     Id           Name Building
0  4653     Jane Smith        A
1  3467    Steve Jones        B
2    34        Kim Lee        F
3  4567     John Evans        A 
4  3643   Kevin Franks        S
5   244  Stella Howard        D

DfRemove looks like:

     Id           Name Building
0  4567     John Evans        A 
1   244  Stella Howard        D

I would like to remove any records from DfMaster if they appear in DfRemove. So my new DfMaster in this example would look like:

     Id           Name Building
0  4653     Jane Smith        A
1  3467    Steve Jones        B
2    34        Kim Lee        F
3  3643   Kevin Franks        S

Where John and Stella have been removed.

I have tried:

DfMaster [DfMaster [~DfRemove [id]]]

without success.

How can I remove any records from DfMaster if they appear in DfRemove?

Upvotes: 1

Views: 48

Answers (2)

Ankur Sinha
Ankur Sinha

Reputation: 6639

You are nearly there, just do:

DfMaster= DfMaster[~DfMaster.Id.isin(DfRemove.Id)]

Output:

     Id           Name Building
0  4653     Jane Smith        A
1  3467    Steve Jones        B
2    34        Kim Lee        F
3  3643   Kevin Franks        S

Upvotes: 2

bexi
bexi

Reputation: 1216

Am I assuming correctly that Id is a unique identifier (i.e. comparing Id is sufficient)?

If so, how about this:

DfMaster = DfMaster.loc[~DfMaster['Id'].isin(DfRemove['Id'])]

Upvotes: 0

Related Questions