比方说,我有两个数据帧df1
和df2
,每个数据帧都有一个多索引。第一个多索引列是['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
答案 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