如何使用来自另一个数据框的索引ID对数据帧进行切片?

时间:2018-04-18 16:53:16

标签: python pandas

我有一个如下所示的数据框(df1):

ID 
loc1
loc2
loc3 
loc6
loc9

我有另一个数据框(df2),如下所示:

     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 

我想使用第一个数据框文件中的键删除第二个文件中的行。我使用了这个,取自Stackedoveflow上的其他地方:

df1[df1.ID.isin(df2)] 

这简单地返回:

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

1 个答案:

答案 0 :(得分:1)

如果ID是您的索引,那么您需要

df1[df1.index.isin(df2)] 

根据df2的结构,您可能需要df1[df1.index.isin(df2.index)]