diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 3a0e1b7568c91..a9ad369ed7b3a 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -814,6 +814,7 @@ Other - Bug in :meth:`Styler.background_gradient` where text-color was not determined correctly (:issue:`39888`) - Bug in :class:`Styler` where multiple elements in CSS-selectors were not correctly added to ``table_styles`` (:issue:`39942`) - Bug in :class:`.Styler` where copying from Jupyter dropped top left cell and misaligned headers (:issue:`12147`) +- Bug in :class:`.Styler.where` where ``kwargs`` were not passed to the applicable callable (:issue:`40845`) - Bug in :meth:`DataFrame.equals`, :meth:`Series.equals`, :meth:`Index.equals` with object-dtype containing ``np.datetime64("NaT")`` or ``np.timedelta64("NaT")`` (:issue:`39650`) - Bug in :func:`pandas.util.show_versions` where console JSON output was not proper JSON (:issue:`39701`) - Bug in :meth:`DataFrame.convert_dtypes` incorrectly raised ValueError when called on an empty DataFrame (:issue:`40393`) diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 267606461f003..711ac64b4e69e 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -1086,7 +1086,8 @@ def where( Parameters ---------- cond : callable - ``cond`` should take a scalar and return a boolean. + ``cond`` should take a scalar, and optional keyword arguments, and return + a boolean. value : str Applied when ``cond`` returns true. other : str @@ -1117,7 +1118,8 @@ def where( other = "" return self.applymap( - lambda val: value if cond(val) else other, subset=subset, **kwargs + lambda val: value if cond(val, **kwargs) else other, + subset=subset, ) def set_precision(self, precision: int) -> Styler: diff --git a/pandas/tests/io/formats/style/test_style.py b/pandas/tests/io/formats/style/test_style.py index 3422eb9dc64b7..2634fc685156c 100644 --- a/pandas/tests/io/formats/style/test_style.py +++ b/pandas/tests/io/formats/style/test_style.py @@ -557,6 +557,21 @@ def g(x): expected = self.df.style.applymap(g, subset=slice_)._compute().ctx assert result == expected + def test_where_kwargs(self): + df = DataFrame([[1, 2], [3, 4]]) + + def f(x, val): + return x > val + + result = df.style.where(f, "color:green;", "color:red;", val=2)._compute().ctx + expected = { + (0, 0): [("color", "red")], + (0, 1): [("color", "red")], + (1, 0): [("color", "green")], + (1, 1): [("color", "green")], + } + assert result == expected + def test_empty(self): df = DataFrame({"A": [1, 0]}) s = df.style