Skip to content

Conditionally styling by HTML classes #14226

Closed
@dov

Description

@dov

Currently the DataFrame.Styler class provides for adding of css key/value attribute pairs. But it is sometimes preferable to add a HTML class to a cell instead, and then let the styling be done by an external css file.

As an example consider the following DataFrame:

df = pd.DataFrame([[1,2],
                  [-5,1]],
                  columns=['A','B'])

As an example, we would like to attach the class "negative" to the -5 and receive the following HTML:

<html><table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>A</th>
      <th>B</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>1</td>
      <td>2</td>
    </tr>
    <tr>
      <th>1</th>
      <td class="negative">-5</td>
      <td>1</td>
    </tr>
  </tbody>
</table></html>

Regarding how to implement this, here are a couple of ideas:

  1. Add a flag by_class to apply() and applymap() that instructs the styler that the "function" will return a classes instead of css strings.
  2. Add new functions apply_class() and applymap_class().
  3. Create a new class StyleClass() and use isinstance(ret,StyleClass) to determine whether to modify the style directly or by adding additional classes.

IMO, I believe that it would be a better interface of styler that apply and applymap were to return classes by default and then optionally provide a css style sheet that can be resolved when turning the style into html. Such an approach would also be easier to adapt to additional backends, e.g. LaTeX. The disadvantage though is that it would break backwards compatibility, and that it would make styling for iPython (the main usecase?) more complicated.

Metadata

Metadata

Assignees

No one assigned

    Labels

    EnhancementIO HTMLread_html, to_html, Styler.apply, Styler.applymapOutput-Formatting__repr__ of pandas objects, to_string

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions