You need to enable JavaScript to run this app. Pandas列坐标字符串偶数次空格替换为逗号的实现方法
优惠活动
大模型
产品
解决方案
定价
更多

Pandas列坐标字符串偶数次空格替换为逗号的实现方法

解决方案

方案1:调整现有自定义函数

你提供的函数仅需要修改一处查找位置的参数即可满足需求,调整后的函数和调用方式如下:

def nth_repl_all(s, sub, repl, nth):
    find = s.find(sub)
    i = 1
    while find != -1:
        if i == nth:
            s = s[:find]+repl+s[find + len(sub):]
            i = 0
        # 去掉原代码多余的+1,避免跳过连续匹配的空格
        find = s.find(sub, find + len(sub))
        i += 1
    return s

# 调用示例:替换所有第2次出现的空格为`, `
df['col3'] = df['col3'].apply(lambda x: nth_repl_all(x, ' ', ', ', 2))

核心逻辑:你需要替换每第2个空格为, ,刚好匹配原函数每n次替换的逻辑,仅需要修正原函数查找下一个位置时多+1的错误,避免漏匹配空格。

方案2:更简洁的实现(推荐)

无需自定义复杂的字符串遍历逻辑,用Pandas自带的字符串处理或简单列表推导即可实现,可读性和性能更好。

方式A:列表分组拼接(兼容性最好)

def format_coord_str(s):
    # 拆分所有单个坐标
    coord_list = s.split()
    # 每两个坐标为一组拼接,再用逗号连接所有组
    coord_pairs = [f"{coord_list[i]} {coord_list[i+1]}" for i in range(0, len(coord_list), 2)]
    return ', '.join(coord_pairs)

df['col3'] = df['col3'].apply(format_coord_str)

方式B:正则替换(代码最简)

直接用正则匹配每两个坐标后的空格,替换为, 即可:

df['col3'] = df['col3'].str.replace(r'(\S+\s\S+)\s', r'\1, ', regex=True)

两种方式最终输出的col3格式都完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 21:42:01