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

后端 未结 5 1102
借酒劲吻你
借酒劲吻你 2021-02-05 06:36

I have this Dataframe:

import pandas as pd
df = pd.DataFrame({\'Hugo\' : {\'age\' : 21, \'weight\' : 75},
                   \'Bertram\': {\'age\' :         


        
5条回答
  •  旧时难觅i
    2021-02-05 07:21

    Your DataFrame df has name (= 'Bertram', 'Donald', 'Hugo') as index

    That is, your df is:

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

    You can convert the index (name) into a new column inside your DataFrame df by using the .reset_index() method.

    df.reset_index(inplace=True)
    

    name becomes a column and the new index is the standard default integer index:

    Your df looks like this now:

    Out[1]:    
        name     age  weight
    
    0   Bertram   45      65
    1   Donald    75      85
    2   Hugo      21      75
    

    Now, you can change the index to age with the .set_index() method.

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

    dfis now:

    Out[2]: 
         name  weight
    age                 
    45   Bertram      65
    75   Donald       85
    21   Hugo         75
    

    As @jezrael points out above you can do this in a single step, instead of two steps, like this:

    df = df.reset_index().set_index('age')
    

提交回复
热议问题