Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyError while accessing multi index dataframe in Pandas

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?

like image 514
nithinj Avatar asked Jun 01 '26 10:06

nithinj


2 Answers

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.

like image 159
miradulo Avatar answered Jun 02 '26 22:06

miradulo


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

like image 33
EdChum Avatar answered Jun 03 '26 00:06

EdChum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!