konewka
konewka

Reputation: 650

Using a pandas MultiIndex to join two dataframes

I have two pandas data frames:

df1:

        column
index1
rec-1   foo
rec-2   bar
rec-3   bar
  :      :

df2:

          test
index2
rec-1-b   baz
rec-2-b   foo
rec-3-b   quux
   :       :

along with a MultiIndex object

multiIndex1:

(rec-1,rec-1-b)
(rec-2,rec-3-b)
:

linking the two data frames together. How would I now obtain a data frame that looks like this:

joined_df:

                  column   test
index1  index2
rec-1   rec-1-b   foo      baz
rec-2   rec-3-b   bar      quux
  :        :       :         : 

Upvotes: 1

Views: 806

Answers (1)

jezrael
jezrael

Reputation: 862591

I think you need reindex with join or concat:

mux = pd.MultiIndex.from_tuples([('rec-1','rec-1-b'),('rec-2','rec-3-b')])

df = df1.reindex(mux, level=0).join(df2.reindex(mux, level=1))

Or:

df = pd.concat([df1.reindex(mux, level=0), df2.reindex(mux, level=1)], axis=1)

print (df)
              column  test
rec-1 rec-1-b    foo   baz
rec-2 rec-3-b    bar  quux

Upvotes: 2

Related Questions