简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM