Search code examples
pythonpandasmulti-index

Get location of a level in a pandas.MultiIndex


Given a pandas.MultiIndex, I would like to know the level number given a level name.

So, given

index = pd.MultiIndex(
        names=['ind1', 'ind2'],
        levels=[['a'], ['b']],
        codes=[[], []]
    )

I would like to find out the position of ind1 and ind2, without having to do

ind1_loc = [name for name in index.names if name == 'ind1'][0]

I feel that definitely should be possible but I can't find it in the documentation.

The reason why I want to do it is because neither iterrows() nor itertuples() return level names so that you must access the returned index by level number.


Solution

  • I believe you need indexing if need name of level or .index method for position by index name:

    index = pd.MultiIndex(
            names=['ind1', 'ind2'],
            levels=[['a'], ['b']],
            codes=[[], []]
        )
    
    print (index.names[1])
    ind2
    
    print (index.names.index('ind2'))
    1