nsus
nsus

Reputation: 13

How to use df.rename?

I am solving an assignment problem from a mooc on Coursera. I have to rename a couple of row labels. I am a new to python and as such often fail to grasp certain nuances as i am fairly certain is the case here. I have tried the rename function as follows

energy.set_index('Country', inplace=True)
energy.rename(index={'Republic of Korea':'South Korea', 'United States of 
      America':'United States'})

However, the data frame isn't reflecting the change. The following code returns an empty dataframe.

energy[energy.index=='South Korea']

What am i doing wrong here? Thanks

Upvotes: 1

Views: 279

Answers (2)

U13-Forward
U13-Forward

Reputation: 71610

To explain:

Your code works fine, just is that you need to assign back, like (or use pandas inplace=True):

energy = energy.rename(index={'Republic of Korea':'South Korea', 
                          'United States of America':'United States'})

Or:

energy.rename(index={'Republic of Korea':'South Korea', 
                 'United States of America':'United States'},
          inplace=True)

Or:

energy=energy.rename({'Republic of Korea':'South Korea', 
           'United States of America':'United States'},
           axis="index")

Or:

energy.rename({'Republic of Korea':'South Korea', 
           'United States of America':'United States'},
           axis="index",inplace=True)

Note you can do:

energy.loc["South Korea"]

Instead of:

energy[energy.index=='South Korea']

Upvotes: 0

lightalchemist
lightalchemist

Reputation: 10219

Check out the docs. What you want is

energy = energy.rename(index={'Republic of Korea':'South Korea', 
                              'United States of America':'United States'})

or

energy.rename(index={'Republic of Korea':'South Korea', 
                     'United States of America':'United States'},
              inplace=True)

or

energy.rename({'Republic of Korea':'South Korea', 
               'United States of America':'United States'},
               axis="index", inplace=True)

Because inplace was not set to True, you need to store the return result.

Also, you can just do

energy.loc["South Korea"]

That is the whole point of having an index - so that you can use keys to access the rows.

Upvotes: 1

Related Questions