Python Pandas: Select 一列的多个单元格值基于另一列的值

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

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

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

我想创建一个新列,它是 values 的总和,只要 variables 的其余部分不等于 variables 中当前行的变量。例如,对于第一行,我想对 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