跳到内容

样式设置

Polars DataFrame 中的数据可以通过 DataFrame.style 属性进行样式设置以供展示使用。这会返回一个来自 Great TablesGT 对象,它支持表格展示的结构化、格式化和样式设置。

import polars as pl
import polars.selectors as cs

path = "docs/assets/data/iris.csv"

df = (
    pl.scan_csv(path)
    .group_by("species")
    .agg(cs.starts_with("petal").mean().round(3))
    .collect()
)
print(df)
shape: (3, 3)
┌────────────┬──────────────┬─────────────┐
│ species    ┆ petal_length ┆ petal_width │
│ ---        ┆ ---          ┆ ---         │
│ str        ┆ f64          ┆ f64         │
╞════════════╪══════════════╪═════════════╡
│ Versicolor ┆ 4.26         ┆ 1.326       │
│ Setosa     ┆ 1.462        ┆ 0.246       │
│ Virginica  ┆ 5.552        ┆ 2.026       │
└────────────┴──────────────┴─────────────┘

结构:添加标题

df.style.tab_header(title="Iris Data", subtitle="Mean measurement values per species")
鸢尾花数据
各物种的平均测量值
物种 花瓣长度 花瓣宽度
变色鸢尾 4.26 1.326
山鸢尾 1.462 0.246
弗吉尼亚鸢尾 5.552 2.026

结构:添加行标题

df.style.tab_stub(rowname_col="species")
花瓣长度 花瓣宽度
变色鸢尾 4.26 1.326
山鸢尾 1.462 0.246
弗吉尼亚鸢尾 5.552 2.026

结构:添加跨列标题

(
    df.style.tab_spanner("Petal", cs.starts_with("petal")).cols_label(
        petal_length="Length", petal_width="Width"
    )
)
物种 花瓣
长度 宽度
变色鸢尾 4.26 1.326
山鸢尾 1.462 0.246
弗吉尼亚鸢尾 5.552 2.026

格式:限制小数位数

df.style.fmt_number("petal_width", decimals=1)
物种 花瓣长度 花瓣宽度
变色鸢尾 4.26 1.3
山鸢尾 1.462 0.2
弗吉尼亚鸢尾 5.552 2.0

样式:高亮显示最大行

from great_tables import loc, style

df.style.tab_style(
    style.fill("yellow"),
    loc.body(
        rows=pl.col("petal_length") == pl.col("petal_length").max(),
    ),
)
物种 花瓣长度 花瓣宽度
变色鸢尾 4.26 1.326
山鸢尾 1.462 0.246
弗吉尼亚鸢尾 5.552 2.026

样式:加粗物种列

from great_tables import loc, style

df.style.tab_style(
    style.text(weight="bold"),
    loc.body(columns="species"),
)
物种 花瓣长度 花瓣宽度
变色鸢尾 4.26 1.326
山鸢尾 1.462 0.246
弗吉尼亚鸢尾 5.552 2.026

完整示例

from great_tables import loc, style

(
    df.style.tab_header(
        title="Iris Data", subtitle="Mean measurement values per species"
    )
    .tab_stub(rowname_col="species")
    .cols_label(petal_length="Length", petal_width="Width")
    .tab_spanner("Petal", cs.starts_with("petal"))
    .fmt_number("petal_width", decimals=2)
    .tab_style(
        style.fill("yellow"),
        loc.body(
            rows=pl.col("petal_length") == pl.col("petal_length").max(),
        ),
    )
)
鸢尾花数据
各物种的平均测量值
花瓣
长度 宽度
变色鸢尾 4.26 1.33
山鸢尾 1.462 0.25
弗吉尼亚鸢尾 5.552 2.03