1

I have a dataframe df structured as follows:

  from       rate   to
0  CHF   1.000000  CHF
1  CHF  19.673256  MXN
2  CHF   0.000000  ZAR
3  CHF   0.000775  XAU
4  CHF  32.961405  THB

and I've re-indexed it to be as follows:

               rate
from to            
CHF  CHF   1.000000
     MXN  19.675255
     ZAR   0.000000
     XAU   0.000775
     THB  32.961068
...

using df = df.set_index(['from','to'],drop=True, append=False).

I want to simply call get on the dataframe using a pair of indices. For example, I would expect df[['CHF','MXN']] to return 19.675255 but instead an error is raised stating "['CHF' 'MXN'] not in index".

It seems like this should be very straightforward -- what am I doing wrong?

Thanks

1 Answer 1

1

Option 1
pd.IndexSlice

idx = pd.IndexSlice

df.loc[idx['CHF', 'MXN']]

rate    19.673256
Name: (CHF, MXN), dtype: float64

If you want the result as a scalar, call .item -

df.loc[idx['CHF', 'MXN']].item()
19.673256

Option 2
xs

df.xs(['CHF', 'MXN'])

rate    19.673256
Name: (CHF, MXN), dtype: float64
Sign up to request clarification or add additional context in comments.

5 Comments

Awesome thank you. This works. Off-hand, do you know which option should run fastest, or are they the same?
@Blake You're operating on an index, so both methods would probably be equally fast. It would depend on the individual overhead each function entails. My guess is loc would be slightly faster.
Let me asking a question :-)
@Wen I have one for you to answer: stackoverflow.com/questions/48122394/…
@cᴏʟᴅsᴘᴇᴇᴅ added an answer to that question :-)

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.