Home > Software design >  Slicing a multiindex via Pandas
Slicing a multiindex via Pandas

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 requirement?

Here is the multi index-

enter image description here

The output should be similar to such format-

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

Also below is the code used to generate the multindex-

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