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

后端 未结 3 791
栀梦
栀梦 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:34

    You can convert the column names to multi index based on the columns pattern and then stack at a particular level depending on the result you need:

    import pandas as pd
    df.set_index('id', inplace=True)
    df.columns = pd.MultiIndex.from_tuples(tuple(df.columns.str.split("_")))
    df.stack(level = 1).reset_index(level = 1, drop = True).reset_index()
    
    # id    a   b    c      
    #101    a   1   aa
    #101    b   2   bb
    #101    c   3   cc
    #102    d   4   dd
    #102    e   5   ee
    #102    f   6   ff
    

提交回复
热议问题