Skip to content

Commit b002086

Browse files
committed
ENH: Styler.highlight_null can accepts subset argument
1 parent 0c50950 commit b002086

File tree

3 files changed

+24
-2
lines changed

3 files changed

+24
-2
lines changed

doc/source/whatsnew/v1.1.0.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ Other enhancements
4242
^^^^^^^^^^^^^^^^^^
4343

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

pandas/io/formats/style.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1006,19 +1006,23 @@ def hide_columns(self, subset) -> "Styler":
10061006
def _highlight_null(v, null_color: str) -> str:
10071007
return f"background-color: {null_color}" if pd.isna(v) else ""
10081008

1009-
def highlight_null(self, null_color: str = "red") -> "Styler":
1009+
def highlight_null(self, null_color: str = "red", subset=None) -> "Styler":
10101010
"""
10111011
Shade the background ``null_color`` for missing values.
10121012
10131013
Parameters
10141014
----------
10151015
null_color : str
1016+
subset : IndexSlice, default None
1017+
A valid slice for ``data`` to limit the style application to.
1018+
1019+
.. versionadded:: 1.1.0
10161020
10171021
Returns
10181022
-------
10191023
self : Styler
10201024
"""
1021-
self.applymap(self._highlight_null, null_color=null_color)
1025+
self.applymap(self._highlight_null, null_color=null_color, subset=subset)
10221026
return self
10231027

10241028
def background_gradient(

pandas/tests/io/formats/test_style.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1091,6 +1091,23 @@ def test_highlight_null(self, null_color="red"):
10911091
expected = {(0, 0): [""], (1, 0): ["background-color: red"]}
10921092
assert result == expected
10931093

1094+
def test_highlight_null_subset(self):
1095+
# GH 31345
1096+
df = pd.DataFrame({"A": [0, np.nan], "B": [0, np.nan]})
1097+
result = (
1098+
df.style.highlight_null(null_color="red", subset=["A"])
1099+
.highlight_null(null_color="green", subset=["B"])
1100+
._compute()
1101+
.ctx
1102+
)
1103+
expected = {
1104+
(0, 0): [""],
1105+
(1, 0): ["background-color: red"],
1106+
(0, 1): [""],
1107+
(1, 1): ["background-color: green"],
1108+
}
1109+
assert result == expected
1110+
10941111
def test_nonunique_raises(self):
10951112
df = pd.DataFrame([[1, 2]], columns=["A", "A"])
10961113
with pytest.raises(ValueError):

0 commit comments

Comments
 (0)