Django0602
Django0602

Reputation: 807

Pandas multiplying a dataframe column with groupby result

I have a dataframe:

cust_sign_month      month         user      country      Charge_volume
2018-01              2018-01        10        DE           100 
2018-01              2018-01        22        DE           200              
2018-01              2018-02        33        IN           100              
2019-01              2019-02        42        IN           200             

I want a new col "Volume" that will store the result based on the following calculation:

The average of the "Charge_volume" column based on grouping country and month multiplied by the user column

The output should look like this:

cust_sign_month      month         user      country      Charge_volume    Volume
2018-01              2018-01        10        DE           100             1500
2018-01              2018-01        22        DE           200             3300 
2018-01              2018-02        33        IN           100             4950 
2019-01              2019-02        42        IN           200             8400

I have tried the following code but it doesn't seem to work:

df['Volume'] = df.groupby(['month','country'])['Charge_volume'].mean()*df['user']

Upvotes: 0

Views: 26

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150785

Try groupby().transform:

df['Volume'] = df['user'] * df.groupby(['month','country'])['Charge_volume'].transform('mean')

Upvotes: 1

Related Questions