Let
df = pd.DataFrame({"v":range(12)}, index=pd.MultiIndex.from_product([["a","b","c"],[1,2,3,4]]))
and suppose I want to select only rows with the first level being a
or c
:
v
a 1 0
2 1
3 2
4 3
c 1 8
2 9
3 10
4 11
I can do:
df[df.index.to_frame()[0].isin(("a","c"))]
but this creates an intermediate frame which seems like a waste.
Is there a better way?
In this case you want to use .loc
:
df.loc[["a", "c"], :]