Skip to content

REGR: styler.highlight_min/max did not ignore pd.NA and caused error #42861

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 4 commits into from
Aug 4, 2021
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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.3.2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ Fixed regressions
- Regression in :meth:`DataFrame.drop` does nothing if :class:`MultiIndex` has duplicates and indexer is a tuple or list of tuples (:issue:`42771`)
- Fixed regression where :meth:`pandas.read_csv` raised a ``ValueError`` when parameters ``names`` and ``prefix`` were both set to None (:issue:`42387`)
- Fixed regression in comparisons between :class:`Timestamp` object and ``datetime64`` objects outside the implementation bounds for nanosecond ``datetime64`` (:issue:`42794`)
-
- Fixed regression in :meth:`.Styler.highlight_min` and :meth:`.Styler.highlight_max` where ``pandas.NA`` was not successfully ignored (:issue:`42650`)

.. ---------------------------------------------------------------------------

Expand Down
12 changes: 10 additions & 2 deletions pandas/io/formats/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -2348,7 +2348,11 @@ def highlight_max(
"""

def f(data: FrameOrSeries, props: str) -> np.ndarray:
return np.where(data == np.nanmax(data.to_numpy()), props, "")
arg = {"skipna": True}
Copy link
Contributor

Choose a reason for hiding this comment

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

i think actually just passing the arg is better here e.g. max(skipna=True) as more readable

Copy link
Contributor Author

Choose a reason for hiding this comment

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

i refactored this, pulling the function out, have a relook

if isinstance(data, DataFrame):
return np.where(data == data.max(**arg).max(**arg), props, "")
else:
return np.where(data == data.max(**arg), props, "")

if props is None:
props = f"background-color: {color};"
Expand Down Expand Up @@ -2399,7 +2403,11 @@ def highlight_min(
"""

def f(data: FrameOrSeries, props: str) -> np.ndarray:
return np.where(data == np.nanmin(data.to_numpy()), props, "")
arg = {"skipna": True}
if isinstance(data, DataFrame):
return np.where(data == data.min(**arg).min(**arg), props, "")
else:
return np.where(data == data.min(**arg), props, "")

if props is None:
props = f"background-color: {color};"
Expand Down
26 changes: 22 additions & 4 deletions pandas/tests/io/formats/style/test_highlight.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
import pytest

from pandas import (
NA,
DataFrame,
IndexSlice,
)
import pandas._testing as tm

pytest.importorskip("jinja2")

Expand Down Expand Up @@ -55,9 +55,7 @@ def test_highlight_minmax_basic(df, f):
}
if f == "highlight_min":
df = -df
with tm.assert_produces_warning(RuntimeWarning):
# All-NaN slice encountered
result = getattr(df.style, f)(axis=1, color="red")._compute().ctx
result = getattr(df.style, f)(axis=1, color="red")._compute().ctx
assert result == expected


Expand All @@ -78,6 +76,26 @@ def test_highlight_minmax_ext(df, f, kwargs):
assert result == expected


@pytest.mark.parametrize("f", ["highlight_min", "highlight_max"])
@pytest.mark.parametrize("axis", [None, 0, 1])
def test_highlight_minmax_nulls(f, axis):
# GH 42750
expected = {
(1, 0): [("background-color", "yellow")],
(1, 1): [("background-color", "yellow")],
}
if axis == 1:
expected.update({(2, 1): [("background-color", "yellow")]})

if f == "highlight_max":
df = DataFrame({"a": [NA, 1, None], "b": [np.nan, 1, -1]})
else:
df = DataFrame({"a": [NA, -1, None], "b": [np.nan, -1, 1]})

result = getattr(df.style, f)(axis=axis)._compute().ctx
assert result == expected


@pytest.mark.parametrize(
"kwargs",
[
Expand Down