1
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
0

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Could you please fix the formatting issues in the question. I can't do it because I don't have enough reputation yet.
I'm a bit confused. Doesn't the question say df.loc['one',1] has already been tried? Maybe edit the question ;)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.