我正在try 设计一个简单的乘法表.我有以下规则,如果一个单元格不满足它,我必须用不同的 colored颜色 给它上色.


给出数字10和11,从-798010开始的rule is broken!=110,所以 colored颜色 是红色:

  • (100-(100-10)-(100-11)) = -79(100-10)*(100-11) = 8010组合为字符串:-798010
  • 10*11:110

Example 2:给出数字10和99,从990开始的rule is satisfied==990,所以 colored颜色 是绿色的.

  • (100-(100-10)-(100-99)) = 9(100-10)*(100-99) = 90组合为字符串:990
  • 10*90:990

目前我正在判断规则中是否包含数字.无论用哪种方法,我得到的都是一种 colored颜色 的所有单元:

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)

推荐答案

  • df.style.applymap按元素操作,因此样式化函数只需要1个单元格(不是数据帧)
  • 100-(100-a)-(100-b)人可以简化为a+b-100

因此,样式函数应该如下所示:

def rule(cell):
    a, b = map(int, cell.split('*'))                  # split 'a*b' into [a, b]
    cond1 = str(a+b-100) + str((100-a)*(100-b))       # string version
    cond2 = a * b                                     # multiplication version
    color = 'green' if int(cond1) == cond2 else 'red' # check rule
    return f'background-color: {color}'               # return css style

df.style.applymap(rule)


顺便说一句,用NumPy广播创建最初的df要简单得多:

a = np.arange(10, 100).astype(str)
df = pd.DataFrame(np.char.add(np.char.add(a[:, None], '*'), a))

#         0      1      2  ...     87     88     89
# 0   10*10  10*11  10*12  ...  10*97  10*98  10*99
# 1   11*10  11*11  11*12  ...  11*97  11*98  11*99
# 2   12*10  12*11  12*12  ...  12*97  12*98  12*99
# ..    ...    ...    ...  ...    ...    ...    ...
# 87  97*10  97*11  97*12  ...  97*97  97*98  97*99
# 88  98*10  98*11  98*12  ...  98*97  98*98  98*99
# 89  99*10  99*11  99*12  ...  99*97  99*98  99*99
# 
# [90 rows x 90 columns]

Python相关问答推荐

Django mysql图标不适用于小 case

沿着数组中的轴计算真实条目

Python库:可选地支持numpy类型,而不依赖于numpy

加速Python循环

OR—Tools中CP—SAT求解器的IntVar设置值

如何调整QscrollArea以正确显示内部正在变化的Qgridlayout?

如何在UserSerializer中添加显式字段?

UNIQUE约束失败:customuser. username

基于多个数组的多个条件将值添加到numpy数组

如何在FastAPI中替换Pydantic的constr,以便在BaseModel之外使用?'

如何将泛型类类型与函数返回类型结合使用?

当HTTP 201响应包含 Big Data 的POST请求时,应该是什么?  

我什么时候应该使用帆布和标签?

为什么Visual Studio Code说我的代码在使用Pandas concat函数后无法访问?

如何在Python中从html页面中提取html链接?

分解polars DataFrame列而不重复其他列值

极点用特定值替换前n行

我如何为测试函数的参数化提供fixture 生成的数据?如果我可以的话,还有其他 Select 吗?

在Django REST框架中定义的URL获得404分

如何从具有完整层次数据的Pandas框架生成图形?