I have a dataframe after applying groupby:
category | item
------------------
A        | a_item1
         | a_itme2
         | a_item3
------------------
B        | b_item1
         | b_item2
------------------
On this, I want to add a new column with the calculation: 10 / (no of items per category).
For the example data, this would be:
category | item   |  value
----------------------------
A        | a_item1|   3.33
         | a_itme2|   3.33
         | a_item3|   3.33
----------------------------
B        | b_item1|   5
         | b_item2|   5
-----------------------------
How can this be done?
Advertisement
Answer
Use Series.value_counts with Series.map:
df['value'] = 10 / df['category'].map(df['category'].value_counts())
Or:
df['value'] = df['category'].map(df['category'].value_counts()).rdiv(10)