Alex Trevylan
Alex Trevylan

Reputation: 545

How to slice a data frame using index ids from another data frame?

I have a data frame (df1) that looks like this:

ID 
loc1
loc2
loc3 
loc6
loc9

I have another data frame (df2) that looks like this:

     ID    Values            Fruit 
    loc1   [0.1,0.2,0.4....] apple
    loc2   [0.1,0.2,0.4....] apple
    loc3   [0.1,0.2,0.3....] grape 
    loc4   [0.1,0.2,0.4....] pear 
    loc5   [0.1,0.1,0.4....] orange 
    loc6   [0.1,0.1,0.4....] apple
    loc7   [0.1,0.2,0.4....] apple
    loc8   [0.4,0.1,0.4....] apple 
    loc9   [0.3,0.2,0.4....] pear 
    loc10  [0.1,0.2,0.4....] orange 

I want to delete the rows in the second file using the keys from the first data frame file. I used this, taken from elsewhere on Stackedoveflow:

df1[df1.ID.isin(df2)] 

This simply returns:

AttributeError: 'DataFrame' object has no attribute 'ID'

Upvotes: 0

Views: 657

Answers (1)

rafaelc
rafaelc

Reputation: 59274

If ID is your index, then you want

df1[df1.index.isin(df2)] 

Depending on how your df2 is structured, you may want df1[df1.index.isin(df2.index)]

Upvotes: 2

Related Questions