Set column names when stacking pandas DataFrame

后端 未结 3 1635
清歌不尽
清歌不尽 2021-02-02 11:29

When stacking a pandas DataFrame, a Series is returned. Normally after I stack a DataFrame, I convert it back into a DataFrame

3条回答
  •  悲&欢浪女
    2021-02-02 11:54

    A pipe-ing friendly alternative to chrisb's answer:

    df.stack().rename_axis(['id', 'date', 'var_name']).rename('value').reset_index()
    

    And if explicit is better than implicit:

    (
        df
        .stack()
        .rename_axis(index={'id': 'id', 'date': 'date', None: 'var_name'})
        .rename('value')
        .reset_index()
    )
    

    When using the dict mapper, you can skip the names which should stay the same:

    df.stack().rename_axis(index={None: 'var_name'}).rename('value').reset_index()
    

提交回复
热议问题