如何在 Polars 中突出显示每列的值

问题描述 投票:0回答:1

我有一个 Polars DataFrame,我想使用 Polars 中的

style
和 loc 功能突出显示每列的前 3 个值。我可以对单个列实现此目的,但我当前的方法涉及大量重复,这无法扩展到许多变量。

import polars as pl
import polars.selectors as cs
from great_tables import loc, style 

df = pl.DataFrame({
    "id": [1, 2, 3, 4, 5],
    "variable1": [15, 25, 5, 10, 20],
    "variable2": [40, 30, 50, 10, 20],
    "variable3": [400, 100, 300, 200, 500]
})

top3_var1 = pl.col("variable1").is_in(pl.col("variable1").top_k(3))
top3_var2 = pl.col("variable2").is_in(pl.col("variable2").top_k(3))

(
    df
    .style
    .tab_style(
        style.text(weight="bold"),  
        loc.body("variable1", top3_var1)
    )
    .tab_style(
        style.text(weight="bold"),
        loc.body("variable2", top3_var2)
    )
)

这可行,但对于许多列来说它不可扩展,因为我必须为每列手动定义

top3_var

我尝试使用

pl.all().top_k(3)
使该过程更加自动化:

(
    df
    .style
    .tab_style(
        style.text(weight="bold",   ),  
        loc.body("variable1", top3_var1)
    )
    .tab_style(
        style.text(weight="bold"),
        loc.body("variable2", top3_var2)
    )
)

但是,我不确定如何应用 style 和 loc 方法来仅突出显示每列中的前 3 个值,而不影响整行。

python python-polars great-tables
1个回答
0
投票

正如评论中所述,GitHub 上已经有一些关于添加适合用例的 loc.body(mask=...) 参数的

 讨论 

在实现此功能之前,您可以创建一个

GT

 (
Great Table) 对象并迭代使用 gt.tab_style
,如下所示。这避免了手动链接 
tab_style
 调用。

import polars as pl import polars.selectors as cs from great_tables import GT, loc, style df = pl.DataFrame({ "id": [1, 2, 3, 4, 5], "variable1": [15, 25, 5, 10, 20], "variable2": [40, 30, 50, 10, 20], "variable3": [400, 100, 300, 200, 500] }) gt = GT(df) for col in df.select(cs.exclude("id")).columns: gt = gt.tab_style( style.text(weight="bold"), loc.body(col, pl.col(col).is_in(pl.col(col).top_k(3))) ) gt

GreatTable

© www.soinside.com 2019 - 2024. All rights reserved.