Adding a 'count' column to the result of a groupby in pandas?

后端 未结 2 917
[愿得一人]
[愿得一人] 2020-11-30 08:33

I think this is a fairly basic question, but I can\'t seem to find the solution.

I have a pandas dataframe similar to the following:

import pandas as         


        
2条回答
  •  猫巷女王i
    2020-11-30 09:11

    You can using size

    df.groupby(['A','B']).size()
    Out[590]: 
    A  B
    x  p    2
    y  q    1
    z  r    2
    dtype: int64
    

    For your solution adding one of the columns

    df.groupby(['A','B']).B.agg('count')
    Out[591]: 
    A  B
    x  p    2
    y  q    1
    z  r    2
    Name: B, dtype: int64
    

    Update :

    df.groupby(['A','B']).B.agg('count').to_frame('c').reset_index()
    
    #df.groupby(['A','B']).size().to_frame('c').reset_index()
    Out[593]: 
       A  B  c
    0  x  p  2
    1  y  q  1
    2  z  r  2
    

提交回复
热议问题