How to group dataframe rows into list in pandas groupby

前端 未结 12 2169
日久生厌
日久生厌 2020-11-21 04:56

I have a pandas data frame df like:

a b
A 1
A 2
B 5
B 5
B 4
C 6

I want to group by the first column and get second col

12条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-21 05:58

    Let us using df.groupby with list and Series constructor

    pd.Series({x : y.b.tolist() for x , y in df.groupby('a')})
    Out[664]: 
    A       [1, 2]
    B    [5, 5, 4]
    C          [6]
    dtype: object
    

提交回复
热议问题