Dean
Dean

Reputation: 171

I get a KeyError when using Multi-index on a dataframe

I have a dataframe (df_final) with 2 indexes (Mineral and Year).

                         Developed Countries   ...  Transition Countries 
Mineral      Year                              ...                       
Iron Fe      2014-01-01             543730900  ...              119680450
             2015-01-01             580394662  ...              113540570
             2016-01-01             608537133  ...              108977300
             2017-01-01             632252158  ...              109270430
             2018-01-01             648117225  ...              110999150
Chromium CrO 2014-01-01                451819  ...                2669000
             2015-01-01                457100  ...                2502900
             2016-01-01                469140  ...                2493000
             2017-01-01                416285  ...                2740200
             2018-01-01                509424  ...                3078100
Cobalt       2014-01-01                 15383  ...                   5400
             2015-01-01                 16298  ...                   5800
             2016-01-01                 15281  ...                   5600
             2017-01-01                 14032  ...                   4700
             2018-01-01                 12353  ...                   5330

Data gets returned perfectly fine with this query:

df_final.loc['Gold','2014']

However, I get a

KeyError: '2014'

with this query:

df_final.loc[:,'2014']

Any ideas?

Upvotes: 0

Views: 207

Answers (1)

AdibP
AdibP

Reputation: 2939

you can use this to get all Mineral with Year = '2014' :

df_final.loc[(df_final.index.levels[0], '2014'), :]

Upvotes: 1

Related Questions