I need a cumulative sum of each name in my df['Name'] column, but I need the count to reset when a new name appears in the column. How would I accomplish this in pandas? I've tried various things with df.cumsum
, df.rolling
, etc with no luck.
Name
Devonta Freeman
Devonta Freeman
Devonta Freeman
Devonta Freeman
Devonta Freeman
Devonta Freeman
Devonta Freeman
Devonta Freeman
Devonta Freeman
Devonta Freeman
Devonta Freeman
Devonta Freeman
Devonta Freeman
Devonta Freeman
Devonta Freeman
Antonio Brown
Antonio Brown
Antonio Brown
Antonio Brown
Antonio Brown
Antonio Brown
Antonio Brown
Antonio Brown
Antonio Brown
Antonio Brown
Antonio Brown
Antonio Brown
Antonio Brown
Antonio Brown
Antonio Brown
Antonio Brown
Antonio Brown
Desired Output:
Name Count
Devonta Freeman 1
Devonta Freeman 2
Devonta Freeman 3
Devonta Freeman 4
Devonta Freeman 5
Devonta Freeman 6
Devonta Freeman 7
Devonta Freeman 8
Devonta Freeman 9
Devonta Freeman 10
Devonta Freeman 11
Devonta Freeman 12
Devonta Freeman 13
Devonta Freeman 14
Devonta Freeman 15
Antonio Brown 1
Antonio Brown 2
Antonio Brown 3
Antonio Brown 4
Antonio Brown 5
Antonio Brown 6
Antonio Brown 7
Antonio Brown 8
Antonio Brown 9
Antonio Brown 10
Antonio Brown 11
Antonio Brown 12
Antonio Brown 13
Antonio Brown 14
Antonio Brown 15
Antonio Brown 16
Antonio Brown 17
CodePudding user response:
You're looking for cumcount
.
df['Count'] = df.groupby('Name').cumcount()
Output:
>>> df
Name Count
0 Devonta Freeman 1
1 Devonta Freeman 2
2 Devonta Freeman 3
3 Devonta Freeman 4
4 Devonta Freeman 5
5 Devonta Freeman 6
6 Devonta Freeman 7
7 Devonta Freeman 8
8 Devonta Freeman 9
9 Devonta Freeman 10
10 Devonta Freeman 11
11 Devonta Freeman 12
12 Devonta Freeman 13
13 Devonta Freeman 14
14 Devonta Freeman 15
15 Antonio Brown 1
16 Antonio Brown 2
17 Antonio Brown 3
18 Antonio Brown 4
19 Antonio Brown 5
20 Antonio Brown 6
21 Antonio Brown 7
22 Antonio Brown 8
23 Antonio Brown 9
24 Antonio Brown 10
25 Antonio Brown 11
26 Antonio Brown 12
27 Antonio Brown 13
28 Antonio Brown 14
29 Antonio Brown 15
30 Antonio Brown 16
31 Antonio Brown 17