Skip to content

BUG: Series[sparse].where losing fill_value #45691

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 3 commits into from
Jan 29, 2022
Merged
Show file tree
Hide file tree
Changes from all 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.5.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ Reshaping

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

ExtensionArray
Expand Down
3 changes: 2 additions & 1 deletion pandas/core/arrays/sparse/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -1355,7 +1355,8 @@ def _where(self, mask, value):
# NB: may not preserve dtype, e.g. result may be Sparse[float64]
# while self is Sparse[int64]
naive_implementation = np.where(mask, self, value)
result = type(self)._from_sequence(naive_implementation)
dtype = SparseDtype(naive_implementation.dtype, fill_value=self.fill_value)
result = type(self)._from_sequence(naive_implementation, dtype=dtype)
return result

# ------------------------------------------------------------------------
Expand Down
14 changes: 14 additions & 0 deletions pandas/tests/arrays/sparse/test_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -880,6 +880,20 @@ def test_generator_warnings(self):
pass
assert len(w) == 0

def test_where_retain_fill_value(self):
# GH#45691 don't lose fill_value on _where
arr = SparseArray([np.nan, 1.0], fill_value=0)

mask = np.array([True, False])

res = arr._where(~mask, 1)
exp = SparseArray([1, 1.0], fill_value=0)
tm.assert_sp_array_equal(res, exp)

ser = pd.Series(arr)
res = ser.where(~mask, 1)
tm.assert_series_equal(res, pd.Series(exp))

def test_fillna(self):
s = SparseArray([1, np.nan, np.nan, 3, np.nan])
res = s.fillna(-1)
Expand Down