python - 基于每行唯一文本模板的输出列
问题描述
这是我正在使用的数据框:
|ID | type | product | date | time | template_id | template |
| 1 | A | xx | 04/01 | 4pm | 1 | Product {0} was sold on {1} at {2}.format(product,date,time) |
| 2 | A | xx | 05/01 | 6pm | 1 | Product {0} was sold on {1} at {2}.format(product,date,time) |
| 3 | B | yy | 04/10 | 4pm | 2 | Item {0} was purchased on {1}.format(product,date) |
| 4 | B | yy | 04/10 | 4pm | 1 | Product {0} was sold on {1} at {2}.format(product,date,time) |
不同的 'type' 映射到不同 template_id 的组合。每个模板 id 都有一个不同的模板。
我感兴趣的输出:
|ID | type | product | date | time | template_id | text_col |
| 1 | A | xx | 04/01 | 4pm | 1 | Product xx was sold on 04/01 at 4pm |
| 2 | A | xx | 05/01 | 6pm | 1 | Product xx was sold on 05/01 at 6pm |
| 3 | B | yy | 04/10 | 4pm | 2 | Item yy was purchased on 04/10 |
| 4 | B | yy | 04/10 | 4pm | 1 | Product yy was sold on 04/10 at 4pm |
我尝试遍历 df 中的每一行并存储产品、日期、时间变量,如下所示:
for x in df.iterrows():
product=product
date=date
time=time
但我不确定如何将这些值嵌入到模板列中,然后将这些值作为该 df 的新列输出。
任何帮助表示赞赏!
解决方案
你可以试试这个:
# Store templates in a dict
templates = {
1: "Product {0} was sold on {1} at {2}",
2: "Item {0} was purchased on {1}",
}
# Create a list of strings with desired values
text_col = [
templates[row["template_id"]]
.replace("{0}", row["product"])
.replace("{1}", row["date"])
.replace("{2}", row["time"])
for _, row in df.iterrows()
]
# Add a new column
df["text_col"] = pd.DataFrame(text_col)
print(df)
product date time template_id text_col
0 xx 04/01 4pm 1 Product xx was sold on 04/01 at 4pm
1 xx 05/01 6pm 1 Product xx was sold on 05/01 at 6pm
2 yy 04/10 4pm 2 Item yy was purchased on 04/10
3 yy 04/10 4pm 1 Product yy was sold on 04/10 at 4pm
推荐阅读
- java - 使用 java 16 和 gradle 7 构建项目时出现“致命错误:无法在类路径或引导类路径中找到包 java.lang”
- google-sheets - 将 ROW 函数与公式要处理的范围结合使用
- python - 如果文件夹已经存在,如何创建子文件夹?
- amazon-web-services - 检索地图变量的子网 ID
- docker - 要在 yaml 文件中输入以进行 KNATIVE 部署的正确图像 url 是什么
- typescript - 如何将 SCSS 样式表添加到 Lit Web 组件?
- python - 将代码步骤组合成用户定义的函数
- r - 从其他行获取平均值到当前行
- c# - 在一种情况下,继承的依赖属性更改无法传播给子项
- asp.net-mvc - COM+ 激活库崩溃 .Net v4 工作进程