Search code examples
pythonpandasmulti-index

How to set multiindex column from existing multiindex column df


The objective is to add another multiindex on top of existing multiindex column in Pandas.

I have the impression this can be achieve as below

 # Assuming we have an existing multilevel index as below
df.columns = pd.MultiIndex.from_product([['level1'],['level2'],df.columns ])

# Along the pipeline, we would like to append another multiindex on top of it
    df.columns = pd.MultiIndex.from_product([['Top'],df.columns ])

However, the compiler return an error

NotImplementedError: isna is not defined for MultiIndex

May I know how to fix this issue?

Code to reproduce the above error

import pandas as pd
df = pd.DataFrame({'A': [11, 21, 31],
               'B': [12, 22, 32],
               'C': [13, 23, 33]},
              index=['ONE', 'TWO', 'THREE'])


df.columns = pd.MultiIndex.from_product([['level1'],['level2'],df.columns ])
df.columns = pd.MultiIndex.from_product([['Top'],df.columns ])

Expected output

      Top
      level1        
      level2        
           A   B   C
ONE       11  12  13
TWO       21  22  23
THREE     31  32  33

Solution

  • Use pd.concat:

    >>> pd.concat([df], keys=['Top'], axis='columns')
             Top
          level1
          level2
               A   B   C
    ONE       11  12  13
    TWO       21  22  23
    THREE     31  32  33