Michael
Michael

Reputation: 351

Create a cumulative count column in pandas dataframe

I have a dataframe set up similar to this

**Person    Value**    
Joe        3
Jake       4
Patrick    2
Stacey     1
Joe        5
Stacey     6
Lara       7
Joe        2
Stacey     1

I need to create a new column 'x' which keeps a running count of how many times each person's name has appeared so far in the list.

Expected output:

**Person    Value**    **x**   
Joe        3             1     
Jake       4             1
Patrick    2             1
Stacey     1             1
Joe        5             2
Stacey     6             2
Lara       7             1
Joe        2             3
Stacey     1             3

All I've managed so far is to create an overall count, which is not what I'm looking for.

Any help is appreciated

Upvotes: 2

Views: 198

Answers (1)

fuglede
fuglede

Reputation: 18201

You could let

df['x'] = df.groupby('Person').cumcount() + 1

Upvotes: 2

Related Questions