Home > OS >  Slicing a MultiIndex
Slicing a MultiIndex

Time:11-22

I want to slice a MultiIndex up to label NY for the first level and from label 8 onwards for the second level. How can I do this?

Here is the MultiIndex:

enter image description here

The output should look like this:

VA  8  Value
    9  Value 
MD  8  Value
    9  Value
NY  8  Value
    9  Value

Below is the code used to generate the MultiIndex:

states = ['VA','MD','NY','NJ','TX']
cd = list(range(10))
idx = pd.MultiIndex.from_product([states, cd])
s = pd.Series(np.random.rand(50), index=idx)

CodePudding user response:

You have to sort it first with sort_index:

subset = s.sort_index(level=0)['MD':'NY'].loc[:, 8:9]

Output:

>>> subset
MD  8    0.222916
    9    0.525990
NJ  8    0.888443
    9    0.374329
NY  8    0.569863
    9    0.680583
dtype: float64
  • Related