Bing
Bing

Reputation: 631

Retain the previous index of the dataframe as a column after setting another column as a index

I have a dataframe(test4) of the following kind with Yrs as a index column-

                  Prs_90      Prs_80      Prs_70
        Yrs                                     
        2012  499.934588  521.512345  425.189729
        2013  579.063531  477.782099  256.382494
        2014  458.415624  456.480642  363.309507
        2015  422.547029  320.282754  578.728535

Now , I want to set Prs_90 as a index which I am doing using test4.set_index("Prs_90", inplace = True)

but it is removing the Yrs index completely which I want to retain.

                       Prs_80      Prs_70
           Prs_90                            
       854.819691  514.883611  338.596315
       780.394013  488.100756  417.143175
       752.188841  326.476833  644.588971
       703.369157  542.508996  361.643381

Expected Output-

                   Prs_80      Prs_70   Yrs
       Prs_90                            
   854.819691  514.883611  338.596315   2012
   780.394013  488.100756  417.143175   2013
   752.188841  326.476833  644.588971   2014
   703.369157  542.508996  361.643381   2015

How to do it?

Upvotes: 1

Views: 57

Answers (2)

Peter Sorensen
Peter Sorensen

Reputation: 73

Before introducing the new Prs_90 index you can call

df = df.reset_index()

reset_index() will make the present index into a column.

Upvotes: 1

run-out
run-out

Reputation: 3184

You could try the following:

test4.reset_index(drop=False).set_index("Prs_90")

Upvotes: 1

Related Questions