Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas Accessing values from second index in multi-indexed dataframe

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?

like image 844
f4hy Avatar asked May 24 '13 22:05

f4hy


2 Answers

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
like image 165
Andy Hayden Avatar answered Oct 08 '22 18:10

Andy Hayden


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.

like image 34
LMc Avatar answered Oct 08 '22 17:10

LMc