Apply a custom text transformation to cells at specified locations.
GT.text_transform(
locations,
fn,
)
With the text_transform() method we can target specific cells and apply a text transformation function to their already-formatted content. This is useful for modifying the rendered text of cells after all formatting (via fmt_*() methods) has been applied.
Parameters
locations: Loc | list[Loc]
-
The cell or set of cells to be associated with the text transformation. Supported locations include loc.body(), loc.stub(), loc.row_groups(), and loc.column_labels().
fn: Callable[[str], str]
-
A function that takes a cell’s text content as a string and returns the transformed string.
Returns
GT
-
The GT object is returned. This is the same object that the method is called on so that we can facilitate method chaining.
Examples
Let’s use the exibble dataset to demonstrate text_transform(). We’ll format the num column and then apply a text transformation to wrap the values in parentheses.
from great_tables import GT, loc, exibble
(
GT(exibble[["num", "char"]].head(4))
.fmt_number(columns="num", decimals=1)
.text_transform(
locations=loc.body(columns="num"),
fn=lambda x: f"({x})",
)
)
| num |
char |
| (0.1) |
apricot |
| (2.2) |
banana |
| (33.3) |
coconut |
| (444.4) |
durian |
Using text_transform() we can also convert specific cells to uppercase. Here we target only the first two rows of the char column.
from great_tables import GT, loc, exibble
(
GT(exibble[["num", "char"]].head(4))
.text_transform(
locations=loc.body(columns="char", rows=[0, 1]),
fn=lambda x: x.upper(),
)
)
| num |
char |
| 0.1111 |
APRICOT |
| 2.222 |
BANANA |
| 33.33 |
coconut |
| 444.4 |
durian |
Multiple locations can be targeted at once by passing a list. In this example, we add a prefix to all cells in both the num and char columns.
from great_tables import GT, loc, exibble
(
GT(exibble[["num", "char"]].head(4))
.fmt_number(columns="num", decimals=2)
.text_transform(
locations=[loc.body(columns="num"), loc.body(columns="char")],
fn=lambda x: f"~ {x}",
)
)
| num |
char |
| ~ 0.11 |
~ apricot |
| ~ 2.22 |
~ banana |
| ~ 33.33 |
~ coconut |
| ~ 444.40 |
~ durian |