[英]Enumerate rows in each group starting from one
I have a dataframe (which is sorted on date, date column is not included in the example for simplicity) that looks like this:我有一个 dataframe (按日期排序,为简单起见,示例中不包括日期列),如下所示:
df = pd.DataFrame(['A', 'B' , 'B', 'A', 'C', 'B'], columns=['letters'])
letters
0 A
1 B
2 B
3 A
4 C
5 B
I want to create a new column that counts the occurrence of each value in the letters
column, increasing 1 by 1 as the value occurs in the letters
column.我想创建一个新列,计算
letters
列中每个值的出现次数,随着值出现在letters
列中,将值加 1。 The data frame I want to reach is like this:我想要达到的数据框是这样的:
letters occurance_counter
0 A 1
1 B 1
2 B 2
3 A 2
4 C 1
5 B 3
Any help would be amazing, thanks in advance!任何帮助都会很棒,在此先感谢!
You can groupby
and use the method cumcount
:您可以
cumcount
groupby
df['occurance_counter'] = df.groupby('letters')['letters'].cumcount().add(1)
Result:结果:
letters occurance_counter
0 A 1
1 B 1
2 B 2
3 A 2
4 C 1
5 B 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.