Skip to content

Commit c128ffa

Browse files
dhendryphofl
andauthored
BUG: Fix style.background_gradient() for nullable dtype (ex: Int64) series with pd.NA values (#50713)
* Fix style.background_gradient() for Int64 series with null values * Update whatsnew * Use the correct issue number * Response to comments: move entry in whatsnew, include github issue in test, and check results against expected values from a regular float series * Update doc/source/whatsnew/v2.0.0.rst Co-authored-by: Patrick Hoefler <61934744+phofl@users.noreply.github.com> Co-authored-by: Patrick Hoefler <61934744+phofl@users.noreply.github.com>
1 parent 8849f18 commit c128ffa

File tree

3 files changed

+12
-2
lines changed

3 files changed

+12
-2
lines changed

doc/source/whatsnew/v2.0.0.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1080,7 +1080,7 @@ ExtensionArray
10801080

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

10861086
Metadata

pandas/io/formats/style.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3619,7 +3619,7 @@ def _background_gradient(
36193619
Color background in a range according to the data or a gradient map
36203620
"""
36213621
if gmap is None: # the data is used the gmap
3622-
gmap = data.to_numpy(dtype=float)
3622+
gmap = data.to_numpy(dtype=float, na_value=np.nan)
36233623
else: # else validate gmap against the underlying data
36243624
gmap = _validate_apply_axis_arg(gmap, "gmap", float, data)
36253625

pandas/tests/io/formats/style/test_matplotlib.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,16 @@ def test_background_gradient_gmap_wrong_series(styler_blank):
260260
styler_blank.background_gradient(gmap=gmap, axis=None)._compute()
261261

262262

263+
def test_background_gradient_nullable_dtypes():
264+
# GH 50712
265+
df1 = DataFrame([[1], [0], [np.nan]], dtype=float)
266+
df2 = DataFrame([[1], [0], [None]], dtype="Int64")
267+
268+
ctx1 = df1.style.background_gradient()._compute().ctx
269+
ctx2 = df2.style.background_gradient()._compute().ctx
270+
assert ctx1 == ctx2
271+
272+
263273
@pytest.mark.parametrize(
264274
"cmap",
265275
["PuBu", mpl.colormaps["PuBu"]],

0 commit comments

Comments
 (0)