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
JavaScript
x
5
1
+351xxxxxxxxx
2
+1xxxxxxxxxx
3
+34xxxxxxxxx
4
+55xxxxxxxxxxx
5
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!
Advertisement
Answer
Not sure if it is the best way, but I was not able to find the way without looping…
JavaScript
1
17
17
1
import pandas as pd
2
import phonenumbers
3
from phonenumbers import geocoder, carrier
4
5
6
df = pd.DataFrame(['+41431234567', '+447399512658'], columns=['Number'])
7
8
ph_numbers = df['Number'].values # creating list of numbers
9
10
country_list = [] # empty list for countries
11
for item in ph_numbers:
12
numb = phonenumbers.parse(item, 'en') # creating phonenumber object
13
print(geocoder.description_for_number(numb, 'en'))
14
country_list.append(geocoder.country_name_for_number(numb, 'en')) #passing phonenumber object to geocoder and appending to list
15
16
df['Country'] = country_list
17