11

I am not really sure how multi indexing works, so I maybe simply be trying to do the wrong things here. If I have a dataframe with

        Value
A  B         
1  1    5.67
1  2    6.87
1  3    7.23
2  1    8.67
2  2    9.87
2  3    10.23

If I want to access the elements where B=2, how would I do that? df.ix[2] gives me the A=2. To get a particular value it seems df.ix[(1,2)] but that is the purpose of the B index if you can't access it directly?

3 Answers 3

8

You can use xs:

In [11]: df.xs(2, level='B')
Out[11]:
   Value
A
1   6.87
2   9.87

alternatively:

In [12]: df1.xs(1, level=1)
Out[12]:
   Value
A
1   5.67
2   8.67
Sign up to request clarification or add additional context in comments.

Comments

6

Just as an alternative, you could use df.loc:

>>> df.loc[(slice(None),2),:]
     Value
A B       
1 2   6.87
2 2   9.87

The tuple accesses the indexes in order. So, slice(None) grabs all values from index 'A', the second position limits based on the second level index, where 'B'=2 in this example. The : specifies that you want all columns, but you could subet the columns there as well.

1 Comment

you can even use a list of indices, like df.loc[(slice(None),[2, 3]),:]
0

If you only want to return a cross-section, use xs (as mentioned by @Andy Hayden).

However, if you want to overwrite some values in the original dataframe, use pd.IndexSlice (with pd.loc) instead. Given a dataframe df:

In [73]: df
Out[73]:
                 col_1  col_2
index_1 index_2
1       1            5      6
        1            5      6
        2            5      6
2       2            5      6

if you want to overwrite with 0 all elements in col_1 where index_2 == 2 do:

In [75]: df.loc[pd.IndexSlice[:, 2], 'col_1'] = 0

In [76]: df
Out[76]:
                 col_1  col_2
index_1 index_2
1       1            5      6
        1            5      6
        2            0      6
2       2            0      6

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.