I have two dataframes. df1 is multi-indexed:
value
first second
a x 0.471780
y 0.774908
z 0.563634
b
According to the documentation, as of pandas 0.14, you can simply join single-index and multiindex dataframes. It will match on the common index name. The how
argument works as expected with 'inner'
and 'outer'
, though interestingly it seems to be reversed for 'left'
and 'right'
(could this be a bug?).
df1 = pd.DataFrame([['a', 'x', 0.471780], ['a','y', 0.774908], ['a', 'z', 0.563634],
['b', 'x', -0.353756], ['b', 'y', 0.368062], ['b', 'z', -1.721840],
['c', 'x', 1], ['c', 'y', 2], ['c', 'z', 3],
],
columns=['first', 'second', 'value1']
).set_index(['first', 'second'])
df2 = pd.DataFrame([['a', 10], ['b', 20]],
columns=['first', 'value2']).set_index(['first'])
print(df1.join(df2, how='inner'))
value1 value2
first second
a x 0.471780 10
y 0.774908 10
z 0.563634 10
b x -0.353756 20
y 0.368062 20
z -1.721840 20