python - 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.
解决方案
嗯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}
推荐阅读
- javascript - ChartJS CustomTooltips 中的图像
- python - 如何在 CPython 源代码中找到 [::-1] (python 中的反转列表)的实现
- c# - 构建错误 -- Selenium -- 无法在声明中指定构造函数参数
- ios - 我的 webview 仅加载 https,但我想要 http 网站。那可能吗?
- jquery - '$ is undefined' 错误,但 'jQuery' 有效
- angular - Angular 2(v6)内联,如果其他?
- python - Scrapy 自定义设置
- php - 在一个 foreach 循环中合并 2 个单独的数据库查询或将查询合并为一个
- angular - Angular6按服务打开/显示组件
- r - Azure 上的 R 服务器