Flatten multiple columns in a dataframe to a single column

后端 未结 4 2071
独厮守ぢ
独厮守ぢ 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:40

    One more (or rather two):)

    pd.melt(df, id_vars='id', value_vars=['other_id_1', 'other_id_2', 'other_id_3'], value_name='other_id')\
    .drop('variable', 1).sort_values(by = 'id')
    

    Option 2:

    df.set_index('id').stack().reset_index(1,drop = True).reset_index()\ 
    .rename(columns = {0:'other_id'})
    

    Both ways you get

        id  other_id
    0   1   100
    1   1   101
    2   1   102
    3   2   200
    4   2   201
    5   2   202
    6   3   300
    7   3   301
    8   3   302
    

提交回复
热议问题