Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the index names of a multiindexed dataframe, pandas

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?

like image 767
Carmen Avatar asked Mar 11 '23 03:03

Carmen


2 Answers

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']
like image 157
jezrael Avatar answered Mar 12 '23 17:03

jezrael


You're looking for df.index.names.

See: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.html

like image 21
IanS Avatar answered Mar 12 '23 16:03

IanS