使用Python Pandas结合phonenumbers库验证DataFrame中电话号码并获取归属国家
解决电话号码验证与归属国家查询的问题
嘿,我来帮你搞定这个问题!首先咱们先拆解一下你代码里的错误,然后一步步实现你需要的电话号码验证和归属国家查询功能。
你的代码错误原因
- axis参数位置错误:你把
axis='columns'写在了lambda函数的参数里,正确的位置应该是apply()方法的参数(即df.apply(lambda x: ..., axis=1),axis=1和axis='columns'是等价的)。 - phonenumbers库用法错误:
phonenumbers.is_valid_number()需要传入的是PhoneNumber对象,而不是直接传字符串+国家代码。你得先用phonenumbers.parse()把电话号码字符串和国家代码转换成PhoneNumber对象,才能进行后续的验证和地理编码。 - 不必要的嵌套调用:你重复调用了两次
phonenumbers.is_valid_number(),这是完全没必要的,还导致了语法错误。
正确的实现方案
咱们把逻辑封装成一个单独的处理函数,这样既可读性强,还能方便处理异常情况(比如格式完全错误的电话号码)。
步骤1:导入所需库
import pandas as pd import phonenumbers from phonenumbers import geocoder
步骤2:定义处理电话号码的函数
这个函数会处理每行数据,完成号码解析、有效性验证和归属国家查询:
def process_phone(row): # 把电话号码转成字符串,避免非字符串类型报错 phone_str = str(row['phoneNumber']) # 获取行中的国家代码(比如'NL'代表荷兰,'GB'代表英国) country_code = row['Country'] try: # 解析电话号码:传入号码字符串和国家代码,得到PhoneNumber对象 parsed_num = phonenumbers.parse(phone_str, country_code) # 验证号码有效性 is_valid = phonenumbers.is_valid_number(parsed_num) # 如果号码有效,获取归属国家名称;无效则返回空字符串 country_name = phonenumbers.geocoder.description_for_number(parsed_num, 'en') if is_valid else '' # 返回验证结果和国家名称 return pd.Series([is_valid, country_name]) except phonenumbers.NumberParseException: # 解析失败(比如号码格式完全错误),返回False和空字符串 return pd.Series([False, ''])
步骤3:应用函数到DataFrame
用apply()按行处理数据,把结果赋值给新的列:
# 假设你的原始DataFrame是df,包含contact、phoneNumber、Country列 df[['phoneCheck', 'phoneCountry']] = df.apply(process_phone, axis=1)
示例运行效果
咱们用你给出的示例数据测试一下:
# 示例数据 data = { 'contact': [1, 2, 3], 'phoneNumber': ['31650868016', '447986123456', '55677'], 'Country': ['NL', 'GB', ''] } df = pd.DataFrame(data) # 应用处理函数 df[['phoneCheck', 'phoneCountry']] = df.apply(process_phone, axis=1) # 查看结果 print(df[['contact', 'phoneNumber', 'phoneCheck', 'phoneCountry']])
输出结果会和你期望的格式一致:
contact phoneNumber phoneCheck phoneCountry 0 1 31650868016 True Netherlands 1 2 447986123456 True United Kingdom 2 3 55677 False
额外说明
- 如果你的
Country列存储的是国家名称(比如'Netherlands')而不是国家代码,需要先把它转换成ISO国家代码(比如'NL'),可以用第三方库比如pycountry来实现。 - 异常处理很重要,能避免因为个别无效号码导致整个程序崩溃,确保处理过程的稳定性。
内容的提问来源于stack exchange,提问作者Monkey D
相关产品推荐
相关产品推荐

