Search code examples
pythonpandasmulti-index

How to extract the index names of a multiindexed dataframe?


I have a multi-indexed dataframe that Looks like this:

                                            TQ bought  
HT           Detailed Instrument                   
Alternative     Investments                 359.445000  
Alternative     Investments                 633.670000  
Alternative     Investments                237.970000  
Alternative     Investments                 40.955000  

HT and Detailed Instrument are the multi-index column names, TQ bought represent the values of the Pivot table.

I'd like to extract the column names of the index as list, such that:

idx_headers = ["HT", "Detailed Instrument"]

I have tried df.index.levels but this does not generate the desired output. Any ideas?


Solution

  • Use index.names:

    print (df.index)
    MultiIndex(levels=[['Alternative'], ['Investments']],
               labels=[[0, 0, 0, 0], [0, 0, 0, 0]],
               names=['HT Detailed', 'Instrument'])
    
    print (df.index.names)
    ['HT Detailed', 'Instrument']