Lisa
Lisa

Reputation: 4416

How to slice MultiIndex and column?

midx = pd.MultiIndex(levels=[['zero', 'one'], ['x', 'y']],labels = [[1, 1, 0, 0],[1, 0, 1, 0]])
        df = pd.DataFrame(np.random.randn(4, 2), index=midx)

>>midx
               0         1
one  y  0.477304  0.247328
     x -1.267339 -1.779735
zero y  0.812613  1.119952
     x  0.092788  0.384020

A more readable way of doing this? have tried df.loc['one',1] no luck..

df.xs('one')[1]
Out[44]: 
y    0.247328
x   -1.779735

Upvotes: 1

Views: 46

Answers (2)

jpp
jpp

Reputation: 164623

As an alternative to pd.IndexSlice, you can use pd.DataFrame.query and select your column in a separate step:

res = df.query('ilevel_0 == "one"').loc[:, 1]

As per the docs, ilevel_0 is used to represent the first unnamed index. For clarity, you can replace this with a genuine name if you defined it as such when you construct the dataframe.

Upvotes: 0

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210822

IIUC:

In [74]: df.loc['one', 1]
Out[74]:
y    0.247328
x   -1.779735
Name: 1, dtype: float64

or more explicitly:

In [80]: df.loc[pd.IndexSlice['one', :], 1]
Out[80]:
one  y    0.247328
     x   -1.779735
Name: 1, dtype: float64

Upvotes: 1

Related Questions