Pandas Melt several groups of columns into multiple target columns by name

后端 未结 3 800
栀梦
栀梦 2020-12-09 04:58

I would like to melt several groups of columns of a dataframe into multiple target columns. Similar to questions Python Pandas Melt Groups of Initial Columns Into Multiple T

3条回答
  •  无人及你
    2020-12-09 05:48

    There is a more efficient way to do these type of problems that involve melting multiple different sets of columns. pd.wide_to_long is built for these exact situations.

    pd.wide_to_long(df, stubnames=['a', 'b', 'c'], i='id', j='dropme', sep='_')\
      .reset_index()\
      .drop('dropme', axis=1)\
      .sort_values('id')
    
        id  a  b   c
    0  101  a  1  aa
    2  101  b  2  bb
    4  101  c  3  cc
    1  102  d  4  dd
    3  102  e  5  ee
    5  102  f  6  ff
    

提交回复
热议问题