Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get normalised value counts weighted by another column?

Tags:

python

pandas

I have a dataframe like this in Pandas:

df = pd.DataFrame({
  'org': ['A1', 'B1', 'A1', 'B2'], 
  'DIH': [True, False, True, False], 
  'Quantity': [10,20,10,20], 
  'Items': [1, 2, 3, 4]
})

Now I want to get the value counts and modal value of Quantity, but weighted by the number of Items.

So I know that I can do

df.groupby('Quantity').agg({'Items': 'sum'}).sort_values('Items', ascending=False)

And get this:

Quantity    Items
20          6
10          4

But how do I get this as a percentage value, like this?

Quantity    Items
20          60
10          40
like image 567
Richard Avatar asked May 11 '26 11:05

Richard


1 Answers

This worked for me

df.groupby('Quantity').agg({'Items': 'sum'}).sort_values('Items', ascending=False)/df['Items'].sum()*100
like image 167
SO44 Avatar answered May 13 '26 00:05

SO44