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

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

    To provide a bit more clarity, let's look at a DataFrame with two levels in its index (a MultiIndex).

    index = pd.MultiIndex.from_product([['TX', 'FL', 'CA'], 
                                        ['North', 'South']], 
                                       names=['State', 'Direction'])
    
    df = pd.DataFrame(index=index, 
                      data=np.random.randint(0, 10, (6,4)), 
                      columns=list('abcd'))
    

    The reset_index method, called with the default parameters, converts all index levels to columns and uses a simple RangeIndex as new index.

    df.reset_index()
    

    Use the level parameter to control which index levels are converted into columns. If possible, use the level name, which is more explicit. If there are no level names, you can refer to each level by its integer location, which begin at 0 from the outside. You can use a scalar value here or a list of all the indexes you would like to reset.

    df.reset_index(level='State') # same as df.reset_index(level=0)
    

    In the rare event that you want to preserve the index and turn the index into a column, you can do the following:

    # for a single level
    df.assign(State=df.index.get_level_values('State'))
    
    # for all levels
    df.assign(**df.index.to_frame())
    

提交回复
热议问题