[英]Pandas multiplying a dataframe column with groupby result
I have a dataframe:我有一个 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:我想要一个新的 col“Volume”,它将根据以下计算存储结果:
The average of the "Charge_volume" column based on grouping country and month multiplied by the user column基于分组国家和月份的“Charge_volume”列的平均值乘以用户列
The output should look like this: output 应如下所示:
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']
Try groupby().transform
:尝试groupby().transform
:
df['Volume'] = df['user'] * df.groupby(['month','country'])['Charge_volume'].transform('mean')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.