Skip to content
Advertisement

How can I add a counter column that counts specific values in another column in a pandas dataframe?

I have a large dataframe (>16M rows) which has a column named ‘user’. Every user have more than one occurrences. I want to add a new column ‘counter’ that increases every time a specific user has a new record.

The dataframe looks like this:

JavaScript

I want it to look like this with the new counter column

JavaScript

I tried the following line of code, but it’s taking ages:

JavaScript

Advertisement

Answer

Please checkout pandas cumcount

JavaScript

should do the trick

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement