Set column names when stacking pandas DataFrame

后端 未结 3 1628
清歌不尽
清歌不尽 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:59

    pd.melt is often useful for converting DataFrames from "wide" to "long" format. You could use pd.melt here if you convert the id and date index levels to columns first:

    In [56]: pd.melt(df.reset_index(), id_vars=['id', 'date'], value_vars=['value', 'value2'], var_name='var_name', value_name='value')
    Out[56]: 
       id        date var_name  value
    0   1  2015-09-31    value    100
    1   2  2015-09-31    value     95
    2   3  2015-09-31    value     42
    3   1  2015-09-31   value2    200
    4   2  2015-09-31   value2     57
    5   3  2015-09-31   value2     27
    

提交回复
热议问题