How to calculate count and percentage in groupby in Python
<p>I have following output after grouping by</p>

<pre><code>Publisher.groupby('Category')['Title'].count()
Category
Coding          5
Hacking         7
Java            1
JavaScript      5
LEGO           43
Linux           7
Networking      5
Others        123
Python          8
R               2
Ruby            4
Scripting       4 
Statistics      2
Web             3
</code></pre>

<p>In the above output I want the percentage also i.e for the first row <code>5*100/219</code> and so on. I am doing following</p>

<pre><code> Publisher.groupby('Category')['Title'].agg({'Count':'count','Percentage':lambda x:x/x.sum()})
</code></pre>

<p>But it gives me an error. Please help</p>

<p>I think you can use:</p>

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

<p>Sample:</p>

<pre><code>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
</code></pre>

python pandas group-by