How to group dataframe rows into list in pandas groupby

前端 未结 12 2164
日久生厌
日久生厌 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:43

    To solve this for several columns of a dataframe:

    In [5]: df = pd.DataFrame( {'a':['A','A','B','B','B','C'], 'b':[1,2,5,5,4,6],'c'
       ...: :[3,3,3,4,4,4]})
    
    In [6]: df
    Out[6]: 
       a  b  c
    0  A  1  3
    1  A  2  3
    2  B  5  3
    3  B  5  4
    4  B  4  4
    5  C  6  4
    
    In [7]: df.groupby('a').agg(lambda x: list(x))
    Out[7]: 
               b          c
    a                      
    A     [1, 2]     [3, 3]
    B  [5, 5, 4]  [3, 4, 4]
    C        [6]        [4]
    

    This answer was inspired from Anamika Modi's answer. Thank you!

提交回复
热议问题