您可以使用
size
df.groupby(['A','B']).size()Out[590]: A Bx p 2y q 1z r 2dtype: int64
为您的解决方案添加列之一
df.groupby(['A','B']).B.agg('count')Out[591]: A Bx p 2y q 1z r 2Name: B, dtype: int64更新:
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 c0 x p 21 y q 12 z r 2


