Skip to content

BUG: Fix style.background_gradient() for nullable dtype (ex: Int64) series with pd.NA values #50713

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 10 commits into from
Jan 16, 2023
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v2.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1079,7 +1079,7 @@ ExtensionArray

Styler
^^^^^^
-
- Fix :meth:`~pandas.io.formats.style.Styler.background_gradient` for nullable dtype :class:`Series` with ``NA`` values (:issue:`50712`)
-

Metadata
Expand Down
2 changes: 1 addition & 1 deletion pandas/io/formats/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -3619,7 +3619,7 @@ def _background_gradient(
Color background in a range according to the data or a gradient map
"""
if gmap is None: # the data is used the gmap
gmap = data.to_numpy(dtype=float)
gmap = data.to_numpy(dtype=float, na_value=np.nan)
else: # else validate gmap against the underlying data
gmap = _validate_apply_axis_arg(gmap, "gmap", float, data)

Expand Down
10 changes: 10 additions & 0 deletions pandas/tests/io/formats/style/test_matplotlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,16 @@ def test_background_gradient_gmap_wrong_series(styler_blank):
styler_blank.background_gradient(gmap=gmap, axis=None)._compute()


def test_background_gradient_nullable_dtypes():
# GH 50712
df1 = DataFrame([[1], [0], [np.nan]], dtype=float)
df2 = DataFrame([[1], [0], [None]], dtype="Int64")

ctx1 = df1.style.background_gradient()._compute().ctx
ctx2 = df2.style.background_gradient()._compute().ctx
assert ctx1 == ctx2


@pytest.mark.parametrize(
"cmap",
["PuBu", mpl.colormaps["PuBu"]],
Expand Down