这是使红色标记的每列中的最大值的代码.

import pandas as pd

def highlight_max(s):
    '''
    highlight the maximum in a Series yellow.
    '''
    is_max = s == s.max()
    return ['color: red' if v else '' for v in is_max]


writer = pd.ExcelWriter(f"after.xlsx", engine="xlsxwriter")
df = pd.read_excel('test.xlsx')
df.style.apply(highlight_max).to_excel(writer, index=False)
writer.save()

如何优化代码,使每列的前三个数据都用红色标记?

推荐答案

IIUC,您只需修改函数中定义的布尔掩码is_max.

可能的代码:

import pandas as pd
import numpy as np

df = pd.DataFrame({
    "x1": np.random.randint(0, 100, size=(25,)),
    "x2": np.random.randint(0, 100, size=(25,)),
    "x3": np.random.randint(0, 100, size=(25,)),
    "x4": np.random.randint(0, 100, size=(25,))
})

def highlight_ngreatest(s: pd.Series, n: int = 3):
    """
    Highlight N greatest values in a Series red.
    """
    is_n_greatest = s.isin(s.nlargest(n))
    return ["color: red" if v else "" for v in is_n_greatest]

df.style.apply(highlight_ngreatest, n=3)

输出:

enter image description here

Python相关问答推荐

如何找到满足各组口罩条件的第一行?

聚合具有重复元素的Python字典列表,并添加具有重复元素数量的新键

如何请求使用Python将文件下载到带有登录名的门户网站?

在Python argparse包中添加formatter_class MetavarTypeHelpFormatter时, - help不再工作""""

不允许访问非IPM文件夹

如何指定列数据类型

在两极中过滤

无法在Spyder上的Pandas中将本地CSV转换为数据帧

如何将相同组的值添加到嵌套的Pandas Maprame的倒数第二个索引级别

如何使用matplotlib查看并列直方图

你能把函数的返回类型用作其他地方的类型吗?'

如何获得满足掩码条件的第一行的索引?

Pythonquests.get(Url)返回Colab中的空内容

替换包含Python DataFrame中的值的<;

如何关联来自两个Pandas DataFrame列的列表项?

使用美汤对维基百科表格进行网络刮擦未返回任何内容

将鼠标悬停在海运`pairplot`的批注/高亮显示上

从`end_date`回溯,如何计算以极为单位的滚动统计量?

如何在函数签名中输入数据类字段

基于符号和位置 Select 数据帧特定区域的毕达式方法