Find the to-date count of a group-by and add it as a column [duplicate]

  aggregation, group-by, pandas, python

I have a dataframe that contains categories, users and events, I want to add a column that counts how many times that category has been seen by that user at the time of that event.
I have used group-by and agg but that gives me the total count, not the count at the time of the event.

df.groupby(['category', 'user_id']).agg(['count'])

So I have:

|user_id|category|event_type|
|1|A|23|
|1|B|45|
|1|C|67|
|1|A|18|
|2|A|25|
|1|C|32|

And I want

|user_id|category|event_type|count |
|1|A|23|1|
|1|B|45|1|
|1|C|67|1|
|1|A|18|2|
|2|A|25|1|
|1|C|32|2|

Source: Python Questions

LEAVE A COMMENT