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

Using .data_color for a subset of rows #248

Closed tomas19 closed 2 weeks ago

tomas19 commented 3 months ago

Is it possible to use the .data_color method for a subset of the rows?

I have a dataframe where the last row and columns are the sum of the values of each column and row, respectively. It is easy to exclude the last column from the colormap, specifying the column names in columns, but I couldn't figure out how to exclude the last row.

It should be possible to do it with the summary_rows(), but from the video below, apparently it is not implemented yet (?) https://www.youtube.com/watch?v=p42Xc6dl3Ek

Thanks!

rasmi commented 2 months ago

Similar question here. The use cases is specifically to apply colors to a table, factoring in all values into the domain except the Grand Total. It is easy to exclude specific columns with the columns= argument, but there is no such argument for rows. One could compute the palette manually as is done in the underlying code, but it adds another step. In that sense, related to #172 and #173 for this specific use case.

rich-iannone commented 2 months ago

Sorry for the delay in responding but data_color() needs a rows argument. We will try to get that in soon.

rasmi commented 2 months ago

I did a hacky workaround for this here (may not work in many cases, e.g. assumes pandas, expects a list of ints, must be consecutive top-to-bottom rows that only exclude rows from the end of the table):

Added a rows argument to _data_color/base.py's data_color method:

def data_color(
    self: GTSelf,
    columns: Union[str, List[str], None] = None,
    palette: Union[str, List[str], None] = None,
    domain: Union[List[str], List[float], List[int], None] = None,
    na_color: Optional[str] = None,
    alpha: Optional[Union[int, float]] = None,
    reverse: bool = False,
    autocolor_text: bool = True,
    rows: Optional[List[int]] = None,
) -> GTSelf:

Further down in the data_color method, grab the desired rows:

    # Get the internal data table
    data_table = self._tbl_data
    # Use only selected rows.
    if rows:
      data_table = data_table.copy().iloc[rows]

Not ideal but it allowed me to create and render my table in the interim!

rich-iannone commented 2 weeks ago

Completed with https://github.com/posit-dev/great-tables/pull/364.