Ishan
Ishan

Reputation: 43

Calculating the frequency of each row in Pandas DataFrame

Suppose I have given datasets:

Sr.No|Query
-----
 1.   a
 2.   a
 3.   b
 4.   b
 5.   a

I want the following result :

Sr.No | Query | Frequency
1.    a         3
2.    a         3
3.    b         2
4.    b         2
5.    a         3

Please note that the duplicates should not be removed.

Upvotes: 4

Views: 1319

Answers (1)

jezrael
jezrael

Reputation: 863741

You can use transform with size:

df['Frequency']= df.groupby('Query')['Query'].transform('size')
print (df)
   Sr.No Query  Frequency
0    1.0     a          3
1    2.0     a          3
2    3.0     b          2
3    4.0     b          2
4    5.0     a          3

Upvotes: 1

Related Questions