Skip to content

Commit

Permalink
CLN: simplify Styler._translate (#43686)
Browse files Browse the repository at this point in the history
  • Loading branch information
attack68 committed Oct 16, 2021
1 parent 7f2b418 commit 445bb9f
Show file tree
Hide file tree
Showing 6 changed files with 222 additions and 111 deletions.
43 changes: 23 additions & 20 deletions doc/source/user_guide/style.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -1047,7 +1047,7 @@
"source": [
"### 5. If every byte counts use string replacement\n",
"\n",
"You can remove unnecessary HTML, or shorten the default class names with string replace functions."
"You can remove unnecessary HTML, or shorten the default class names by replacing the default css dict. You can read a little more about CSS [below](#More-About-CSS-and-HTML)."
]
},
{
Expand All @@ -1056,21 +1056,24 @@
"metadata": {},
"outputs": [],
"source": [
"html = Styler(df4, uuid_len=0, cell_ids=False)\\\n",
" .set_table_styles([{'selector': 'td', 'props': props},\n",
" {'selector': '.col1', 'props': 'color:green;'},\n",
" {'selector': '.level0', 'props': 'color:blue;'}])\\\n",
" .to_html()\\\n",
" .replace('blank', '')\\\n",
" .replace('data', '')\\\n",
" .replace('level0', 'l0')\\\n",
" .replace('col_heading', '')\\\n",
" .replace('row_heading', '')\n",
"\n",
"import re\n",
"html = re.sub(r'col[0-9]+', lambda x: x.group().replace('col', 'c'), html)\n",
"html = re.sub(r'row[0-9]+', lambda x: x.group().replace('row', 'r'), html)\n",
"print(html)"
"my_css = {\n",
" \"row_heading\": \"\",\n",
" \"col_heading\": \"\",\n",
" \"index_name\": \"\",\n",
" \"col\": \"c\",\n",
" \"row\": \"r\",\n",
" \"col_trim\": \"\",\n",
" \"row_trim\": \"\",\n",
" \"level\": \"l\",\n",
" \"data\": \"\",\n",
" \"blank\": \"\",\n",
"}\n",
"html = Styler(df4, uuid_len=0, cell_ids=False)\n",
"html.set_table_styles([{'selector': 'td', 'props': props},\n",
" {'selector': '.c1', 'props': 'color:green;'},\n",
" {'selector': '.l0', 'props': 'color:blue;'}],\n",
" css_class_names=my_css)\n",
"print(html.to_html())"
]
},
{
Expand All @@ -1079,8 +1082,7 @@
"metadata": {},
"outputs": [],
"source": [
"from IPython.display import HTML\n",
"HTML(html)"
"html"
]
},
{
Expand Down Expand Up @@ -1658,6 +1660,7 @@
" + `row<m>`, where `m` is the numeric position of the cell.\n",
" + `col<n>`, where `n` is the numeric position of the cell.\n",
"- Blank cells include `blank`\n",
"- Trimmed cells include `col_trim` or `row_trim`\n",
"\n",
"The structure of the `id` is `T_uuid_level<k>_row<m>_col<n>` where `level<k>` is used only on headings, and headings will only have either `row<m>` or `col<n>` whichever is needed. By default we've also prepended each row/column identifier with a UUID unique to each DataFrame so that the style from one doesn't collide with the styling from another within the same notebook or page. You can read more about the use of UUIDs in [Optimization](#Optimization).\n",
"\n",
Expand Down Expand Up @@ -2020,7 +2023,7 @@
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
Expand All @@ -2034,7 +2037,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.6"
"version": "3.9.5"
}
},
"nbformat": 4,
Expand Down
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.4.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ Styler
- Global options have been extended to configure default ``Styler`` properties including formatting and encoding and mathjax options and LaTeX (:issue:`41395`)
- Naive sparsification is now possible for LaTeX without the multirow package (:issue:`43369`)
- :meth:`Styler.to_html` omits CSSStyle rules for hidden table elements (:issue:`43619`)
- Custom CSS classes can now be directly specified without string replacement (:issue:`43686`)

Formerly Styler relied on ``display.html.use_mathjax``, which has now been replaced by ``styler.html.mathjax``.

Expand Down
45 changes: 41 additions & 4 deletions pandas/io/formats/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,10 @@ class Styler(StylerRenderer):
Attributes
----------
env : Jinja2 jinja2.Environment
template : Jinja2 Template
template_html : Jinja2 Template
template_html_table : Jinja2 Template
template_html_style : Jinja2 Template
template_latex : Jinja2 Template
loader : Jinja2 Loader
See Also
Expand Down Expand Up @@ -182,6 +185,11 @@ class Styler(StylerRenderer):
* Blank cells include ``blank``
* Data cells include ``data``
* Trimmed cells include ``col_trim`` or ``row_trim``.
Any, or all, or these classes can be renamed by using the ``css_class_names``
argument in ``Styler.set_table_classes``, giving a value such as
*{"row": "MY_ROW_CLASS", "col_trim": "", "row_trim": ""}*.
"""

def __init__(
Expand Down Expand Up @@ -1159,6 +1167,7 @@ def _copy(self, deepcopy: bool = False) -> Styler:
- caption
Non-data dependent attributes [copied and exported]:
- css
- hidden index state and hidden columns state (.hide_index_, .hide_columns_)
- table_attributes
- table_styles
Expand All @@ -1185,6 +1194,7 @@ def _copy(self, deepcopy: bool = False) -> Styler:
"template_html",
]
deep = [ # nested lists or dicts
"css",
"_display_funcs",
"_display_funcs_index",
"_display_funcs_columns",
Expand Down Expand Up @@ -1948,9 +1958,10 @@ def set_sticky(

def set_table_styles(
self,
table_styles: dict[Any, CSSStyles] | CSSStyles,
table_styles: dict[Any, CSSStyles] | CSSStyles | None = None,
axis: int = 0,
overwrite: bool = True,
css_class_names: dict[str, str] | None = None,
) -> Styler:
"""
Set the table styles included within the ``<style>`` HTML element.
Expand Down Expand Up @@ -1990,6 +2001,11 @@ def set_table_styles(
.. versionadded:: 1.2.0
css_class_names : dict, optional
A dict of strings used to replace the default CSS classes described below.
.. versionadded:: 1.4.0
Returns
-------
self : Styler
Expand All @@ -2001,6 +2017,22 @@ def set_table_styles(
Styler.set_table_attributes: Set the table attributes added to the ``<table>``
HTML element.
Notes
-----
The default CSS classes dict, whose values can be replaced is as follows:
.. code-block:: python
css_class_names = {"row_heading": "row_heading",
"col_heading": "col_heading",
"index_name": "index_name",
"col": "col",
"col_trim": "col_trim",
"row_trim": "row_trim",
"level": "level",
"data": "data",
"blank": "blank}
Examples
--------
>>> df = pd.DataFrame(np.random.randn(10, 4),
Expand Down Expand Up @@ -2036,10 +2068,15 @@ def set_table_styles(
See `Table Visualization <../../user_guide/style.ipynb>`_ user guide for
more details.
"""
if isinstance(table_styles, dict):
if css_class_names is not None:
self.css = {**self.css, **css_class_names}

if table_styles is None:
return self
elif isinstance(table_styles, dict):
axis = self.data._get_axis_number(axis)
obj = self.data.index if axis == 1 else self.data.columns
idf = ".row" if axis == 1 else ".col"
idf = f".{self.css['row']}" if axis == 1 else f".{self.css['col']}"

table_styles = [
{
Expand Down

0 comments on commit 445bb9f

Please sign in to comment.