如何检查熊猫数据框多索引子集之间的相等性?

时间:2018-08-02 09:54:27

标签: python pandas dataframe

比方说,我有两个数据帧df1df2,每个数据帧都有一个多索引。第一个多索引列是['A','B','C','D'],第二个['A','B']

我想获取包含df行的数据帧df1,其中df1[['A','B']] == df2[['A','B']]。当['A','B']是我df的某些列时,此语法有效,但当['A','B']在索引中时,则无效。 (我宁愿避免使用df.reset_index()

这是最小的示例:

L = ([["foo","blih",23,1],
     ["foo","blah",2,13],
     ["bar","blih",1,23],
     ["bar","blah",2,31]])

example = pd.DataFrame(L,columns = ["A","B","value1","value2"])
L2 = ([["blih",23,1],
      ["blih",1,23]])
example2 = pd.DataFrame(L2,columns = ["B","value1","value2"])
example = example.set_index(["A","B"])
example2 = example2.set_index(["B"])

这是数据帧example

          value1  value2
A   B                
bar blih       1      23
    blah       2      31
foo blih      23       1
    blah       2      13

example2

      value1  value2
B                
blih      23       1
blih       1      23

预期输出: example的行,其中example['B'] == example2['B']

          value1  value2
A   B                
bar blih       1      23
foo blih      23       1

1 个答案:

答案 0 :(得分:0)

您要匹配多个列值,其中一些在索引中,而另一些不在索引中。 DataFrame.merge确实是您想要的。

example.reset_index().merge(example2).set_index(['A', 'B'])

输出:

          value1  value2
A   B                   
bar blih       1      23
foo blih      23       1

您需要在reset_index左边的DataFrame的唯一原因是因为合并将不会保留不是键的索引列的多索引。也就是说,

example.merge(example2, on=['B', 'value1', 'value2']) 

输出:

      value1  value2
B                   
blih      23       1
blih       1      23