Python Pandas slice multiindex by second level index (or any other level) Python Pandas slice multiindex by second level index (or any other level) pandas pandas

Python Pandas slice multiindex by second level index (or any other level)


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.IndexSlicedf.loc[idx[:,[3,4]],:]           Title  ScoreFirst Rank             A     3     lime     80      4     lame     70B     3     lame    200      4     dime    100

For reproducing the data:

from io import StringIOs="""First Rank Title ScoreA      1    foo   100A      2    bar   90A      3    lime  80A      4    lame  70B      1    foo   400B      2    lime  300B      3    lame  200B      4    dime  100"""df = pd.read_csv(StringIO(s),                 sep='\s+',                 index_col=["First", "Rank"])


Another way to slice by 2nd (sub) level in a multi level index is to Use slice(None) with .loc[]. 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] ),  : ]