我在這個上拉我的頭發。
我有 2 個資料框:
df1 保存球員的資料,包括他們的位置(區域)(前鋒、中場或后衛)和他們的一些
游戲統計。
df1 = pd.DataFrame({'Zone': ['DEF', 'MID', 'FWD'], 'Tackles': [5, 10, 5], 'Goals': [0, 1, 1], 'Shots': [10, 5, 2]} , index=(['Player A', 'Player B', 'Player C']))
Zone Tackles Goals Shots
Player A DEF 5 0 10
Player B MID 10 1 5
Player C FWD 5 1 2
df2 包含我要應用的權重,以計算每個玩家的表現指數。重量取決于球員的位置
df2 = pd.DataFrame({'Tackles': [1, 2, 4], 'Goals': [10, 5, 2], 'Shots': [3, 3, 1]}, index=(['FWD', 'MID', 'DEF']))
Tackles Goals Shots
FWD 1 10 3
MID 2 5 3
DEF 4 2 1
我想將 df1 中的每一行乘以 df2 中的對應行
這就是我想要得到的:
Zone Tackles Goals Shots Index
Player A DEF 5 0 10 30.0 (5*4 0*2 10*1)
Player B MID 10 1 5 40.0 (10*2 1*5 5*3)
Player C FWD 5 1 2 21.0 (5*1 1*10 2*3)
我試過的是這樣的:
df1['Index'] = (df1 * df2.loc[df1['Zone']]).sum(axis=1)
但它不起作用...
非常感謝您的幫助
uj5u.com熱心網友回復:
附加臨時Zone作為索引df1:
df1['Index'] = df1.set_index('Zone', append=True).mul(df2, level=1).sum(axis=1).values
print(df1)
# Output
Zone Tackles Goals Shots Index
Player A DEF 5 0 10 30
Player B MID 10 1 5 40
Player C FWD 5 1 2 21
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/408953.html
標籤:
