["python","pandas"]
Pandas: Get unique MultiIndex level values by label

Say you have this MultiIndex-ed DataFrame: df = pd.DataFrame({'country':['DE','DE','FR','FR'], 'biome':['Lake','Forest','Lake','Forest'], 'area':[10,20,30,40], 'count':[7,5,2,3]}) df = df.set_index(['country','biome']) Which looks like this: area count country biome DE Lake 10 7 Forest 20 5 FR Lake 30 2 Forest 40 3 I would like to retrieve the unique values per index level. This can be accomplished using >>> df.index.levels[0] ['DE', 'FR'] >>> df.index.levels[1] ['Lake', 'Forest'] What I would really like to do, is to retrieve these lists by addressing the levels by their name, i.e. 'country' and 'biome'. The shortest two ways I could find looks like this: >>> list(set(df.index.get_level_values('country'))) ['DE', 'FR'] >>> df.index.levels[df.index.names.index('country')] ['DE', 'FR'] But non of them are very elegant. Is there a shorter and/or more performant way?
Pandas 0.23.0 finally introduced a much cleaner solution to this problem: the level argument to Index.unique(): In [3]: df.index.unique(level='country') Out[3]: Index(['DE', 'FR'], dtype='object', name='country') This is now the recommended solution. It is far more efficient because it avoids creating a complete representation of the level values in memory, and re-scanning it.