Flatten multiple columns in a dataframe to a single column

后端 未结 4 2080
独厮守ぢ
独厮守ぢ 2020-12-11 11:07

I have a dataframe like this:

id    other_id_1    other_id_2    other_id_3
1     100           101           102
2     200           201           202
3              


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-11 11:21

    By using pd.wide_to_long:

    pd.wide_to_long(df,'other_id_',i='id',j='drop').reset_index().drop('drop',axis=1).sort_values('id')
        Out[36]: 
           id  other_id_
        0   1        100
        3   1        101
        6   1        102
        1   2        200
        4   2        201
        7   2        202
        2   3        300
        5   3        301
        8   3        302
    

    or unstack

    df.set_index('id').unstack().reset_index().drop('level_0',1).rename(columns={0:'other_id'})
    
    Out[43]: 
       id  other_id
    0   1       100
    1   2       200
    2   3       300
    3   1       101
    4   2       201
    5   3       301
    6   1       102
    7   2       202
    8   3       302
    

提交回复
热议问题