Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge multilevel (i.e. MultiIndex) dataframes?

What's the python/panda way to merge on multilevel dataframe on column "t" under "cell1" and "cell2"?

import pandas as pd
import numpy as np

df1 = pd.DataFrame(np.arange(4).reshape(2, 2), 
               columns = [['cell 1'] * 2, ['t', 'sb']])
df2 = pd.DataFrame([[1, 5], [2, 6]], 
           columns = [['cell 2'] * 2, ['t', 'sb']])

Now when I tried to merge on "t", python REPL will error out

ddf = pd.merge(df1, df2, on='t', how='outer')

What's a good way to handle this?

like image 895
Carson Pun Avatar asked Jan 28 '26 05:01

Carson Pun


1 Answers

pd.merge(df1, df2, left_on=[('cell 1', 't')], right_on=[('cell 2', 't')])
like image 187
Mike Graham Avatar answered Jan 30 '26 21:01

Mike Graham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!