Skip to content
Advertisement

Pandas multindex on column after merge

I created this dataframe:

d1 = {'john': [10, 11], 'adam': [20,21]}
d2 = {'john': [1,12], 'adam': [3,34]}
test_df1= pd.DataFrame(data=d1)
test_df2= pd.DataFrame(data=d2)

current = pd.concat([test_df1, test_df2], keys=['test_df1','test_df2'], axis=1)
current

enter image description here

but I need to change order in column multiindex. I need to have something like this

data = {('John', 'test_df1'): [10, 11], ('John', 'test_df2'): [1, 12], ('Adam', 'test_df1'): [20, 21], ('Adam','test_df2'): [3,34]}
columns = pd.MultiIndex.from_tuples([('John', 'test_df1'),('John', 'test_df2'),('Adam', 'test_df1'),('Adam', 'test_df2')])
needed = pd.DataFrame(data, columns=columns)
needed

enter image description here

Could you help me :) ?

Advertisement

Answer

You can use swaplevel on the resulting dataframe:

current.swaplevel(0,1, axis=1).sort_index(axis=1)

Output:

      adam              john         
  test_df1 test_df2 test_df1 test_df2
0       20        3       10        1
1       21       34       11       12
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement