我想要其他列中的一列的和,但要基于其他列的条件



我在下面给出了一个数据帧

[![enter image description here][1]][1]
example for year 2016 'div' should only have sum of 'avg_coef' across only 2016 
and same for 2017 'div' should only have sum of 'avg_coef' across only 2017 and not any other value

我几乎已经通过应用lambda实现了这一点,但当应用它时,它只在循环中的最后一年起作用,并在循环中前进时将div中的其他值赋值为0,下面是生成的代码和输出

[![enter image description here][1]][1]
[![enter image description here][1]][1]

一些人认为,它只适用于去年,也就是2021年,还请建议你有一个更优化的方法来做这件事,谢谢大家

您可以使用.transform()

df['div'] = df.groupby('Year')['avg_coef'].transform(sum)

最新更新