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

如何在Pandas DataFrame某列的数字与字符间添加空格

解决Pandas DataFrame指定列字母与数字间添加空格的问题

可以通过正则表达式配合Pandas的字符串替换方法实现需求,核心思路是精准匹配字母与数字的分界位置,然后插入空格。

具体实现代码

import pandas as pd

data = {'first_column':  ['first_value', 'second_value', 'third_value'],
        'second_column': ['first_value', 'second_value', 'third_value'],
         'third_column':['AA6589', 'GG6589', 'BXV6589'],
        'fourth_column':['first_value', 'second_value', 'third_value'],
        }

df = pd.DataFrame(data)

# 对third_column做处理:在字母和数字的分界处插入空格
df['third_column'] = df['third_column'].str.replace(r'([A-Za-z])(\d)', r'\1 \2', regex=True)

print(df)

代码说明

  • str.replace(r'([A-Za-z])(\d)', r'\1 \2', regex=True):
    • 正则([A-Za-z])(\d)会捕获任意单个字母,以及紧随其后的单个数字,用括号将两者分成独立分组;
    • 替换规则r'\1 \2'是把第一个分组(字母)、空格、第二个分组(数字)拼接,从而完成分隔。

执行后third_column的内容会变为:['AA 6589', 'GG 6589', 'BXV 6589'],其余列保持原样。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 04:26:03