python - 用熊猫中的其他列子字符串替换子字符串
问题描述
我有一个数据框,其中包含一些模板字符串和相应的字符串变量来替换。例如,给定:
template,variable
"{color} shirt in {size}", "blue,medium"
"{capacity} bottle in {color}", "24oz,teal"
"{megapixel}mp camera", "24.1"
我想制作以下内容:
"blue shirt in medium"
"24oz bottle in teal"
"24.1mp camera"
保证第一列中模板子字符串的数量将等于第二列中字符串中的变量数量。字符串的格式与上面的示例一致。
我的第一个想法是使用extractall
然后加入创建一个多索引数据框:
templates = df['template'].str.extractall('({\w+\})')
variables = df['variable'].str.extractall('(\w+)')
multi_df = templates.join(variables, how='inner')
但我不知道从那里去哪里。或者有没有更简单的方法?
解决方案
用于string.Formatter
从template
列中提取变量并构建字典以进行替换。
>>> df
template value # I modified your column name
0 {color} shirt in {size} blue,medium
1 {capacity} bottle in {color} 24oz,teal
2 {megapixel}mp camera 24.1
from string import Formatter
def extract_vars(s):
return tuple(fn for _, fn, _, _ in Formatter().parse(s) if fn is not None)
df['variable'] = df['template'].apply(extract_vars)
df['value'] = df['value'].str.split(',')
df['combined'] = df.apply(lambda x: dict(zip(x['variable'], x['value'])), axis=1)
此时,您的数据框如下所示:
template value variable combined
0 {color} shirt in {size} [blue, medium] [color, size] {'color': 'blue', 'size': 'medium'}
1 {capacity} bottle in {color} [24oz, teal] [capacity, color] {'capacity': '24oz', 'color': 'teal'}
2 {megapixel}mp camera [24.1] [megapixel] {'megapixel': '24.1'}
最后,评估你的字符串:
>>> df.apply(lambda x: x['template'].format(**x['combined']), axis=1)
0 blue shirt in medium
1 24oz bottle in teal
2 24.1mp camera
dtype: object
推荐阅读
- mongodb - 在 Mongo 集合上运行任意查询有多糟糕
- javascript - 当访问者在剪贴板上复制内容时如何自定义警报
- javascript - 为什么不使用 jQuery ajax 删除数据
- c# - Protocols.SoapException:找不到文件,我把路径
- javascript - 如何使用偏移值检查时区的夏令时启用
- sql - 如何使用 OPENJSON 在 sql server 中导航具有命名空间前缀(例如 n1:、n7: )的 json 对象的路径?
- java - 如何将Java中的“Color.rgb”设置为随机?
- java - 按下按钮时如何在Java中销毁CoundownTimer?
- sql - 在 SQL (ORACLE) 上组合和检查表值
- c# - Asp .Net Core 单元测试模拟 UserManager.CreateAsync 并返回身份结果