首页 > 解决方案 > Fill dictonary values as the sum of values from a pandas dataframe

问题描述

I have a dictionary that contains the names of various players with all values set to None like so...

players = {'A': None,
           'B': None,
           'C': None,
           'D': None,
           'E': None}

A pandas data frame (df_1) that contains the keys, i.e. player names

   col_0  col_1  col_2
   -----  -----  -----
0    A       B      C
1    A       E      D
2    C       B      A

and a dataframe (df_2) that contains their scores in corresponding matches

    score_0  score_1  score_2
     -----    -----    -----
0      1       10        2
1      6       15        7
2      8       1         9

Hence, total score of A is..

      1       +      6        +      9         =  16
(0, score_0)  + (1, score_0)  + (2, score_2)

and I would like to map all the players(A, B, C..) to their total score in the dictionary of players that I had created earlier.

Here's some code that I wrote...

for player in players:
  players[player] = df_2.loc[df_1['col_0'] == player, 'score_0'].sum()
  players[player] += df_2.loc[df_1['col_1'] == player, 'score_1'].sum()
  players[player] += df_2.loc[df_1['col_2'] == player, 'score_2'].sum()
print(players)

This produces the desired result, but I am wondering if a faster, more pandas like way is available. Any help would be appreciated.

标签: pythonpandas

解决方案


pandas stack,通常我们可以groupby在展平df之后

s=df2.stack().groupby(df1.stack().values).sum()
s
A    16
B    11
C    10
D     7
E    15
dtype: int64
s.to_dict()
{'A': 16, 'B': 11, 'C': 10, 'D': 7, 'E': 15}

推荐阅读