我有 2 個帶有匹配 ID 的表。我想回傳與表 1 中的每個列關聯的表 2 中的值并創建表 3。我知道如何使用 vlookup 在 excel 中執行此操作。我也知道在嘗試執行 vlookup 之類的操作時應該使用 join 或 merge。但是,我不知道如何在這里得到我想要的結果,因為我不能像在 excel 中那樣簡單地將公式拖到另一個單元格中。
如果我可以只回傳所需的總和而不是表列和總和,更新 它也會對我有所幫助。所以表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
uj5u.com熱心網友回復:
您可以stack,map和assign總和:
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)
uj5u.com熱心網友回復:
你可以使用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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/483170.html
上一篇:如何在嵌入訊息中也包含正常內容?
