简体   繁体   English

将序列号添加到每组熊猫python

[英]add serial count to each group pandas python

I have a simple problem but haven't been able to fix it. 我有一个简单的问题,但无法解决。

I have a simple table such as: 我有一个简单的表,例如:

group1 
a
a
a
b
b
b
c
c

I can add a count to the column with: 我可以使用以下方法向该列添加计数:

df['count'] = range(1, len(df) + 1)

I have tried to alter this with groupby functions but can't manage to stop the count and restart per group such as: 我试图使用groupby函数更改此设置,但是无法停止计数并按组重新启动,例如:

group1 count
a 1
a 2
a 3
b 1
b 2
b 3
c 1
c 2

You could use cumcount . 您可以使用cumcount If you want to start from 1 you could add it: 如果要从1开始,可以添加它:

In [16]: df['count'] = df.groupby('group1').cumcount()+1

In [17]: df
Out[17]:
  group1  count
0      a      1
1      a      2
2      a      3
3      b      1
4      b      2
5      b      3
6      c      1
7      c      2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM