Flatten multiple columns in a dataframe to a single column

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

    If id isn't the index, set it first:

    df = df.set_index('id')
    
    df
    
        other_id_1  other_id_2  other_id_3
    id                                    
    1          100         101         102
    2          200         201         202
    3          300         301         302
    

    Now, call the pd.DataFrame constructor. You'll have to tile the index using np.repeat.

    df_new = pd.DataFrame({'other_id' : df.values.reshape(-1,)}, 
                             index=np.repeat(df.index, len(df.columns)))
    df_new
    
        other_id
    id          
    1        100
    1        101
    1        102
    2        200
    2        201
    2        202
    3        300
    3        301
    3        302
    

提交回复
热议问题