You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas中按类型拆分手机号并复制行?

问题:拆分多手机号列并规整为单行单手机号格式

需求说明:将包含主手机号和多值其他手机号的DataFrame处理为单行仅存一个手机号的格式,同时新增phone_type列标记手机号类型(主手机号标记为work,其他手机号标记为other)。

原始DataFrame

namephoneother_phone
alice(111) 111-1111(222) 222-2222, (333) 333-3333
bob(444) 444-4444(555) 555-5555, (666) 666-6666
colin(777) 777-7777(888) 888-8888
david(999) 999-9999NaN

期望输出

namephonephone_type
alice(111) 111-1111work
alice(222) 222-2222other
alice(333) 333-3333other
bob(444) 444-4444work
bob(555) 555-5555other
bob(666) 666-6666other
colin(777) 777-7777work
colin(888) 888-8888other
david(999) 999-9999work

解决方法(Pandas实现)

通过以下步骤完成数据规整:

import pandas as pd

# 构造原始DataFrame(如果已有数据可跳过此步)
data = {
    'name': ['alice', 'bob', 'colin', 'david'],
    'phone': ['(111) 111-1111', '(444) 444-4444', '(777) 777-7777', '(999) 999-9999'],
    'other_phone': ['(222) 222-2222, (333) 333-3333', '(555) 555-5555, (666) 666-6666', '(888) 888-8888', pd.NA]
}
df = pd.DataFrame(data)

# 1. 拆分other_phone为列表,空值转为空列表
df['other_phone'] = df['other_phone'].str.split(', ').fillna(pd.Series([[]], index=df.index))

# 2. 拆分other_phone的多行,标记为other类型
other_df = df.explode('other_phone').dropna(subset=['other_phone'])
other_df = other_df.rename(columns={'other_phone': 'phone'})
other_df['phone_type'] = 'other'

# 3. 处理主手机号行,标记为work类型
work_df = df[['name', 'phone']].copy()
work_df['phone_type'] = 'work'

# 4. 合并结果并排序
final_df = pd.concat([work_df, other_df], ignore_index=True)
final_df = final_df.sort_values('name').reset_index(drop=True)

print(final_df)

关键步骤说明

  • str.split(', '):按逗号加空格拆分多手机号,转为列表格式
  • fillna(pd.Series([[]], index=df.index)):将NaN值替换为空列表,避免拆分时丢失行
  • explode('other_phone'):把列表中的每个手机号拆分为单独一行
  • 分别构造主、副手机号的DataFrame后合并,保证类型标记准确

内容的提问来源于stack exchange,提问作者KLG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 11:34:58