Skip to content

ENH: Styler.highlight_null can accepts subset argument #31350

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
Show file tree
Hide file tree
Changes from 2 commits
Commits
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ Other enhancements
^^^^^^^^^^^^^^^^^^

- :class:`Styler` may now render CSS more efficiently where multiple cells have the same styling (:issue:`30876`)
- :meth:`Styler.highlight_null` now accepts ``subset`` argument (:issue:`31345`)
-
-

Expand Down
10 changes: 7 additions & 3 deletions pandas/io/formats/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -1006,19 +1006,23 @@ def hide_columns(self, subset) -> "Styler":
def _highlight_null(v, null_color: str) -> str:
return f"background-color: {null_color}" if pd.isna(v) else ""

def highlight_null(self, null_color: str = "red") -> "Styler":
def highlight_null(self, null_color: str = "red", subset=None) -> "Styler":
"""
Shade the background ``null_color`` for missing values.

Parameters
----------
null_color : str
null_color : str, default 'red'
subset : IndexSlice, default None
Copy link
Member

Choose a reason for hiding this comment

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

This isn't an IndexSlice right? Just a label or list of labels?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It is an IndexSlice, since it calls self.applymap and applymap uses IndexSlice.

< code >

def _applymap(self, func: Callable, subset=None, **kwargs) -> "Styler":
func = partial(func, **kwargs) # applymap doesn't take kwargs?
if subset is None:
subset = pd.IndexSlice[:]
subset = _non_reducing_slice(subset)
result = self.data.loc[subset].applymap(func)
self._update_ctx(result)
return self

< proof >

image

< the doc >

Copy link
Member

Choose a reason for hiding this comment

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

The test case here though is not for an IndexSlice rather a list of labels. I think for a natural API should go with Label / Sequence of Labels as mentioned above

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It can take Label / Sequence of Labels as well, just like other Styler built-in methods.

image

Copy link
Member

Choose a reason for hiding this comment

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

Can you update this to label or list of labels?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

sure.

A valid slice for ``data`` to limit the style application to.

.. versionadded:: 1.1.0

Returns
-------
self : Styler
"""
self.applymap(self._highlight_null, null_color=null_color)
self.applymap(self._highlight_null, null_color=null_color, subset=subset)
return self

def background_gradient(
Expand Down
17 changes: 17 additions & 0 deletions pandas/tests/io/formats/test_style.py
Original file line number Diff line number Diff line change
Expand Up @@ -1091,6 +1091,23 @@ def test_highlight_null(self, null_color="red"):
expected = {(0, 0): [""], (1, 0): ["background-color: red"]}
assert result == expected

def test_highlight_null_subset(self):
# GH 31345
df = pd.DataFrame({"A": [0, np.nan], "B": [0, np.nan]})
result = (
df.style.highlight_null(null_color="red", subset=["A"])
.highlight_null(null_color="green", subset=["B"])
._compute()
.ctx
)
expected = {
(0, 0): [""],
(1, 0): ["background-color: red"],
(0, 1): [""],
(1, 1): ["background-color: green"],
}
assert result == expected

def test_nonunique_raises(self):
df = pd.DataFrame([[1, 2]], columns=["A", "A"])
with pytest.raises(ValueError):
Expand Down