How can I calculate a group-wise percentage in pandas?
similar to Pandas: .groupby().size() and percentages or Pandas Very Simple Percent of total size from Group by I want to calculate the percentage of a value per group.
How can I achieve this?
My dataset is structured like
ClassLabel, Field
Initially, I aggregate on both ClassLbel
and Field
like
grouped = mydf.groupby(['Field', 'ClassLabel']).size().reset_index()
grouped = grouped.rename(columns={0: 'customersCountPerGroup'})
Now I would like to know the percentage of customers in each group on a per group basis. The groups total can be obtained like mydf.groupby(['Field']).size()
but I neither can merge that as a column nor am I sure this is the right approach - there must be something simpler.
edit
I want to calculate the percentage only based on a single group e.g. 3 0 0.125 1 0.250 the sum of 0 + 1 --> 0.125 + 0.250 = 0,375 and use this value to devide / normalize grouped and not grouped.sum()