Using the modified example from here
In [30]: def mklbl(prefix,n): return ["%s%s" % (prefix,i) for i in range(n)] ....: In [31]: columns = MultiIndex.from_tuples([('a','foo'),('a','bar'), ('b','foo'),('b','bah')], names=['lvl0', 'lvl1']) In [33]: index = MultiIndex.from_product([mklbl('A',4),mklbl('B',2)]) In [34]: df = DataFrame(np.arange(len(index)*len(columns)).reshape((len(index),len(columns))), index=index, columns=columns).sortlevel().sortlevel(axis=1) In [35]: df Out[35]: lvl0 ab lvl1 bar foo bah foo A0 B0 1 0 3 2 B1 5 4 7 6 A1 B0 9 8 11 10 B1 13 12 15 14 A2 B0 17 16 19 18 B1 21 20 23 22 A3 B0 25 24 27 26 B1 29 28 31 30 In [36]: df.loc['A0'] Out[36]: lvl0 ab lvl1 bar foo bah foo B0 1 0 3 2 B1 5 4 7 6 In [37]: df.loc['A1'] Out[37]: lvl0 ab lvl1 bar foo bah foo B0 9 8 11 10 B1 13 12 15 14
No loop required.
You can also select them to return the frame (with the original MI) for example df.loc[['A1']]
If you want to get the values ββin the index:
In [38]: df.index.get_level_values(0).unique() Out[38]: array(['A0', 'A1', 'A2', 'A3'], dtype=object)
source share