遍历具有多个句柄的 Pandas DataFrame,并迭代追加已编辑的行?

Iterate through a Pandas DataFrame with multiple handles, and iteratively append edited rows?

我有 3 个数据框:

我想做类似的事情:

    for idx, W_nm, L_nm in df1[['index','winner_name','loser_name']].values:
      df3.loc[idx] = df2.loc[W_nm] - df2.loc[L_nm]
      #... edit this row further

失败是因为:

有没有办法引用第一行的索引?

我读过 iterrows().loc[] 慢 7 倍而且我有相当多的数据要处理

还有比这更干净的吗:

    for idx in df1.index:
      W_nm = df1.loc[idx,'winner_name']
      L_nm = df1.loc[idx,'loser_name']
      df3.loc[idx] = df2.loc[W_nm] - df2.loc[L_nm]
      #... edit this row further

这并没有解决 "no defined columns",但给了我我的句柄。

所以我期待的是:

 df1
[            'Loser'  'Winner'   'Score'
  0          Harry    Hermione   3-7   ...
  1          Harry    Ron        0-2   ...
  2          Ron      Voldemort  7-89   ... ]

 df2
[            'Spells' 'Allies'
  Harry      23       84      ...
  Hermione   94       68      ...
  Ron        14       63      ...
  Voldemort  97       92      ... ]

then

df3
[            'Spells' 'Allies'
  0          -71      16      ...
  1          9        21      ...
  2          -83      -29     ... ]

你需要的是join:

loser = df1.join(df2, on='Loser').loc[:,['Spells', 'Allies']]
winner = df1.join(df2, on='Winner').loc[:,['Spells', 'Allies']]
df3 = winner - loser

根据您的示例数据给出:

   Spells  Allies
0      71     -16
1      -9     -21
2      83      29