Concatenate rows of pandas DataFrame with same id

后端 未结 1 809
盖世英雄少女心
盖世英雄少女心 2021-02-04 14:16

Say I have a pandas DataFrame such as:

   A  B  id
0  1  1   0
1  2  1   0
2  3  2   1
3  0  2   1

Say I want to combine rows with the same id

1条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-04 14:55

    You could use groupby for that with groupby agg method and tolist method of Pandas Series:

    In [762]: df.groupby('id').agg(lambda x: x.tolist())
    Out[762]: 
             A       B
    id                
    0   [1, 2]  [1, 1]
    1   [3, 0]  [2, 2]
    

    groupby return an Dataframe as you want:

    In [763]: df1 = df.groupby('id').agg(lambda x: x.tolist())
    
    In [764]: type(df1)
    Out[764]: pandas.core.frame.DataFrame
    

    To exactly match your expected result you could additionally do reset_index or use as_index=False in groupby:

    In [768]: df.groupby('id', as_index=False).agg(lambda x: x.tolist())
    Out[768]: 
       id       A       B
    0   0  [1, 2]  [1, 1]
    1   1  [3, 0]  [2, 2]
    
    In [771]: df1.reset_index()
    Out[771]: 
       id       A       B
    0   0  [1, 2]  [1, 1]
    1   1  [3, 0]  [2, 2]
    

    0 讨论(0)
提交回复
热议问题