How to convert index of a pandas dataframe into a column?

前端 未结 7 580
后悔当初
后悔当初 2020-11-22 08:54

This seems rather obvious, but I can\'t seem to figure out how to convert an index of data frame to a column?

For example:

df=
        gi       ptt_l         


        
7条回答
  •  悲哀的现实
    2020-11-22 09:25

    rename_axis + reset_index

    You can first rename your index to a desired label, then elevate to a series:

    df = df.rename_axis('index1').reset_index()
    
    print(df)
    
       index1         gi  ptt_loc
    0       0  384444683      593
    1       1  384444684      594
    2       2  384444686      596
    

    This works also for MultiIndex dataframes:

    print(df)
    #                        val
    # tick       tag obs        
    # 2016-02-26 C   2    0.0139
    # 2016-02-27 A   2    0.5577
    # 2016-02-28 C   6    0.0303
    
    df = df.rename_axis(['index1', 'index2', 'index3']).reset_index()
    
    print(df)
    
           index1 index2  index3     val
    0  2016-02-26      C       2  0.0139
    1  2016-02-27      A       2  0.5577
    2  2016-02-28      C       6  0.0303
    

提交回复
热议问题