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
相关产品推荐
相关产品推荐

