简体   繁体   中英

Slicing a multiindex via Pandas

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-

在此处输入图像描述

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)

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

If I understand your question correctly, what you want is the first level to contain VA, MD, NY , and the second level to have 8, 9 . If that is so, simply pass a list of each of these to loc :

s.loc[['VA', 'MD', 'NY'], [8,9]]
 
VA  8    0.314514
    9    0.426652
MD  8    0.347657
    9    0.417436
NY  8    0.001026
    9    0.460668
dtype: float64

The code above will select all of VA , MD , NY for the first level, and for the second level, it will collect only rows that have 8, 9 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM