posit-dev / great-tables

Make awesome display tables using Python.
https://posit-dev.github.io/great-tables/
MIT License
1.44k stars 50 forks source link

Add the `fmt_units()` method #240

Closed rich-iannone closed 1 month ago

rich-iannone commented 3 months ago

This PR adds the fmt_units() method. This performs a conversion of units in the units notation syntax (e.g., "x10^9 / L" or "x10^9 L^-1", etc.) to HTML. The method, like others of the fmt_*(), only concerns itself with text transformations in the table body. Other methods will also gain the ability to convert text in units notation to nicely formatted HTML in later PRs.

Here's an example that uses fmt_units() with the illness dataset. It so happens that the units column has strings in units notation, so, we just need to point this method to that column:

from great_tables import GT, style, loc
from great_tables.data import illness

(
    GT(illness, rowname_col="test")
    .fmt_units(columns="units")
    .fmt_number(columns=lambda x: x.startswith("day"), decimals=2, drop_trailing_zeros=True)
    .tab_header(title="Laboratory Findings for the YF Patient")
    .tab_spanner(label="Day", columns=lambda x: x.startswith("day"))
    .tab_spanner(label="Normal Range", columns=lambda x: x.startswith("norm"))
    .cols_label(
      norm_l="Lower",
      norm_u="Upper",
      units="Units"
    )
    .opt_vertical_padding(scale=0.4)
    .opt_align_table_header(align="left")
    .tab_options(heading_padding="10px")
    .tab_style(
        locations=loc.body(columns="norm_l"),
        style=style.borders(sides="left")
    )
    .opt_vertical_padding(scale=0.5)
)

illness

Fixes: https://github.com/posit-dev/great-tables/issues/211 Partially addresses the .epic issue: https://github.com/posit-dev/great-tables/issues/169

codecov-commenter commented 2 months ago

Codecov Report

Attention: Patch coverage is 95.71429% with 6 lines in your changes missing coverage. Please review.

Project coverage is 86.49%. Comparing base (23704ee) to head (55d2fab). Report is 8 commits behind head on main.

Files Patch % Lines
great_tables/_helpers.py 96.87% 4 Missing :warning:
great_tables/_formats.py 80.00% 2 Missing :warning:
Additional details and impacted files ```diff @@ Coverage Diff @@ ## main #240 +/- ## ========================================== + Coverage 86.07% 86.49% +0.41% ========================================== Files 41 41 Lines 4323 4487 +164 ========================================== + Hits 3721 3881 +160 - Misses 602 606 +4 ```

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.

machow commented 1 month ago

From pairing, it sounds like this will be a helpful addition for the SciPy talk.

Let's...

rich-iannone commented 1 month ago

@machow I added a reference to define_units() in the See Also section of the fmt_units() docstring.