3

I have the following dataframe having "Location" and "Name" as the index.

Location  Name   Cost   Item Purchased                
Store 1   Chris  22.5   Dog Food
          Kevyn   2.5   Kitty Litter
Store 2   Vinod   5.0   Bird Seed

I can access df.loc["Store 1"] But df.loc["Store 1"]["Kevyn"] is giving me KeyError. What am I doing wrong?

1

2 Answers 2

3

You're using some incorrect chained indexing here, where you want to be indexing both levels of the MultiIndex with something like

df.loc['Store 1', 'Kevyn']

See Basic indexing on axis with MultiIndex in the docs.

Sign up to request clarification or add additional context in comments.

Comments

1

You need to pass a tuple:

In [100]:
df.loc[('Store 1', 'Kevyn'),:]

Out[100]:
Cost                       2.5
Item Purchased    Kitty Litter
Name: (Store 1, Kevyn), dtype: object

The docs detail how to index

1 Comment

In fact, you should use df.loc[('Store 1', 'Kevyn'),:] in order to avoid misinterpretations, cf. pandas.pydata.org/pandas-docs/stable/user_guide/…

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.