如何在Polars中为DataFrame每列高亮前3个值(优化可扩展性)
批量为Polars DataFrame多列前3个值添加高亮样式
你可以通过循环遍历目标列或者函数式链式处理的方式,避免重复代码,实现多列自动高亮前3个值的需求。以下是具体实现方案:
方案1:循环遍历目标列(直观易读)
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] }) # 自动筛选需要处理的列:排除id列,取所有数值列 target_cols = cs.numeric().exclude("id")(df).columns # 初始化样式对象 styled_df = df.style # 循环为每列设置高亮 for col in target_cols: # 生成当前列前3个值的判断条件 top3_condition = pl.col(col).is_in(pl.col(col).top_k(3)) # 应用加粗样式 styled_df = styled_df.tab_style( style.text(weight="bold"), loc.body(col, top3_condition) ) styled_df
方案2:函数式链式处理(简洁链式写法)
如果偏好Polars的链式风格,可以用functools.reduce实现:
import polars as pl import polars.selectors as cs from great_tables import loc, style from functools import reduce 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] }) target_cols = cs.numeric().exclude("id")(df).columns # 用reduce链式叠加样式 styled_df = reduce( lambda acc, col: acc.tab_style( style.text(weight="bold"), loc.body(col, pl.col(col).is_in(pl.col(col).top_k(3))) ), target_cols, df.style ) styled_df
核心逻辑说明
- 自动列筛选:通过
cs.numeric().exclude("id")自动识别需要处理的数值列,无需手动列名,新增列时自动适配。 - 列独立条件:每列单独生成
top_k(3)的判断条件,确保只高亮当前列的前3个值,不会影响整行或其他列。 - 批量样式应用:通过循环或reduce批量调用
tab_style,避免重复编写相同的样式代码。
内容的提问来源于stack exchange,提问作者Simon
相关产品推荐
相关产品推荐

