DataFrame中手机号格式标准化:国家码校验与统一格式处理
Pandas 电话号码格式化解决方案
需要处理DataFrame中的联系号码,统一格式为(+国家码)纯数字,规则如下:
- 无国家码的号码默认添加
+1 - 空值/NA保持不变
- 已符合格式的号码无需修改
原始数据
id contact 1 +1(123)-456-7890 2 +552(123)-(456)-(7890) 3 (+91)1234567890 // correct 4 123-456-7890 // by default add +1, if there is no code 5 // Ignore NA cases 6 +11234567890 // separate country code from given number and formate it
实现代码
import pandas as pd import re # 构造原始DataFrame data = { 'id': [1, 2, 3, 4, 5, 6], 'contact': [ '+1(123)-456-7890', '+552(123)-(456)-(7890)', '(+91)1234567890', '123-456-7890', '', '+11234567890' ] } df1 = pd.DataFrame(data) def format_contact(contact): # 处理空值/空白字符串 if pd.isna(contact) or contact.strip() == '': return contact # 提取所有数字字符 all_digits = re.sub(r'\D', '', contact) # 判断原号码是否包含国家码前缀(+号) has_country_code = '+' in contact # 提取号码核心部分(最后10位数字) number_core = all_digits[-10:] if len(all_digits) >= 10 else all_digits # 确定国家码 if has_country_code: # 国家码是+号对应的数字(排除最后10位号码) country_code = all_digits[:-10] if len(all_digits) > 10 else '1' else: # 无国家码默认用1 country_code = '1' # 拼接成目标格式 return f'(+{country_code}){number_core}' # 应用格式化函数 df1['contact'] = df1['contact'].apply(format_contact) print(df1)
处理结果
id contact 1 (+1)1234567890 2 (+552)1234567890 3 (+91)1234567890 4 (+1)1234567890 5 6 (+1)1234567890
内容的提问来源于stack exchange,提问作者parth hirpara
相关产品推荐
相关产品推荐

