相当于R groupby mutate的Python pandas [英] Python pandas equivalent to R groupby mutate

查看:69
本文介绍了相当于R groupby mutate的Python pandas 的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此在R中,当我有一个由4列组成的数据帧时,将其称为df,并且我想通过一个组的总和来计算比率,我可以采用以下方式:

So in R when I have a data frame consisting of say 4 columns, call it df and I want to compute the ratio by sum product of a group, I can it in such a way:

// generate data
df = data.frame(a=c(1,1,0,1,0),b=c(1,0,0,1,0),c=c(10,5,1,5,10),d=c(3,1,2,1,2));
| a   b   c    d |
| 1   1   10   3 |
| 1   0   5    1 |
| 0   0   1    2 |
| 1   1   5    1 |
| 0   0   10   2 |
// compute sum product ratio
df = df%>% group_by(a,b) %>%
      mutate(
          ratio=c/sum(c*d)
      );
| a   b   c    d  ratio |
| 1   1   10   3  0.286 |
| 1   1   5    1  0.143 |
| 1   0   5    1  1     |
| 0   0   1    2  0.045 |
| 0   0   10   2  0.454 |

但是在python中,我需要求助于循环. 我知道应该有比python中的原始循环更优雅的方式,有人有任何想法吗?

But in python I need to resort to loops. I know there should be a more elegant way than raw loops in python, anyone got any ideas?

推荐答案

可以使用与groupby()apply()类似的语法来完成此操作:

It can be done with similar syntax with groupby() and apply():

df['ratio'] = df.groupby(['a','b'], group_keys=False).apply(lambda g: g.c/(g.c * g.d).sum())

这篇关于相当于R groupby mutate的Python pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆