First, you should sort as follows:
df.sort_index(level=['year','foo'], ascending=[1, 0], inplace=True)
It should fix KeyError. But df.loc[pd.IndexSlice[2002, :10], :] will not give you the result you expect. The loc function is not iloc, and it will try to find indices 0,1..9 in foo. Secondary Multiindex levels do not support iloc, I would suggest using groupby. If you already have this multi-index, you should do:
df.reset_index() df = df.sort_values(by=['year','foo'],ascending=[True,False]) df.groupby('year').head(10)
If you need n entries with the smallest foo value, you can use tail(n) . If you need, say, the first, third and fifth entries, you can use nth([0,2,4]) , as you mentioned in the question. I think this is the most efficient way to do this.
Danila savenkov
source share