Python Pandas slice multiindex by second level index (or any other level)
Another way to slice by arbitrary level in a multi level index is to Use slice(None)
with .loc[]
. .loc[]
will take a tuple for multi level index, using slice(None)
for a level indicates that particular index is not being sliced, then pass a single item or list for the index that is being sliced. Hope it helps future readers
df.loc[ ( slice(None), [3, 4] ), : ]
Use an indexer to slice arbitrary values in arbitrary dimensions--just pass a list with whatever the desired levels / values are for that dimension.
idx = pd.IndexSlice
df.loc[idx[:,[3,4]],:]
Title Score
First Rank
A 3 lime 80
4 lame 70
B 3 lame 200
4 dime 100
For reproducing the data:
from io import StringIO
s="""
First Rank Title Score
A 1 foo 100
A 2 bar 90
A 3 lime 80
A 4 lame 70
B 1 foo 400
B 2 lime 300
B 3 lame 200
B 4 dime 100
"""
df = pd.read_csv(StringIO(s),
sep='\s+',
index_col=["First", "Rank"])