Making a new column that is a ratio

Viewed 367

I have this dataframe:

mob.columns
Out[806]: Index([u'country', u'maxterm', u'quantity'], dtype='object')

Here is some data:

mob.head(5) 
Out[807]: 
      country maxterm  quantity
0      China    aled        44
1      China    fanx        77
2      China    grrx        12
3      China    hldo        13
4      China    jnmp        29

What is the simplest way to create a new column that is a ratio of the quantity listed on each row to the sum of all the quantities for each country? I was trying groupby and pivot and making a lambda function. This attempt

mob.groupby(['country', 'maxterm'])['quantity'].apply(lambda x: x / float(sum(x)) )

didn't work, it just outputted a bunch of 1's. It would be best if I can just make a new column in the original dataframe.

1 Answers
Related