Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the sub_level index value of Pandas dataframe?

Tags:

pandas

I have a multilevel dataframe df :

>>> df
                   sales     cash
STK_ID RPT_Date                  
000568 20120630   51.926   42.845
       20120930   80.093   57.488
000596 20120630   22.278   18.247
       20120930   32.585   26.177
000799 20120630    9.291    6.513
       20120930   14.784    8.157

And I want to get the value list of sub_level index 'STK_ID' , which will return a list of ['000568','000596','000799'].
Is there any direct function to do this (without using reset_index and getting the column value)?

like image 926
bigbug Avatar asked Feb 18 '23 19:02

bigbug


1 Answers

You are looking for index.levels:

In [10]: df1.index.levels
Out[10]: 
[Index(['000568', '000596', '000799'], dtype=object),
 Int64Index([20120630, 20120930], dtype=int64)]

In [11]: df1.index.levels[0]
Out[11]: Index(['000568','000596','000799'], dtype=object)

Note you can see the index names:

In [12]: df1.index.names
Out[12]: ['STK_ID', 'RPT_Date']

These are discussed in the docs here.

like image 61
Andy Hayden Avatar answered May 11 '23 01:05

Andy Hayden