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

如何遍历Pandas DataFrame填充HTML模板,仅grade为A时填入grade_info

需求说明

遍历现有DataFrame,根据HTML模板生成内容填充到grade_notes列,仅当grade值为A(不区分大小写)时才填入grade_info的内容,否则该位置留空。

原代码存在的问题

  • 遍历逻辑错误:不应该遍历grade_info列逐行重写整列的grade_notes,会导致最后一行的判断覆盖所有行结果
  • 占位符不匹配:模板里的占位符是[NAME]、[grade_info],原代码里写的[Name]、[GRADE_INFO]无法匹配替换
  • 语法错误:replace方法括号未配对,文件路径缺少引号,for循环缺少冒号
  • 冗余操作:不需要每次循环都重复读取模板文件,提前读取一次即可
  • 判断条件错误:原代码判断'A' in i是检查grade_info里是否包含A,不符合需求里判断grade列是否等于A的要求

正确实现代码

import pandas as pd

# 提前一次性读取模板,避免重复IO操作
with open('c:/users/documents/htmlex.txt', 'r') as f:
    template = f.read().strip()

# 单次apply完成所有行的判断和替换,无需额外循环
df['grade_notes'] = df.apply(lambda row: template
                             .replace('[NAME]', str(row['name']))
                             .replace('[ID]', str(row['id']))
                             .replace('[grade_info]', str(row['grade_info']) if row['grade'].strip().upper() == 'A' else ''),
                             axis=1)

输出效果验证

对应给出的测试数据,grade_notes列最终内容如下:

  • id=1:
My name is aj. My ID # is 1.

pass
  • id=2:
My name is bj. My ID # is 2.

  • id=3:
My name is kj. My ID # is 3.

pass
  • id=4:
My name is mj. My ID # is 4.

  • id=5:
My name is dj. My ID # is 5.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 01:54:03