【问题标题】:Multiply 1 Dataframe by a row in another one selected based on its index value将 1 Dataframe 乘以根据其索引值选择的另一行中的一行
【发布时间】:2022-01-10 16:20:57
【问题描述】:

我在这上面拉头发。

我有 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)

但它不起作用......

非常感谢您的帮助

【问题讨论】:

    标签: python pandas dataframe indexing .loc


    【解决方案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
    

    【讨论】:

    • @viannedubs。我更新了我的答案。现在我觉得是对的。请检查一下。
    • 有效!!谢谢。
    猜你喜欢
    • 1970-01-01
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-14
    • 2016-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多