3

I have a bunch of Pandas code that uses tuples as indices. I've recently come across the need to access an individual element of a DataFrame with DataFrame.ix, which is getting confused by the tuples. It seems to think my tuple is a sequence of keys I want to access, not a single keys (which happens to be a sequence) that I want to access. How can I extract an individual row for which a tuple is the key?

Perhaps this is a cautionary tale not to use sequences in a Pandas index, but in my case it's too late.

import string, pandas as pd, numpy as np

bar = pd.DataFrame(np.random.random((8,2)))
bar.columns = ['col1', 'col2']
bar.index = list(string.ascii_lowercase)[:8]
print bar
print bar.iloc[0].name
print bar.ix[bar.iloc[0].name]

bar.index = [tuple(list(string.ascii_lowercase)[i:i+3]) for i in range(8)]
print bar.iloc[0].name
print bar.ix[bar.iloc[0].name] # Fails with `KeyError: 'a'`
2
  • Confirmed that both solutions work. I'll accept the one that uses ix since it conforms more narrowly to the question as asked. But is either of the two preferred? Commented Aug 24, 2014 at 22:39
  • xs may be preferable here. The indexers (ix, iloc, loc) can do a lot more, but because of the syntax ambiguity between tuple keys and MultiIndex selection, it's likely less error prone. Commented Aug 25, 2014 at 1:30

2 Answers 2

6

You can wrap the tuple in a list to make this work.

In [17]: bar.ix[[bar.iloc[0].name]]
Out[17]: 
               col1      col2
(a, b, c)  0.216689  0.262511
Sign up to request clarification or add additional context in comments.

1 Comment

Note that this returns a DataFrame instance and the xs method in the other answer returns a Series instance.
3

I don't think it is possible to do it with indexing, but you can do it with xs:

>>> bar.xs(bar.iloc[0].name)
col1    0.864788
col2    0.708136
Name: (a, b, c), dtype: float64

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.