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

pandas中将模板列子串替换为另一列对应子串的实现方法求助

解决方案

直接逐行调用Python原生字符串的format方法即可,逻辑简单且不会出现正则匹配丢失字符的问题:
首先是测试数据构造(你可以跳过这步直接用自己的df):

import pandas as pd

df = pd.DataFrame({
    'template': ["{color} shirt in {size}", "{capacity} bottle in {color}", "{megapixel}mp camera"],
    'variable': ["blue,medium", "24oz,teal", "24.1"]
})

核心处理逻辑:

df['output'] = df.apply(
    lambda row: row['template'].format(*row['variable'].split(',')),
    axis=1
)

运行后查看output列即可得到你要的结果:

print(df['output'])
# 0    blue shirt in medium
# 1     24oz bottle in teal
# 2        24.1mp camera
# Name: output, dtype: object

补充说明

你之前用extractall的思路存在一个明显问题:正则(\w+)只能匹配字母、数字、下划线,会丢失变量值里的小数点等特殊字符,比如示例中的24.1会被错误提取为24,后续拼接也会出错。如果没有特殊需求,上面的apply方案是最高效简洁的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 14:39:01