from great_tables import GT, exibble, loc, style
= exibble[["num", "char", "currency"]].head(3)
lil_exibble = GT(lil_exibble) gt_ex
Row Selection
Location and formatter functions (e.g. loc.body()
and GT.fmt_number()
) can be applied to specific rows, using the rows=
argument.
Rows may be specified using any of the following:
- None (the default), to select everything.
- an integer for the row’s position.
- a list of or integers.
- a Polars selector for filtering.
- a function that takes a DataFrame and returns a boolean Series.
The following sections will use a subset of the exibble
data, to demonstrate these options.
Using integers
Use a single integer, or a list of integers, to select rows by position.
"currency", rows=0, decimals=1) gt_ex.fmt_currency(
num | char | currency |
---|---|---|
0.1111 | apricot | $50.0 |
2.222 | banana | 17.95 |
33.33 | coconut | 1.39 |
Notice that a dollar sign ($
) was only added to the first row (index 0
in python).
Indexing works the same as selecting items from a python list. This negative integers select relative to the final row.
"currency", rows=[0, -1], decimals=1) gt_ex.fmt_currency(
num | char | currency |
---|---|---|
0.1111 | apricot | $50.0 |
2.222 | banana | 17.95 |
33.33 | coconut | $1.4 |
Using polars expressions
The rows=
argument accepts polars expressions, which return a boolean Series, indicating which rows to operate on.
For example, the code below only formats the num
column, but only when currency is less than 40.
import polars as pl
= GT(pl.from_pandas(lil_exibble))
gt_polars
"num", rows=pl.col("currency") < 40) gt_polars.fmt_integer(
num | char | currency |
---|---|---|
0.1111 | apricot | 49.95 |
2 | banana | 17.95 |
33 | coconut | 1.39 |
Here’s a more realistic example, which highlights the row with the highest value for currency.
import polars.selectors as cs
gt_polars.tab_style("yellow"),
style.fill(
loc.body(=cs.all(),
columns=pl.col("currency") == pl.col("currency").max()
rows
) )
num | char | currency |
---|---|---|
0.1111 | apricot | 49.95 |
2.222 | banana | 17.95 |
33.33 | coconut | 1.39 |
Using a function
Since libraries like pandas
don’t have lazy expressions, the rows=
argument also accepts a function for selecting rows. The function should take a DataFrame and return a boolean series.
Here’s the same example as the previous polars section, but with pandas data, and a lamba for selecting rows.
"num", rows=lambda D: D["currency"] < 40) gt_ex.fmt_integer(
num | char | currency |
---|---|---|
0.1111 | apricot | 49.95 |
2 | banana | 17.95 |
33 | coconut | 1.39 |
Here’s the styling example from the previous polars section.
import polars.selectors as cs
gt_ex.tab_style("yellow"),
style.fill(
loc.body(=lambda colname: True,
columns=lambda D: D["currency"] == D["currency"].max()
rows
) )
num | char | currency |
---|---|---|
0.1111 | apricot | 49.95 |
2.222 | banana | 17.95 |
33.33 | coconut | 1.39 |