如何在Pandas中按类型拆分手机号并复制行?
问题:拆分多手机号列并规整为单行单手机号格式
需求说明:将包含主手机号和多值其他手机号的DataFrame处理为单行仅存一个手机号的格式,同时新增phone_type列标记手机号类型(主手机号标记为work,其他手机号标记为other)。
原始DataFrame
| name | phone | other_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-9999 | NaN |
期望输出
| name | phone | phone_type |
|---|---|---|
| alice | (111) 111-1111 | work |
| alice | (222) 222-2222 | other |
| alice | (333) 333-3333 | other |
| bob | (444) 444-4444 | work |
| bob | (555) 555-5555 | other |
| bob | (666) 666-6666 | other |
| colin | (777) 777-7777 | work |
| colin | (888) 888-8888 | other |
| david | (999) 999-9999 | work |
解决方法(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
相关产品推荐
相关产品推荐

