How labels are maps in Pandas MultiIndex?

Viewed 1421

I have this data set,

new_df = pd.DataFrame( { 
    "Country" : ["C1", "C2", "C1", "C3", "C1", "C3", "C1"],
    "City" : ["ISB", "KHR", "LAH", "DUB", "RWP", "RWP", "RWP"],
    "Sales" : [10, 25, 40, 20, 45 , 43,10]  } )

on which i did this;

grouped_new_df = new_df.groupby(['Country', 'City'])
new_new_df = grouped_new_df.agg({'Sales': {'Mean': np.mean, 'Sum':np.sum}})

enter image description here

new_new_df.index
MultiIndex(levels=[['C1', 'C2', 'C3'], ['DUB', 'ISB', 'KHR', 'LAH', 'RWP']],
           labels=[[0, 0, 0, 1, 2, 2], [1, 3, 4, 2, 0, 4]],
           names=['Country', 'City'])

Here I don't understand how these labels labels=[[0, 0, 0, 1, 2, 2], [1, 3, 4, 2, 0, 4]], are mapping ?

2 Answers

The labels are the respective indices of your levels. For instance, the first level of your multiindex in Country. If you look at the levels for that, it is the list comprising C1, C2, and C3. So your data is C1,C1,C1,C2,C3,C3, i.e. indices [0,0,0,1,2,2] of the list [C1,C2,C3].

Same logic applies for the City levels

In your example , if you want the value of index level=1 , you can .

new_new_df.index.levels[1][new_new_df.index.labels[1]]
Out[230]: Index(['ISB', 'LAH', 'RWP', 'KHR', 'DUB', 'RWP'], dtype='object', name='City')
Related