Populating Country column from international phone numbers


I have a dataframe with several data including the column phone.
I would like to create a column name country, based on the phone numbers.
The phone numbers are in the format +country_code_phonenumber, i.e.,for several countries.


What is the best way to do this with the library phonenumbers? Or is there another way to do it that I’m missing?

Thank you in advance!

Asked By: Jorge Gomes



Not sure if it is the best way, but I was not able to find the way without looping…

import pandas as pd
import phonenumbers
from phonenumbers import geocoder, carrier

df = pd.DataFrame(['+41431234567', '+447399512658'], columns=['Number'])

ph_numbers = df['Number'].values # creating list of numbers

country_list = []  # empty list for countries
for item in ph_numbers:
    numb = phonenumbers.parse(item, 'en') # creating phonenumber object
    print(geocoder.description_for_number(numb, 'en'))
    country_list.append(geocoder.country_name_for_number(numb, 'en')) #passing phonenumber object to geocoder and appending to list

df['Country'] = country_list
Answered By: NoobVB