great-tables
great-tables copied to clipboard
Implement `GT.pipe()` and `GT.pipes()`
Related to #353.
After reviewing the pipe()
methods from Pandas and Polars, I propose adding GT.pipe()
and GT.pipes()
in this PR.
GT.pipe()
GT.pipe()
will function similarly to Pandas
and Polars
, receiving a function along with optional positional and keyword arguments. An example is provided below:
import polars as pl
from great_tables import GT, loc, style
from great_tables.data import towny
towny_mini = pl.from_pandas(towny).head(10)
columns = ["land_area_km2", "density_2021"]
colors = ["lightgray", "lightblue"]
def tbl_style(gtbl: GT, columns: list[str], colors: list[str]) -> GT:
for column, color in zip(columns, colors):
gtbl = gtbl.tab_style(
style=style.fill(color=color),
locations=loc.body(columns=column, rows=pl.col(column).eq(pl.col(column).max())),
)
return gtbl
(
GT(
towny_mini[["name", "land_area_km2", "density_2021"]],
rowname_col="name",
).pipe(tbl_style, columns, colors)
)
GT.pipes()
GT.pipe()
serves as a convenient helper method for chaining multiple pre-built functions (or using partial
). An example is provided below:
from functools import partial
import polars as pl
from great_tables import GT, loc, style
from great_tables.data import towny
towny_mini = pl.from_pandas(towny).head(10)
columns = ["land_area_km2", "density_2021"]
colors = ["lightgray", "lightblue"]
def tbl_style(gtbl: GT, column: str, color: str) -> GT:
return gtbl.tab_style(
style=style.fill(color=color),
locations=loc.body(columns=column, rows=pl.col(column).eq(pl.col(column).max())),
)
(
GT(
towny_mini[["name", "land_area_km2", "density_2021"]],
rowname_col="name",
).pipes(
*[partial(tbl_style, column=column, color=color) for column, color in zip(columns, colors)]
)
)
Table
Both methods yield the table as follows:
Assistance Required
I hope the API design makes sense, and could the team please review my docs to ensure they render correctly? I'm relatively new to quarto
.