gpt4 book ai didi

Python Pandas : Select Multiple Cell Values of one column based on the Value of another Column

转载 作者:行者123 更新时间:2023-11-30 22:43:43 25 4
gpt4 key购买 nike

所以我的 Pandas 数据如下所示:

values    variables
134 1
12 2
43 1
54 3
16 2

只要 variables 的其余部分不等于 variables 中当前行的变量,我想创建一个新列,它是 values 的总和。例如,对于第一行,我想要对所有 values 行进行求和,其中 variables != 1。结果如下所示:

values    variables   result
134 1 82
12 2 231
43 1 82
54 3 205
16 2 231

我尝试过一些类似枚举的方法,但我似乎无法很好地处理这个问题。谢谢!

最佳答案

您可以等效地从不使用任何过滤器的总和中减去等于当前变量的所有值的总和,而不是求所有不等于当前变量的值的总和:

df['result'] = df['values'].sum()
df['result'] -= df.groupby('variables')['values'].transform('sum')

或者如果你想简洁的话可以用一行:

df['result'] = df['values'].sum() - df.groupby('variables')['values'].transform('sum')

结果输出:

   values  variables  result
0 134 1 82
1 12 2 231
2 43 1 82
3 54 3 205
4 16 2 231

关于Python Pandas : Select Multiple Cell Values of one column based on the Value of another Column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41683748/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com