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

后端 未结 2 914
[愿得一人]
[愿得一人] 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条回答
  •  借酒劲吻你
    2020-11-30 09:23

    pandas >= 1.1: DataFrame.value_counts

    This is an identical replacement for df.groupby(['A', 'B']).size().

    df.value_counts(['A', 'B'])
    
    A  B
    z  r    2
    x  p    2
    y  q    1
    dtype: int64
    
    df.value_counts(['A', 'B']).reset_index(name='c')
    
       A  B  c
    0  z  r  2
    1  x  p  2
    2  y  q  1
    

提交回复
热议问题