How to group dataframe rows into list in pandas groupby

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

    As you were saying the groupby method of a pd.DataFrame object can do the job.

    Example

     L = ['A','A','B','B','B','C']
     N = [1,2,5,5,4,6]
    
     import pandas as pd
     df = pd.DataFrame(zip(L,N),columns = list('LN'))
    
    
     groups = df.groupby(df.L)
    
     groups.groups
          {'A': [0, 1], 'B': [2, 3, 4], 'C': [5]}
    

    which gives and index-wise description of the groups.

    To get elements of single groups, you can do, for instance

     groups.get_group('A')
    
         L  N
      0  A  1
      1  A  2
    
      groups.get_group('B')
    
         L  N
      2  B  5
      3  B  5
      4  B  4
    

提交回复
热议问题