Three Approaches to Styling the Table Body in Great Tables
python
polars
gt
Author
Jerry Wu
Published
January 24, 2025
This post demonstrates three approaches to styling the table body:
Using a for-loop: Repeatedly call GT.tab_style() for each column.
Utilizing the locations= parameter in GT.tab_style(): Pass a list of loc.body() objects.
Leveraging the mask= parameter in loc.body(): Use Polars expressions for streamlined styling.
Let’s dive in.
Preparations
We’ll use the built-in dataset gtcars to create a Polars DataFrame. First, we’ll select the columns mfr, drivetrain, year, and hp to create a small pivoted table named df_mini. Then, we’ll pass df_mini to the GT object and use GT.tab_stub(), setting drivetrain as rowname_col= and mfr as groupname_col= to create the table gt, as shown below:
In this example, loc.body() is smart enough to automatically target the rows where the cell value exceeds 650 for each numerical column. In general, you can think of mask= as a syntactic sugar that Great Tables provides to save you from having to manually loop through the columns.
Final Words
This post summarizes three approaches to styling the table body. Among them, the mask= parameter in loc.body() is definitely my favorite, inspired by #389 and implemented by me.
Special thanks to @rich-iannone and @machow for their invaluable suggestions during development. Any remaining bugs are entirely on me.
Disclaimer
This post was drafted by me, with AI assistance to refine the content.