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

Pandas如何按accountNumber前缀条件给对应单元格设置黄色背景

解决方案

原有代码的核心逻辑错误:applymap 方法会逐个提取endingBalanceLC列的单个单元格值传入自定义函数,你将单个数值和代表全行判断结果的布尔序列account做相等判断,完全不匹配判断逻辑,因此无法触发样式设置。

正确实现代码如下:

import pandas as pd

df = pd.read_excel("GLAB.xlsx")

def highlight_matched_row(row):
    # 初始化当前行所有单元格无自定义样式
    style_series = pd.Series('', index=row.index)
    # 判断当前行accountNumber前3位是否为121
    if str(row['accountNumber'])[:3] == '121':
        # 仅为endingBalanceLC列单元格设置黄色背景
        style_series['endingBalanceLC'] = 'background-color: yellow'
    return style_series

# 按行应用样式规则
styled_df = df.style.apply(highlight_matched_row, axis=1)

# 若需要导出带样式的结果到Excel,可执行下方代码
# styled_df.to_excel("带样式结果.xlsx", engine="openpyxl", index=False)

注意事项:

  • 如果accountNumber字段本身是字符串类型,可以去掉str()转换步骤
  • 该代码在Jupyter类交互环境运行可直接预览样式效果,普通Python脚本运行无法直接可视化,需要导出到Excel查看效果

内容的提问来源于stack exchange,提问作者Tudor Hosu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 06:54:03