pandas combine group by and rows to columns

前端 未结 2 664
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-14 12:15

I\'m trying to transform this dataset:

A   B   C
1   x1  a
1   x1  a
1   x1  b
2   x2  b
2   x2  a

into:

A   B   C1  C2  C         


        
2条回答
  •  梦谈多话
    2021-01-14 12:59

    Use groupby + apply -

    v = df.groupby(['A' ,'B']).C.apply(lambda x: x.tolist())
    
    df = pd.DataFrame(v.tolist(), index=v.index)\
           .rename(columns=lambda x: x + 1)\
           .add_prefix('C')\
           .reset_index()
    df
    
       A   B C1 C2    C3
    0  1  x1  a  a     b
    1  2  x2  b  a  None
    

提交回复
热议问题