Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Pandas Column Value Increment Counter for Unique Values

Say I have a series like (assume this is a dataframe with many columns, but I only care about df["Key"] right now) :

Key
----
1234
1234
1234
5678
6789
7890
7890
6789
2345

How do I create a new column called "Counter" that increments matching values in "Key" ?, like the following :

Key     Counter
----    -------
1234       1
1234       2
1234       3
5678       1
6789       1
7890       1
7890       2
6789       2
2345       1

I don’t want a summary of the total count of each unique value…I know that you can get a value of unique counts by doing something like df["Key"].value_counts() or df.groupby('Key').count()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use pd groupby cumcount:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html

which maps to 0-n, so optionally add 1 to the result:

out = df.groupby('Key').cumcount() + 1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading