添加一个列,该列根据它与其他两个列的匹配程度进行计算

Add a column that does a calculation based on how it matches two other columns

我想比较两列,然后根据比较结果计算加权平均值。

在这里,我们看到代码相同,ID 不同,但重复。我希望 Value_new 成为显示 Value 的加权倍数的列。例如,ID = 1 重复 4 次。因此,第一行的 Value_new 将是 0.5/(0.5+0.5+0.7+1) = 0.185

有:

Code    ID  Value
66099   1   0.3
55933   1   0.5
55933   2   0.4
55933   1   0.5
55933   1   0.7
55933   1   1
55933   2   2
55933   2   0.8
55933   3   3
55933   4   6
55933   5   7

想要(第一行 = 0.5/(0.5+0.5+0.7+1) = 0.185:

Code    ID  Value   Value_new
66099   1   0.3 0.3
55933   1   0.5 0.185185185
55933   2   0.4 0.125
55933   1   0.5 0.185185185
55933   1   0.7 0.259259259
55933   1   1   0.37037037
55933   2   2   0.625
55933   2   0.8 0.25
55933   3   3   1
55933   4   6   1.5
55933   5   7   1.4

我不确定您如何获取只有一个值的类别的值(例如,为什么第一行的 Value_new 设置为 0.3,为什么最后一行2 行 1.51.4?),但 IIUC 根据您对所需输出的描述,使用 transform:

df['Value_new'] = df.groupby(['Code','ID'])['Value'].transform(lambda x: x/x.sum())

>>> df
     Code  ID  Value  Value_new
0   66099   1    0.3   1.000000
1   55933   1    0.5   0.185185
2   55933   2    0.4   0.125000
3   55933   1    0.5   0.185185
4   55933   1    0.7   0.259259
5   55933   1    1.0   0.370370
6   55933   2    2.0   0.625000
7   55933   2    0.8   0.250000
8   55933   3    3.0   1.000000
9   55933   4    6.0   1.000000
10  55933   5    7.0   1.000000