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

前端 未结 7 654
后悔当初
后悔当初 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:42

    either:

    df['index1'] = df.index
    

    or, .reset_index:

    df.reset_index(level=0, inplace=True)
    

    so, if you have a multi-index frame with 3 levels of index, like:

    >>> 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
    

    and you want to convert the 1st (tick) and 3rd (obs) levels in the index into columns, you would do:

    >>> df.reset_index(level=['tick', 'obs'])
              tick  obs     val
    tag                        
    C   2016-02-26    2  0.0139
    A   2016-02-27    2  0.5577
    C   2016-02-28    6  0.0303
    

提交回复
热议问题