I have a dataframe after applying groupby
:
JavaScript
x
10
10
1
category | item
2
------------------
3
A | a_item1
4
| a_itme2
5
| a_item3
6
------------------
7
B | b_item1
8
| b_item2
9
------------------
10
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:
JavaScript
1
10
10
1
category | item | value
2
----------------------------
3
A | a_item1| 3.33
4
| a_itme2| 3.33
5
| a_item3| 3.33
6
----------------------------
7
B | b_item1| 5
8
| b_item2| 5
9
-----------------------------
10
How can this be done?
Advertisement
Answer
Use Series.value_counts
with Series.map
:
JavaScript
1
2
1
df['value'] = 10 / df['category'].map(df['category'].value_counts())
2
Or:
JavaScript
1
2
1
df['value'] = df['category'].map(df['category'].value_counts()).rdiv(10)
2