8-Bit Borges
8-Bit Borges

Reputation: 10043

Pandas - map dictionary keys and values to new column

I have a df:

Int64Index: 3572 entries
Data columns (total 58 columns): 

with a column 'team':

 #   Column                        Non-Null Count  Dtype  
---  ------                        --------------  -----  
...
 13  team                         3572 non-null   object 
...

which has items below as unique values, repeated multiple times:

teams = [
    'Grêmio','Internacional', 'Palmeiras', 'Ceará', 
    'Bragantino', 'Corinthians', 'Botafogo', 'Fluminense', 
    'Flamengo', 'Athlético-PR','Coritiba': 'São Paulo',
    'Bahia', 'Sport', 'Fortaleza', 'Atlético-GO',
    'Goiás', 'Santos', 'Atlético-MG', 'Vasco']

Now, based on the dictionary below:

next_round = {
    'Grêmio':'Internacional', 'Palmeiras': 'Ceará', 
    'Bragantino': 'Corinthians', 'Botafogo': 'Fluminense', 
    'Flamengo': 'Athlético-PR','Coritiba': 'São Paulo',
    'Bahia': 'Sport', 'Fortaleza': 'Atlético-GO',
    'Goiás': 'Santos', 'Atlético-MG': 'Vasco'}

I would like to:

  1. create a new column df['home_dummy']
  2. assign the value 'home' to df['home_dummy'] if df['team'] row value is the dictionary key
  3. assign the value 'away' to df['home_dummy'] if df['team] row value is the dictionary value

as in key, value in next_round.items()

Example:

team            home_dummy /
...
Grêmio          home
Internacional   away
Palmeiras       home
Vasco           away
Coritiba        home
...

What is pandas way of doing this?

Upvotes: 0

Views: 303

Answers (1)

Equinox
Equinox

Reputation: 6758

import pandas as pd

df = pd.DataFrame([['Grêmio'],['Internacional'],['Palmeiras'],['Vasco'],['Coritiba']],columns = ['teams'])
next_round = {
    'Grêmio':'Internacional', 'Palmeiras': 'Ceará', 
    'Bragantino': 'Corinthians', 'Botafogo': 'Fluminense', 
    'Flamengo': 'Athlético-PR','Coritiba': 'São Paulo',
    'Bahia': 'Sport', 'Fortaleza': 'Atlético-GO',
    'Goiás': 'Santos', 'Atlético-MG': 'Vasco'}
df['home_dummy'] = ['home' if x in next_round.keys() else 'away' for x in df['teams'] ]
df

   teams    home_dummy
0   Grêmio  home
1   Internacional   away
2   Palmeiras   home
3   Vasco   away
4   Coritiba    home

Upvotes: 2

Related Questions