Copying the example from this question, consider the following dataframe:
mux = pd.MultiIndex.from_arrays([
list('aaaabbbbbccddddd'),
list('tuvwtuvwtuvwtuvw')
], names=['one', 'two'])
df = pd.DataFrame({'col': np.arange(len(mux))}, mux)
col
one two
a t 0
u 1
v 2
w 3
b t 4
u 5
v 6
w 7
t 8
c u 9
v 10
d w 11
t 12
u 13
v 14
w 15
Let's say I want to keep only two rows of the second level of multi index. i.e. my final dataframe looks like this:
col
one two
a t 0
u 1
b t 4
u 5
c u 9
v 10
d w 11
t 12
What's the best way of achieving the above? Ideally, I would have liked to do something like this (obviously wrong syntax)
df.iloc[(:, :2)]
i.e. all values from level 0, and first 2 values from level 1.