Skip to content

Commit f956bb5

Browse files
authored
BUG: Series[sparse].where losing fill_value (#45691)
1 parent f554f22 commit f956bb5

File tree

3 files changed

+17
-2
lines changed

3 files changed

+17
-2
lines changed

doc/source/whatsnew/v1.5.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -316,7 +316,7 @@ Reshaping
316316

317317
Sparse
318318
^^^^^^
319-
-
319+
- Bug in :meth:`Series.where` and :meth:`DataFrame.where` with ``SparseDtype`` failing to retain the array's ``fill_value`` (:issue:`45691`)
320320
-
321321

322322
ExtensionArray

pandas/core/arrays/sparse/array.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1355,7 +1355,8 @@ def _where(self, mask, value):
13551355
# NB: may not preserve dtype, e.g. result may be Sparse[float64]
13561356
# while self is Sparse[int64]
13571357
naive_implementation = np.where(mask, self, value)
1358-
result = type(self)._from_sequence(naive_implementation)
1358+
dtype = SparseDtype(naive_implementation.dtype, fill_value=self.fill_value)
1359+
result = type(self)._from_sequence(naive_implementation, dtype=dtype)
13591360
return result
13601361

13611362
# ------------------------------------------------------------------------

pandas/tests/arrays/sparse/test_array.py

+14
Original file line numberDiff line numberDiff line change
@@ -880,6 +880,20 @@ def test_generator_warnings(self):
880880
pass
881881
assert len(w) == 0
882882

883+
def test_where_retain_fill_value(self):
884+
# GH#45691 don't lose fill_value on _where
885+
arr = SparseArray([np.nan, 1.0], fill_value=0)
886+
887+
mask = np.array([True, False])
888+
889+
res = arr._where(~mask, 1)
890+
exp = SparseArray([1, 1.0], fill_value=0)
891+
tm.assert_sp_array_equal(res, exp)
892+
893+
ser = pd.Series(arr)
894+
res = ser.where(~mask, 1)
895+
tm.assert_series_equal(res, pd.Series(exp))
896+
883897
def test_fillna(self):
884898
s = SparseArray([1, np.nan, np.nan, 3, np.nan])
885899
res = s.fillna(-1)

0 commit comments

Comments
 (0)