35

I have multiindex dataframe that looks like this:

                value
year    name                
1921    Ah      40     
1921    Ai      90      
1922    Ah      100     
1922    Ai      7

in which year and name are the indices. I want to select every row where the name Ai appears. I have tried df.loc[(:,'Ai')] and df.loc['Ai'] but both give errors. How do I index only using the name column?

3 Answers 3

42

@sacul has the most idiomatic answer, but here are a few alternatives.

MultiIndex.get_level_values

df[df.index.get_level_values('name') == 'Ai']

           value
year name       
1921 Ai       90
1922 Ai        7

DataFrame.query

df.query('name == "Ai"')

           value
year name       
1921 Ai       90
1922 Ai        7

DataFrame.loc(axis=0) with pd.IndexSlice

Similar to @liliscent's answer, but does not need the trailing : if you specify axis=0.

df.loc(axis=0)[pd.IndexSlice[:, 'Ai']]

           value
year name       
1921 Ai       90
1922 Ai        7
Sign up to request clarification or add additional context in comments.

2 Comments

Faster, you deserve +1
I didn't know you could use query() with row multi-index. I find this one to be the most intuitive syntax of all the answers.
22

I would use .xs on the first level of your multiindex (note: level=1 refers to the "second" index (name) because of python's zero indexing: level 0 is year in your case):

df.xs('Ai', level=1, drop_level=False)
# or
df.xs('Ai', level='name', drop_level=False)

           value
year name       
1921 Ai       90
1922 Ai        7

1 Comment

All good answers but this is the most straightforward solution I think. Thanks very much.
14

If you prefer loc, you can use:

In [245]: df.loc[(slice(None), 'Ai'), :]
     ...: 
Out[245]: 
           value
year name       
1921 Ai       90
1922 Ai        7

3 Comments

Good answer, this is equivalent to df.loc[pd.IndexSlice[:, 'Ai'], :].
@coldspeed Thanks.
Documented in using slicers and index slice.

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.