基于国际手机号填充DataFrame的country列
基于国际手机号生成国家列的实现方案
一、使用phonenumbers库的最佳实现方式
phonenumbers是Google开发的专业国际手机号处理库,能准确解析、验证号码并获取归属地信息,是处理这类需求的首选方案。
步骤与代码示例
- 先安装库:
pip install phonenumbers
- 编写解析函数并应用到DataFrame:
import phonenumbers from phonenumbers import geocoder import pandas as pd # 示例DataFrame df = pd.DataFrame({ 'phone': ['+351912345678', '+12125551234', '+34600123456', '+5511987654321'] }) def get_phone_country(phone_number): try: # 解析手机号(无需指定默认国家,因为号码带+国家代码) parsed_num = phonenumbers.parse(phone_number, None) # 可选:验证号码格式有效性 if phonenumbers.is_valid_number(parsed_num): # 获取国家名称,可指定语言(如'zh'返回中文,'en'返回英文) return geocoder.description_for_number(parsed_num, 'en') return None except phonenumbers.NumberParseException: # 处理无法解析的无效号码 return None # 生成country列 df['country'] = df['phone'].apply(get_phone_country)
优势
- 自动识别所有合规的国际号码格式,无需手动维护国家代码映射
- 支持号码有效性验证,过滤无效数据
- 可返回多语言的国家名称,适配不同需求
二、其他可行方法
1. 手动国家代码映射
如果你的业务只涉及有限几个国家,可直接创建国家代码与国家名称的映射字典,通过字符串匹配提取归属地:
# 自定义国家代码映射(按需扩展) country_code_mapping = { '+351': 'Portugal', '+1': 'United States', '+34': 'Spain', '+55': 'Brazil' } def get_country_manual(phone_number): for code, country in country_code_mapping.items(): if phone_number.startswith(code): return country return None df['country_manual'] = df['phone'].apply(get_country_manual)
缺点:需手动维护映射字典,无法覆盖所有国家,也无法验证号码有效性。
2. 正则提取国家代码+映射
用正则表达式提取号码开头的国家代码部分,再结合映射字典匹配国家:
import re def extract_country_code(phone_number): # 匹配开头的+和1-3位数字(国际国家代码长度通常为1-3位) match = re.match(r'^(\+\d{1,3})', phone_number) return match.group(1) if match else None df['country_code'] = df['phone'].apply(extract_country_code) df['country_regex'] = df['country_code'].map(country_code_mapping)
特点:比纯字符串匹配更灵活,但仍依赖手动维护的映射字典,适合已知国家范围的场景。
内容的提问来源于stack exchange,提问作者Jorge Gomes
相关产品推荐
相关产品推荐

