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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With