python - 将值从字典映射到数据框
问题描述
我有这个df
:
opponent pontos_num
0 262 29.1
1 265 28.8
2 284 21.4
3 282 16.3
4 266 14.8
5 292 12.4
6 373 9.6
7 354 6.8
8 277 6.3
9 294 5.5
10 276 3.9
11 356 3.5
12 280 3.3
13 263 0.9
14 293 0.2
15 264 0.2
16 285 -1.6
17 290 -5.3
18 267 -6.2
19 275 -6.5
这个字典:
teams_dict = {'team1':262, 'team2': 263, 'team3': 264, 'team4':265, 'team5':266,
'team6':267, 'team7':275, 'team8': 276, 'team9': 277, 'team10': 280, 'team11': 282,
'team12':284, 'team13':285, 'team14':290, 'team15':292, 'team16':293, 'team17':294,
'team18':354, 'team19':356, 'team20':373}
现在我正在尝试将团队名称带入我的df
. 我正在努力:
df['opponent_name'] = df['opponent'].map(lambda x: teams_dict[x])
但我得到:
KeyError: 262
我错过了什么?
解决方案
teams_dict
正如 sushanth已经评论的那样,您需要交换value: key
成对。
那么你应该更喜欢内置.replace
的.map
df['opponent_name'] = df.opponent.replace(
{v: k for k, v in teams_dict.items()})
推荐阅读
- redux - 使用 createSlice reduxtoolkit 进行重构
- google-apps-script - 如何通过脚本检索 Google 表格的最后一行(无论是否为空)?
- python - PyTorch 1D CNN 问题
- azure - JobManagerTask 的 Azure Batch 和用例
- flutter - Flutter 页面来得太慢了。当它包含长数据时
- python - python只读取pdf表格的几行
- kubernetes-helm - 如何从 Kubernetes 中卸载 Tiller?
- reactjs - 在使用 RTKQ 查询的组件中对单击事件调用 updateCachedData 的正确方法是什么?
- node.js - 删除文档和执行 post 中间件时,无法将标头发送到客户端错误
- php - 使用php一次发送和接收多个值的语言翻译