close

How to calculate count and percentage in groupby in Python

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to calculate count and percentage in groupby in Python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to calculate count and percentage in groupby in Python?

  1. How to calculate count and percentage in groupby in Python?

    I think you can use:
    P = Publisher.groupby('Category')['Title'].count().reset_index() P['Percentage'] = 100 * P['Title'] / P['Title'].sum()

  2. calculate count and percentage in groupby in Python

    I think you can use:
    P = Publisher.groupby('Category')['Title'].count().reset_index() P['Percentage'] = 100 * P['Title'] / P['Title'].sum()

Method 1

I think you can use:

P = Publisher.groupby('Category')['Title'].count().reset_index()
P['Percentage'] = 100 * P['Title']  / P['Title'].sum()

Sample:

Publisher = pd.DataFrame({'Category':['a','a','s'],
                   'Title':[4,5,6]})

print (Publisher)
  Category  Title
0        a      4
1        a      5
2        s      6

P = Publisher.groupby('Category')['Title'].count().reset_index()
P['Percentage'] = 100 * P['Title']  / P['Title'].sum()
print (P)
  Category  Title  Percentage
0        a      2   66.666667
1        s      1   33.333333

Method 2

df = pd.DataFrame({'Category':['a','a','s'],
                   'Title':[4,5,6]})

df=df.groupby('Category')['Title'].count().rename("percentage").transform(lambda x: x/x.sum())

df.reset_index()

#output in dataframe type

    Category    percentage
0   a   0.666667
1   s   0.333333

#please let me know if it doesn't solve your current problem

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read