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

后端 未结 3 795
栀梦
栀梦 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

    cols = df.columns.difference(['id'])
    
    pd.lreshape(df, cols.groupby(cols.str.split('_').str[0])).sort_values('id')
    Out: 
        id  a   c  b
    0  101  a  aa  1
    2  101  b  bb  2
    4  101  c  cc  3
    1  102  d  dd  4
    3  102  e  ee  5
    5  102  f  ff  6
    

提交回复
热议问题