Python · country lookup (ISO3 ↔ name)
Quick mapping between ISO codes and country names.
1import pandas as pd2import pycountry3import re45# ----- dummy input -----6df = pd.DataFrame({"ISO3": ["HKG", "GBR", "CHE", "ETH"]})78# ----- helper class -----9class CountryCodeConverter:10 def __init__(self):11 self.alpha3_to_num = {}12 self.num_to_alpha3 = {}13 for c in pycountry.countries:14 if hasattr(c, "alpha_3") and hasattr(c, "numeric"):15 iso3 = c.alpha_316 num = c.numeric.zfill(3)17 self.alpha3_to_num[iso3] = num18 self.num_to_alpha3[num] = iso31920 def to_un_numeric(self, iso3):21 return self.alpha3_to_num.get(str(iso3).upper())2223cc = CountryCodeConverter()2425# ----- Generate complimentary identifiers -----26df["ISO2"] = df["ISO3"].apply(27 lambda x: pycountry.countries.get(alpha_3=x).alpha_228 if pycountry.countries.get(alpha_3=x) else None29)30df["UN_numeric"] = df["ISO3"].apply(cc.to_un_numeric)31df["country"] = df["ISO3"].apply(32 lambda x: pycountry.countries.get(alpha_3=x).name33 if pycountry.countries.get(alpha_3=x) else None34)