我在这个上面拔头发。
我有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)
但它不起作用。。。
提前非常感谢您的帮助
附加临时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