great-tables icon indicating copy to clipboard operation
great-tables copied to clipboard

Fix: Modify the group labels when render_formats() is called

Open juleswg23 opened this issue 3 months ago • 2 comments

Summary

Apply fmt() output to group labels in the stub.

This approach goes upstream of the approach in #755. It is admittedly, a little heavier-weight, but does still happen at render time. The advantage to this over #755 is that we are modifying the group label before the html rendering, so this will apply to latex tables. Additionally, it takes advantage of the stubbed out group_row.group_label attribute.

from great_tables import GT
from great_tables.data import countrypops
import polars as pl
import polars.selectors as cs

# Get vectors of 2-letter country codes for each region of Oceania
countries = {
    "[Australasia](http://www.google.com)": ["AU", "NZ"],
    "[Melanesia](http://www.google.com)": ["NC", "PG", "SB", "VU"],
    "[Micronesia](http://www.google.com)": ["FM", "GU", "KI", "MH", "MP", "NR", "PW"],
    "[Polynesia](http://www.google.com)": ["PF", "WS", "TO", "TV"],
}

# Create a dictionary mapping region to country (e.g. AU -> Australasia)
region_to_country = {
    region: country for country, regions in countries.items() for region in regions
}

wide_pops = (
    pl.from_pandas(countrypops)
    .filter(
        pl.col("country_code_2").is_in(list(region_to_country))
        & pl.col("year").is_in([2000, 2010, 2020])
    )
    .with_columns(pl.col("country_code_2").replace(region_to_country).alias("region"))
    .pivot(index=["country_name", "region"], columns="year", values="population")
    .sort("2020", descending=True)
)

(
    GT(wide_pops, rowname_col="country_name", groupname_col="region")
    .fmt_markdown(columns=["region"])
    .tab_header(title="Populations of Oceania's Countries in 2000, 2010, and 2020")
    .tab_spanner(label="Total Population", columns=cs.all())
    .fmt_integer()
)

Previously, this code block had the following output.

image

Now we see this output:

image

Related GitHub Issues and PRs

closes #761

We could also close #236 if this PR is merged.

Checklist

  • [x] I understand and agree to the Code of Conduct.
  • [x] I have followed the Style Guide for Python Code as best as possible for the submitted code.
  • [ ] I have added pytest unit tests for any new functionality.

juleswg23 avatar Aug 28 '25 19:08 juleswg23