查找行中所有 ID 的值,然后求和 python

find value for all ids in row and then sum python

我有 2 个 table 具有匹配的 ID。我想 return table 2 中的值与 table 1 中的每个列关联并创建 table 3。我知道如何在 excel 中使用vlookup。我也知道在尝试执行 vlookup 之类的操作时应该使用 join 或 merge。但是,我不知道如何在这里得到我想要的结果,因为我不能像 excel.

那样简单地将公式拖到另一个单元格

更新 如果我可以 return 所需的总和而不是 table 列和总和,那对我也会有帮助。所以 table 3 只是成绩总和。

我用假数据编了一个非常简单的例子。请在下面查看我想要的结果。

Table 1
         Student 1   Student 2  Student 3
    0   22882884    22882885    22882945
    1   22882884    22882885    22882935
    
Table 2    
        Student ID Grade
    0   22882884   4.0
    1   22882885   3.5
    2   22882945   2.75
    3   22882935   3.25
Table 3
        Student 1   Student 2  Student 3  Sum of Grades
    0   4.0           3.5       2.75      10.25  
    1   4.0           3.5       3.25      9.75

您可以 stackmapassign 总和:

out = (df1
 .stack()
 .map(df2.set_index('Student ID')['Grade'])
 .unstack()
 .assign(**{'Sum of Grades': lambda d: d.sum(axis=1)})
)

输出:

   Student 1  Student 2  Student 3  Sum of Grades
0        4.0        3.5       2.75          10.25
1        4.0        3.5       3.25          10.75

步骤不完整的替代方案:

s = df2.set_index('Student ID')['Grade']
out = df1.apply(lambda c: c.map(s))
out['Sum of Grades'] = out.sum(axis=1)

您可以使用 itertuples:

df3 = df1.replace(dict(df2.set_index('Student ID')['Grade'].itertuples()))
df3['Sum of Grades'] = df3.sum(1)
 
   student 1  student 2  student 3    Sum of Grades
0        4.0        3.5       2.75            10.25
1        4.0        3.5       3.25            10.75