2

I use three columns from the data frame for indexing:

df = df.set_index(['col1','col2','col3'])

Then I try to get the row that corresponds to a particular index. I tried many different ways:

x = df.loc[(123,456,789)]

x = df.ix[(123,456,789)]

x = df.loc[123,456,789]

x = df.ix[123,456,789]

None of these options works. The error message that I get is:

raise e1
KeyError: 'MultiIndex lexsort depth 0, key was length 3'

I checked if the used value of index exists:

inds = []
for ind in df.index:
    inds.append(ind)

if (123,456,789) in inds:
    print 'in'
else:
    print 'out'

As the result I get in (so, this used value of index exists). What am I doing wrong?

1 Answer 1

2

After you sort the df, all your loc/ix methods should work.

df = df.set_index(['col1','col2','col3'])
df.sort(inplace=True)
Sign up to request clarification or add additional context in comments.

2 Comments

Should I sort the data frame before or after the indexing? How exactly should I sort it (what column should I use for sorting)?
After setting the index, sort the dataframe using index like above. Sorting will make MultiIndex lexsort depth (in the error message) from 0 to 3.

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.