3

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. Example

+351xxxxxxxxx
+1xxxxxxxxxx
+34xxxxxxxxx
+55xxxxxxxxxxx

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!

Jorge Gomes
  • 304
  • 2
  • 15

1 Answers1

2

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
NoobVB
  • 989
  • 6
  • 10
  • this works in general, and that's why I accepted the answer. However it returns a mix of countries and cities, which is weird I have to say – Jorge Gomes Sep 23 '22 at 13:12
  • 1
    my apologies, I have updated the code, `country_name_for_number` should be used instead of `.description_for_valid_number` – NoobVB Sep 23 '22 at 13:45