Search code examples
pythonpandascountry-codespycountry-convert

How do I convert an IOC country code to country name?


I have a pandas dataframe

import pandas as pd

s = pd.DataFrame({'ioc' : ['ESP', 'CYP', 'USA', 'ESP', 'NED']})

and I want to return

out = pd.DataFrame(
    {'ioc' : ['ESP', 'CYP', 'USA', 'ESP', 'NED'],
     'countryName' : ['Spain', 'Cyprus', 'United States of America',
                      'Spain', 'Netherlands']})

Solution

  • Use List of IOC country codes

    ioc = pd.read_html('https://en.wikipedia.org/wiki/List_of_IOC_country_codes')[0]
    ioc = ioc.assign(Code=ioc['Code'].str[-3:]).set_index('Code')['National Olympic Committee']
    
    s['countryName'] = s['ioc'].map(ioc)
    print(s)
    
    # Output:
       ioc    countryName
    0  ESP          Spain
    1  CYP         Cyprus
    2  USA  United States
    3  ESP          Spain
    4  NED    Netherlands