Srijan Sharma
Srijan Sharma

Reputation: 693

divide values of column based on some other column

I have a pandas data frame as can be seen below:

index     ID           Val

 1    BBID_2041         1
 2    BBID_2041         1
 3    BBID_2041         3
 4    BBID_2041         1 
 5    BBID_2041         2
 6    BBID_2041         1
 7    BBID_2041         1
 8    BBID_20410        1
 9    BBID_20410        1
 10   BBID_20410        5
 11   BBID_20410        1

Now I want to divide every value present in column Val by the total number of IDs present in that group. For e.g i want to divide the values from index 1 to 7 by 7 as there are total 7 rows for ID BBID_2041 and so on. I can use a loop for that but what could be a fast way to do that.

Upvotes: 0

Views: 300

Answers (1)

BENY
BENY

Reputation: 323306

By using transform

df['New']=df.groupby('ID').Val.transform(lambda x : x/len(x))
df
Out[814]: 
    index          ID  Val       New
0       1   BBID_2041    1  0.142857
1       2   BBID_2041    1  0.142857
2       3   BBID_2041    3  0.428571
3       4   BBID_2041    1  0.142857
4       5   BBID_2041    2  0.285714
5       6   BBID_2041    1  0.142857
6       7   BBID_2041    1  0.142857
7       8  BBID_20410    1  0.250000
8       9  BBID_20410    1  0.250000
9      10  BBID_20410    5  1.250000
10     11  BBID_20410    1  0.250000

Upvotes: 2

Related Questions