Skip to content

CLN: simplify Styler._translate #43686

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 41 commits into from
Oct 16, 2021
Merged
Show file tree
Hide file tree
Changes from 30 commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
7903723
clean up code
attack68 Sep 21, 2021
6a2793c
row, col and level css
attack68 Sep 21, 2021
d227914
whats new
attack68 Sep 21, 2021
7ca5002
tests and user guide
attack68 Sep 21, 2021
f27f7ed
merge
attack68 Sep 22, 2021
a1000a7
merge
attack68 Sep 22, 2021
021bc26
docs
attack68 Sep 22, 2021
4ba3dff
docs
attack68 Sep 22, 2021
7fee05d
more explicit test
attack68 Sep 22, 2021
baa3233
more explicit test
attack68 Sep 22, 2021
f4ad390
fix checks
attack68 Sep 23, 2021
22b03e3
fix checks
attack68 Sep 23, 2021
db214d8
fix checks
attack68 Sep 23, 2021
24952ae
fix checks
attack68 Sep 24, 2021
1d47d0f
Merge remote-tracking branch 'upstream/master' into clean_styler_css_…
attack68 Sep 24, 2021
566738d
fix checks
attack68 Sep 24, 2021
230138a
fix checks
attack68 Sep 24, 2021
b9ba9ea
refactor to get tests to pass
attack68 Sep 25, 2021
ea2bba1
refactor to get tests to pass
attack68 Sep 25, 2021
ca70491
correct css classes in set_table_styles
attack68 Sep 25, 2021
7a1994e
Merge remote-tracking branch 'upstream/master' into clean_styler_css_…
attack68 Sep 29, 2021
91320f8
add version added
attack68 Sep 29, 2021
92c1941
add version added
attack68 Sep 29, 2021
aad0e16
checks fix
attack68 Sep 29, 2021
61b24ed
add tests allow none
attack68 Sep 29, 2021
d4c5715
fix checks
attack68 Sep 29, 2021
aa0172f
Merge remote-tracking branch 'upstream/master' into clean_styler_css_…
attack68 Oct 2, 2021
84a814f
rename `css` `css_class_names`
attack68 Oct 2, 2021
f06b727
rename `css` `css_class_names`
attack68 Oct 2, 2021
131070f
rename `css` `css_class_names`
attack68 Oct 2, 2021
a048122
update arg name
attack68 Oct 2, 2021
4931f32
Merge remote-tracking branch 'upstream/master' into clean_styler_css_…
attack68 Oct 3, 2021
e9716f2
fix line length
attack68 Oct 3, 2021
d983464
black
attack68 Oct 3, 2021
16946b0
Merge remote-tracking branch 'upstream/master' into clean_styler_css_…
attack68 Oct 9, 2021
6e71e8c
Merge remote-tracking branch 'upstream/master' into clean_styler_css_…
attack68 Oct 11, 2021
1aa7c55
remove css_ids
attack68 Oct 15, 2021
d567d55
remove css_class_names from constructor
attack68 Oct 15, 2021
9d3c177
remove css_class_names from constructor
attack68 Oct 15, 2021
f0b3a20
update docs
attack68 Oct 15, 2021
f945ac8
Merge remote-tracking branch 'upstream/master' into clean_styler_css_…
attack68 Oct 15, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 22 additions & 20 deletions doc/source/user_guide/style.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -1046,7 +1046,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 @@ -1055,21 +1055,23 @@
"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, css_class_names=my_css)\n",
"html.set_table_styles([{'selector': 'td', 'props': props},\n",
" {'selector': '.c1', 'props': 'color:green;'},\n",
" {'selector': '.l0', 'props': 'color:blue;'}])\n",
"print(html.to_html())"
]
},
{
Expand All @@ -1078,8 +1080,7 @@
"metadata": {},
"outputs": [],
"source": [
"from IPython.display import HTML\n",
"HTML(html)"
"html"
]
},
{
Expand Down Expand Up @@ -1655,6 +1656,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 @@ -2017,7 +2019,7 @@
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
Expand All @@ -2031,7 +2033,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.7"
"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
58 changes: 54 additions & 4 deletions pandas/io/formats/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,12 +141,19 @@ class Styler(StylerRenderer):
Object to define how values are displayed. See ``Styler.format``. If not given
uses ``pandas.options.styler.format.formatter``.

.. versionadded:: 1.4.0
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

since you are adding this to set_table_styles, do we need to add here (not a big deal but we already have a lot of options)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for preference I prefer to. most dont import Styler class but those who do might use it, and there are unlikely to be many more options added here in futures so this may be the last...

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i am confused over how this interacts with table_styles. can you either remove this enitrely or clarify.

css_class_names : dict, optional
A dict of strings used to replace the default CSS class names described below.

.. versionadded:: 1.4.0

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 +189,10 @@ 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`` argument, giving
a value such as `{"row": "MY_ROW_CLASS", "col_trim": "", "row_trim": ""}`.
"""

def __init__(
Expand All @@ -199,6 +210,7 @@ def __init__(
thousands: str | None = None,
escape: str | None = None,
formatter: ExtFormatter | None = None,
css_class_names: dict[str, str] | None = None,
):
super().__init__(
data=data,
Expand All @@ -209,6 +221,7 @@ def __init__(
caption=caption,
cell_ids=cell_ids,
precision=precision,
css=css_class_names,
)

# validate ordered args
Expand Down Expand Up @@ -1159,6 +1172,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 +1199,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 +1963,11 @@ 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,
cell_ids: bool | None = None,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we need cell_ids here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

removed/

) -> Styler:
"""
Set the table styles included within the ``<style>`` HTML element.
Expand Down Expand Up @@ -1990,6 +2007,16 @@ 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

cell_ids : bool, optional
Whether to include ids on every element of the format *T_{uuid}_rowM_colN*.

.. versionadded:: 1.4.0

Returns
-------
self : Styler
Expand All @@ -2001,6 +2028,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:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks good. in a followup can you add how this interacts with table_styles, e.g. when to use each one (via docs / examples).


.. 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 +2079,17 @@ 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 cell_ids is not None:
self.cell_ids = cell_ids

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
Loading