Skip to content

BUG: Pandas Styler cell_ids Arg #35586

Closed
@attack68

Description

@attack68

Pandas Styler has the following argument:

cell_ids: bool, default True
If True, each cell will have an id attribute in their HTML tag. The id takes the form T__row<num_row>_col<num_col> where is the unique identifier, <num_row> is the row number and <num_col> is the column number.

This doesn't seem to work.

Consider the example in the docs:

import pandas as pd  # NOTE VERSION 1.1.0
from pandas.io.formats.style import Styler
def highlight_max(s):
    x = s == s.max()
    x = x.replace(False, '')
    x = x.replace(True, 'background-color: yellow; color: brown')
    return x
df = pd.DataFrame(data=[[0,1], [1,0]])
s = Styler(df, uuid='_', cell_ids=False)
s.apply(highlight_max)
s.render()

This will still render id css tags for all cells even though it should have been ignored on some.

Reason and Solution

Upon render, within the code a ctx defaultdict object contains the properties for each cell:

ctx = defaultdict(<class 'list'>, {(1,0): ['background-color: yellow', 'color: brown'], (0,1): ['background-color: yellow', 'color: brown']})

On line 393 we have the condition:

if self.cell_ids or not (len(ctx[r, c]) == 1 and ctx[r, c][0] == ""):
    row_dict["id"] = "_".join(cs[1:])

This fails because the _update_ctx function handles empty string by not adding to the ctx - previously I suspect it performed differently..

We should really change line 393 to:

if self.cell_ids or (r,c) in ctx:

I added a PR for this..

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugIO HTMLread_html, to_html, Styler.apply, Styler.applymap

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions