简体   繁体   中英

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
  :        :       :         : 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM