tgood
tgood

Reputation: 129

Assign progressive count of values in dataframe in Python

I have a data frame like this:

IP_address
   IP1
   IP1
   IP1
   IP4
   IP4
   IP4
   IP4
   IP4
   IP7
   IP7
   IP7

I would like to take count of unique values in this column and note the progressive count as a field by itself. At the end, it should look like this:

IP_address  IP_address_Count
   IP1               1
   IP1               2
   IP1               3
   IP4               1
   IP4               2
   IP4               3
   IP4               4
   IP4               5
   IP7               1
   IP7               2
   IP7               3

There is also the possibility that the IP_addresses would not be grouped. It could appear as:

IP_address
    IP1
    IP1
    IP4
    IP4
    IP1
    IP4
    IP7
    IP4
    IP7
    IP4
    IP7

In that case, I would want:

IP_address  IP_address_Count
   IP1               1
   IP1               2
   IP4               1
   IP4               2
   IP1               3
   IP4               3
   IP7               1
   IP4               4
   IP7               2
   IP4               5
   IP7               3

How to assign count of unique values to the records in a data frame in python

I originally started with the above code but then wanted to develop on and have been unsuccessful as of yet.

Upvotes: 1

Views: 344

Answers (1)

Itamar Mushkin
Itamar Mushkin

Reputation: 2905

You can simply group by the relevant field and then do a cumulative count (gave desired result on my end):

df['IP_address_count'] = df.groupby('IP_address').cumcount()+1

Upvotes: 2

Related Questions