【发布时间】:2023-03-19 07:20:02
【问题描述】:
我有一个数据框,其中包含一些模板字符串和相应的字符串变量来替换。例如,给定:
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')
但我不知道从那里去哪里。或者有没有更简单的方法?
【问题讨论】:
-
单纯的
print(f"{color} shirt in {size}")不行吗?