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

如何按自定义规则为Pandas DataFrame乘法表单元格设置背景色?

乘法表单元格着色异常问题

我需要给一个简易乘法表的单元格按规则着色:符合规则的单元格设为绿色,不符合的设为红色,规则判断逻辑如下:


示例1:给定数字10和11,由于 -798010 ≠ 110,规则不满足,单元格颜色设为红色:

  • 计算(100-(100-10)-(100-11)) = -79 和 (100-10)*(100-11) = 8010,将两个结果字符串拼接得到:-798010
  • 计算10*11的结果:110

示例2:给定数字10和99,由于 990 = 990,规则满足,单元格颜色设为绿色:

  • 计算(100-(100-10)-(100-99)) = 9 和 (100-10)*(100-99) = 90,将两个结果字符串拼接得到:990
  • 计算10*99的结果:990

目前我编写了代码来检查数字是否符合规则,但所有单元格始终只显示同一种颜色,代码如下:

import pandas as pd

l = []
for i in range(10, 100):
     for j in range(10, 100):
        l.append(f'{i}*{j}')
        result = [l[idx:idx+90] for idx in range(0, len(l), 90)]
        df = pd.DataFrame(result)

def style_dataframe(s):
    for row_index, row in df.iterrows():
        for col_name, cell in row.items():
            if int(cell[:2])*int(cell[3:5]) == int(str(100 - ((100 - (int(cell[:2])))-(100-(int(cell[3:5])))))+str((100-(int(cell[:2])))*int(int(cell[3:5])))):
                return 'background-color: green'
            elif int(cell[:2])*int(cell[3:5]) != int(str(100 - ((100 - (int(cell[:2])))-(100-(int(cell[3:5])))))+str((100-(int(cell[:2])))*int(int(cell[3:5])))):
                return 'background-color: red'
  
s = df.style.applymap(style_dataframe)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 07:53:09