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

如何在DataFrame中将字符串按每10个字符拆分生成字符列表?

拆分DataFrame中contact_num列的数字字符串

需求说明

对DataFrame的contact_num列执行以下处理:

  • 纯数字字符串按每10个字符拆分,转为字符串列表
  • 非数值内容(如not available)保持原样

原始DataFrame

contact_num
01111784885788634878
247782788869775178889785427889
not available
2478544756

期望输出DataFrame

contact_num
['0111178488', '5788634878']
['2477827888', '6977517888', '9785427889']
not available
['2478544756']

解决方案(Pandas实现)

通过自定义函数结合apply方法实现需求:

import pandas as pd

# 构建示例DataFrame
df = pd.DataFrame({
    'contact_num': [
        '01111784885788634878',
        '247782788869775178889785427889',
        'not available',
        '2478544756'
    ]
})

# 定义处理函数
def split_contact(s):
    # 判断是否为纯数字字符串
    if s.isdigit():
        # 按每10个字符拆分
        return [s[i:i+10] for i in range(0, len(s), 10)]
    # 非数字内容直接返回原字符串
    return s

# 应用函数到目标列
df['contact_num'] = df['contact_num'].apply(split_contact)

# 查看结果
print(df)

代码说明

  • s.isdigit():快速判断字符串是否由纯数字组成,筛选出需要拆分的条目
  • 列表推导式:通过步长为10的循环,从字符串起始位置开始,每次截取10个字符,生成拆分后的列表
  • 非数字字符串直接返回原内容,确保特殊值不受影响

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 13:50:39