Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - Pandas - Dataframe.set_index - how to keep the old index column

I have this Dataframe:

import pandas as pd
df = pd.DataFrame({'Hugo' : {'age' : 21, 'weight' : 75},
                   'Bertram': {'age' : 45, 'weight' : 65},
                   'Donald' : {'age' : 75, 'weight' : 85}}).T
df.index.names = ['name']


         age  weight
name                
Bertram   45      65
Donald    75      85
Hugo      21      75

I want to change the index to the column 'age':

df.set_index('age', inplace=True)

     weight
age        
45       65
75       85
21       75

The old index-column name gets lost. Is there a way to change the index without losing the original index-column and getting the old column as 'normal' column again, so that it looks like this?

     name       weight
age        
45   Bertram    65
75   Donald     85
21   Hugo       75
like image 788
Egirus Ornila Avatar asked Apr 08 '18 17:04

Egirus Ornila


2 Answers

Use reset_index first and then set_index:

df = df.reset_index().set_index('age')
print (df)
        name  weight
age                 
45   Bertram      65
75    Donald      85
21      Hugo      75
like image 138
jezrael Avatar answered Nov 13 '22 10:11

jezrael


Adding the append=True and with reset_index

df.set_index('age', append=True).reset_index(level=0)
Out[80]: 
        name  weight
age                 
45   Bertram      65
75    Donald      85
21      Hugo      75
like image 10
BENY Avatar answered Nov 13 '22 08:11

BENY