简体   繁体   中英

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'

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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM