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

NumPy way -

tags, C = np.unique(df.IP_address, return_counts=1, return_inverse=1)[1:]
df['IP_address_Count'] = C[tags]

Sample output -

In [275]: df
Out[275]: 
   IP_address  IP_address_Count
0         IP1                 3
1         IP1                 3
2         IP1                 3
3         IP4                 5
4         IP4                 5
5         IP4                 5
6         IP4                 5
7         IP4                 5
8         IP7                 3
9         IP7                 3
10        IP7                 3

You can use value_counts() with map

df['count'] = df['IP_address'].map(df['IP_address'].value_counts())


    IP_address  count
0   IP1         3
1   IP1         3
2   IP1         3
3   IP4         5
4   IP4         5
5   IP4         5
6   IP4         5
7   IP4         5
8   IP7         3
9   IP7         3
10  IP7         3

Using pd.factorize
This should be a very fast solution that scales well for large data

f, u = pd.factorize(df.IP_address.values)
df.assign(IP_address_Count=np.bincount(f)[f])

   IP_address  IP_address_Count
0         IP1                 3
1         IP1                 3
2         IP1                 3
3         IP4                 5
4         IP4                 5
5         IP4                 5
6         IP4                 5
7         IP4                 5
8         IP7                 3
9         IP7                 3
10        IP7                 3

Tags:

Python

Pandas