diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index ad6ad5bcaf309..3b3238586b310 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -64,6 +64,11 @@ class Styler(object): a unique identifier to avoid CSS collisions; generated automatically caption: str, default None caption to attach to the table + 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_col`` + where ```` is the unique identifier, ```` is the row + number and ```` is the column number. Attributes ---------- @@ -112,7 +117,7 @@ class Styler(object): template = env.get_template("html.tpl") def __init__(self, data, precision=None, table_styles=None, uuid=None, - caption=None, table_attributes=None): + caption=None, table_attributes=None, cell_ids=True): self.ctx = defaultdict(list) self._todo = [] @@ -136,6 +141,7 @@ def __init__(self, data, precision=None, table_styles=None, uuid=None, self.table_attributes = table_attributes self.hidden_index = False self.hidden_columns = [] + self.cell_ids = cell_ids # display_funcs maps (row, col) -> formatting function @@ -306,14 +312,16 @@ def format_attr(pair): cs.extend(cell_context.get("data", {}).get(r, {}).get(c, [])) formatter = self._display_funcs[(r, c)] value = self.data.iloc[r, c] - row_es.append({ - "type": "td", - "value": value, - "class": " ".join(cs), - "id": "_".join(cs[1:]), - "display_value": formatter(value), - "is_visible": (c not in hidden_columns) - }) + row_dict = {"type": "td", + "value": value, + "class": " ".join(cs), + "display_value": formatter(value), + "is_visible": (c not in hidden_columns)} + # only add an id if the cell has a style + if (self.cell_ids or + not(len(ctx[r, c]) == 1 and ctx[r, c][0] == '')): + row_dict["id"] = "_".join(cs[1:]) + row_es.append(row_dict) props = [] for x in ctx[r, c]: # have to handle empty styles like [''] diff --git a/pandas/io/formats/templates/html.tpl b/pandas/io/formats/templates/html.tpl index 706db1ecdd961..01ecde7d081f5 100644 --- a/pandas/io/formats/templates/html.tpl +++ b/pandas/io/formats/templates/html.tpl @@ -50,17 +50,17 @@ {%- endblock thead %} {%- block tbody %} - {%- block before_rows %}{%- endblock before_rows %} - {%- for r in body %} - {%- block tr scoped %} - - {%- for c in r %} - {%- if c.is_visible != False %} - <{{ c.type }} id="T_{{ uuid }}{{ c.id }}" class="{{ c.class }}" {{ c.attributes|join(" ") }}>{{ c.display_value }} - {%- endif %} - {%- endfor %} - - {%- endblock tr %} + {% block before_rows %}{% endblock before_rows %} + {% for r in body %} + {% block tr scoped %} + + {% for c in r %} + {% if c.is_visible != False %} + <{{ c.type }} {% if c.id is defined -%} id="T_{{ uuid }}{{ c.id }}" {%- endif %} class="{{ c.class }}" {{ c.attributes|join(" ") }}>{{ c.display_value }} + {% endif %} + {%- endfor %} + + {% endblock tr %} {%- endfor %} {%- block after_rows %}{%- endblock after_rows %}