-2

I have this 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

And this dict:

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}

Now I'm trying to bring team names into my df. I'm trying:

    df['opponent_name'] = df['opponent'].map(lambda x: teams_dict[x])

But I'm getting:

KeyError: 262

What am I missing?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
8-Bit Borges
  • 9,643
  • 29
  • 101
  • 198
  • 4
    ``df['opponent'].map({v: k for k,v in teams.items()})``, swap key & value in ``teams_dict`` – sushanth Aug 29 '20 at 18:09
  • 3
    Does this answer your question? [Reverse / invert a dictionary mapping](https://stackoverflow.com/questions/483666/reverse-invert-a-dictionary-mapping) – MisterMiyagi Aug 29 '20 at 18:50

1 Answers1

0

As sushanth already commented, you need to swap teams_dict to have value: key pairs instead.

Then you should prefer the built-in .replace over .map

df['opponent_name'] = df.opponent.replace(
    {v: k for k, v in teams_dict.items()})
RichieV
  • 5,103
  • 2
  • 11
  • 24