Search code examples
pythonpandasdataframemulti-index

How to merge multi-levels colums inside a pandas DataFrame?


Let DF be a multi-index DataFrame constructed like this:

df_A = {}
df_A['origin'] = pd.DataFrame({'a': [11,12,13], 'b': [True, True, False]})
df_A = pd.concat(df_A, axis=1)

df_B = {}
df_B['destination'] = pd.DataFrame({'c': [11,12,13], 'd': [True, True, False]})
df_B = pd.concat(df_B, axis=1)
df_B

df_C = {}
df_C['origin'] = pd.DataFrame({'e': [11,12,13], 'f': [True, True, False]})
df_C = pd.concat(df_C, axis=1)

DF = df_A.join(df_B.join(df_C))

We see that the resulting DataFrame has one duplicated column level (i.e., 'origin'):

enter image description here

Question: how can we merge the 'origin' columns into a single one? The desired result is:

enter image description here


Solution

  • They are already merged. It's displayed in that way because of columns order. You can just sort index to make origin columns adjacent to each other:

    DF.sort_index(axis=1, level=0, ascending=False)
    
      origin                destination    
           f   e      b   a           d   c
    0   True  11   True  11        True  11
    1   True  12   True  12        True  12
    2  False  13  False  13       False  13