8000 ENH: `Styler.apply_index` and `Styler.applymap_index` for conditional formatting of column/index headers by attack68 · Pull Request #41893 · pandas-dev/pandas · GitHub
[go: up one dir, main page]

Skip to content

ENH: Styler.apply_index and Styler.applymap_index for conditional formatting of column/index headers #41893

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 31 commits into from
Aug 11, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
ece8855
add apply across index
attack68 Jun 9, 2021
a3a88e5
add applymap across index
attack68 Jun 9, 2021
066e4f3
improve docs
attack68 Jun 9, 2021
50dbcc7
Merge remote-tracking branch 'upstream/master' into styler_apply_inde…
attack68 Jun 11, 2021
ef5839f
Merge remote-tracking branch 'upstream/master' into styler_apply_inde…
attack68 Jun 12, 2021
5e4c1c0
add column header styling and amend tests
attack68 Jun 12, 2021
20ac7e0
doc sharing
attack68 Jun 13, 2021
26c5340
doc fix
attack68 Jun 13, 2021
2437b72
doc fix
attack68 Jun 13, 2021
312a6e6
collapse the cellstyle maps
attack68 Jun 13, 2021
553426f
add basic test
attack68 Jun 13, 2021
f01dfee
add basic test
attack68 Jun 13, 2021
f940165
parametrise tests
attack68 Jun 13, 2021
8000
6f5b46c
test for raises ValueError
attack68 Jun 13, 2021
75cf6ca
test html working
attack68 Jun 13, 2021
d654139
test html working
attack68 Jun 13, 2021
728091a
Merge remote-tracking branch 'upstream/master' into styler_apply_inde…
attack68 Jun 14, 2021
17787ef
whats new 1.4.0
attack68 Jun 14, 2021
248de0d
Merge remote-tracking branch 'upstream/master' into styler_apply_inde…
attack68 Jun 20, 2021
321458e
Merge remote-tracking branch 'upstream/master' into styler_apply_inde…
attack68 Jun 29, 2021
ed58798
Merge remote-tracking branch 'upstream/master' into styler_apply_inde…
attack68 Jul 13, 2021
8d8e88f
update tests
attack68 Jul 14, 2021
e17d766
Merge remote-tracking branch 'upstream/master' into styler_apply_inde…
attack68 Jul 30, 2021
f70bf65
Merge remote-tracking branch 'upstream/master' into styler_apply_inde…
attack68 Aug 6, 2021
3dfe6d5
Merge remote-tracking branch 'upstream/master' into styler_apply_inde…
attack68 Aug 9, 2021
81f3a3c
rename: applymap_header -->> applymap_index
attack68 Aug 9, 2021
e709777
skip doctests
attack68 Aug 9, 2021
1e6efea
Merge remote-tracking branch 'upstream/master' into styler_apply_inde…
attack68 Aug 9, 2021
ab237b0
rename levels -->> level
attack68 Aug 9, 2021
9b7ec06
update user guide
attack68 Aug 9, 2021
1c7ef8b
Merge remote-tracking branch 'upstream/master' into styler_apply_inde…
attack68 Aug 11, 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
Prev Previous commit
Next Next commit
rename: applymap_header -->> applymap_index
  • Loading branch information
attack68 committed Aug 9, 2021
commit 81f3a3c04629f0c162dc3519798d8217de9aca25
4 changes: 2 additions & 2 deletions doc/source/reference/style.rst
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ Style application

Styler.apply
Styler.applymap
Styler.apply_header
Styler.applymap_header
Styler.apply_index
Styler.applymap_index
Styler.format
Styler.hide_index
Styler.hide_columns
Expand Down
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.4.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ Other enhancements
- :meth:`Series.ewm`, :meth:`DataFrame.ewm`, now support a ``method`` argument with a ``'table'`` option that performs the windowing operation over an entire :class:`DataFrame`. See :ref:`Window Overview <window.overview>` for performance and functional benefits (:issue:`42273`)
- Added ``sparse_index`` and ``sparse_columns`` keyword arguments to :meth:`.Styler.to_html` (:issue:`41946`)
- Added keyword argument ``environment`` to :meth:`.Styler.to_latex` also allowing a specific "longtable" entry with a separate jinja2 template (:issue:`41866`)
- :meth:`.Styler.apply_header` and :meth:`.Styler.applymap_header` added to allow conditional styling of index and column header values (:issue:`41893`)
- :meth:`.Styler.apply_index` and :meth:`.Styler.applymap_index` added to allow conditional styling of index and column header values (:issue:`41893`)
Copy link
Contributor

Choose a reason for hiding this comment

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

might be worth creating a styler sub-section in other enhancements (followon)

- :meth:`.GroupBy.cummin` and :meth:`.GroupBy.cummax` now support the argument ``skipna`` (:issue:`34047`)
-

Expand Down
26 changes: 13 additions & 13 deletions pandas/io/formats/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -1199,8 +1199,8 @@ def apply(

See Also
--------
Styler.applymap_header: Apply a CSS-styling function to headers elementwise.
Styler.apply_header: Apply a CSS-styling function to headers level-wise.
Styler.applymap_index: Apply a CSS-styling function to headers elementwise.
Styler.apply_index: Apply a CSS-styling function to headers level-wise.
Styler.applymap: Apply a CSS-styling function elementwise.

Notes
Expand Down Expand Up @@ -1244,7 +1244,7 @@ def apply(
)
return self

def _apply_header(
def _apply_index(
self,
func: Callable[..., Styler],
axis: int | str = 0,
Expand Down Expand Up @@ -1288,7 +1288,7 @@ def _apply_header(
ret='np.where(s == "B", "background-color: yellow;", "")',
ret2='["background-color: yellow;" if "x" in v else "" for v in s]',
)
def apply_header(
def apply_index(
self,
func: Callable[..., Styler],
axis: int | str = 0,
Expand Down Expand Up @@ -1319,7 +1319,7 @@ def apply_header(

See Also
--------
Styler.{alt}_header: Apply a CSS-styling function to headers {altwise}.
Styler.{alt}_index: Apply a CSS-styling function to headers {altwise}.
Styler.apply: Apply a CSS-styling function column-wise, row-wise, or table-wise.
Styler.applymap: Apply a CSS-styling function elementwise.

Expand All @@ -1336,7 +1336,7 @@ def apply_header(
>>> df = pd.DataFrame([[1,2], [3,4]], index=["A", "B"])
>>> def color_b(s):
... return {ret}
>>> df.style.{this}_header(color_b)
>>> df.style.{this}_index(color_b)

.. figure:: ../../_static/style/appmaphead1.png

Expand All @@ -1346,21 +1346,21 @@ def apply_header(
>>> df = pd.DataFrame([np.arange(8)], columns=midx)
>>> def highlight_x({var}):
... return {ret2}
>>> df.style.{this}_header(highlight_x, axis="columns", levels=[0, 2])
>>> df.style.{this}_index(highlight_x, axis="columns", levels=[0, 2])

.. figure:: ../../_static/style/appmaphead2.png
"""
self._todo.append(
(
lambda instance: getattr(instance, "_apply_header"),
lambda instance: getattr(instance, "_apply_index"),
(func, axis, levels, "apply"),
kwargs,
)
)
return self

@doc(
apply_header,
apply_index,
this="applymap",
wise="elementwise",
alt="apply",
Expand All @@ -1373,7 +1373,7 @@ def apply_header(
ret='"background-color: yellow;" if v == "B" else None',
ret2='"background-color: yellow;" if "x" in v else None',
)
def applymap_header(
def applymap_index(
self,
func: Callable[..., Styler],
axis: int | str = 0,
Expand All @@ -1382,7 +1382,7 @@ def applymap_header(
) -> Styler:
self._todo.append(
(
lambda instance: getattr(instance, "_apply_header"),
lambda instance: getattr(instance, "_apply_index"),
(func, axis, levels, "applymap"),
kwargs,
)
Expand Down Expand Up @@ -1425,8 +1425,8 @@ def applymap(

See Also
--------
Styler.applymap_header: Apply a CSS-styling function to headers elementwise.
Styler.apply_header: Apply a CSS-styling function to headers level-wise.
Styler.applymap_index: Apply a CSS-styling function to headers elementwise.
Styler.apply_index: Apply a CSS-styling function to headers level-wise.
Styler.apply: Apply a CSS-styling function column-wise, row-wise, or table-wise.

Notes
Expand Down
1 change: 0 additions & 1 deletion pandas/io/formats/style_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -500,7 +500,6 @@ def _translate_body(
f"{row_heading_class} level{c} row{r}",
value,
(_is_visible(r, c, idx_lengths) and not self.hide_index_[c]),
id=f"level{c}_row{r}",
attributes=(
f'rowspan="{idx_lengths.get((c, r), 0)}"'
if idx_lengths.get((c, r), 0) > 1
Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/io/formats/style/test_html.py
Original file line number Diff line number Diff line change
Expand Up @@ -406,9 +406,9 @@ def test_applymap_header_cell_ids(styler, index, columns):
func = lambda v: "attr: val;"
styler.uuid, styler.cell_ids = "", False
if index:
styler.applymap_header(func, axis="index")
styler.applymap_index(func, axis="index")
if columns:
styler.applymap_header(func, axis="columns")
styler.applymap_index(func, axis="columns")

result = styler.to_html()

Expand Down
10 changes: 5 additions & 5 deletions pandas/tests/io/formats/style/test_style.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ def mi_styler_comp(mi_styler):
mi_styler.set_table_attributes('class="box"')
mi_styler.format(na_rep="MISSING", precision=3)
mi_styler.highlight_max(axis=None)
mi_styler.applymap_header(lambda x: "color: white;", axis=0)
mi_styler.applymap_header(lambda x: "color: black;", axis=1)
mi_styler.applymap_index(lambda x: "color: white;", axis=0)
mi_styler.applymap_index(lambda x: "color: black;", axis=1)
mi_styler.set_td_classes(
DataFrame(
[["a", "b"], ["a", "c"]], index=mi_styler.index, columns=mi_styler.columns
Expand Down Expand Up @@ -308,7 +308,7 @@ def test_apply_map_header(method, axis):
}

# test execution added to todo
result = getattr(df.style, f"{method}_header")(func[method], axis=axis)
result = getattr(df.style, f"{method}_index")(func[method], axis=axis)
assert len(result._todo) == 1
assert len(getattr(result, f"ctx_{axis}")) == 0

Expand All @@ -328,15 +328,15 @@ def test_apply_map_header_mi(mi_styler, method, axis):
"apply": lambda s: ["attr: val;" if "b" in v else "" for v in s],
"applymap": lambda v: "attr: val" if "b" in v else "",
}
result = getattr(mi_styler, f"{method}_header")(func[method], axis=axis)._compute()
result = getattr(mi_styler, f"{method}_index")(func[method], axis=axis)._compute()
expected = {(1, 1): [("attr", "val")]}
assert getattr(result, f"ctx_{axis}") == expected


def test_apply_map_header_raises(mi_styler):
# GH 41893
with pytest.raises(ValueError, match="`axis` must be one of 0, 1, 'index', 'col"):
mi_styler.applymap_header(lambda v: "attr: val;", axis="bad-axis")._compute()
mi_styler.applymap_index(lambda v: "attr: val;", axis="bad-axis")._compute()


class TestStyler:
Expand Down
0