Skip to content

BUG: SparseArray.__floordiv__ not matching non-Sparse Series behavior #44928

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
Dec 19, 2021
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.4.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -825,6 +825,7 @@ Sparse
- Bug in :meth:`SparseArray.max` and :meth:`SparseArray.min` raising ``ValueError`` for arrays with 0 non-null elements (:issue:`43527`)
- Bug in :meth:`DataFrame.sparse.to_coo` silently converting non-zero fill values to zero (:issue:`24817`)
- Bug in :class:`SparseArray` comparison methods with an array-like operand of mismatched length raising ``AssertionError`` or unclear ``ValueError`` depending on the input (:issue:`43863`)
- Bug in :class:`SparseArray` arithmetic methods ``floordiv`` and ``mod`` behaviors when dividing by zero not matching the non-sparse :class:`Series` behavior (:issue:`38172`)
-

ExtensionArray
Expand Down
5 changes: 5 additions & 0 deletions pandas/_libs/sparse_op_helper.pxi.in
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@ cdef inline sparse_t __mod__(sparse_t a, sparse_t b):
cdef inline sparse_t __floordiv__(sparse_t a, sparse_t b):
if b == 0:
if sparse_t is float64_t:
# Match non-sparse Series behavior implemented in mask_zero_div_zero
if a > 0:
return INF
elif a < 0:
return -INF
return NaN
else:
return 0
Expand Down
10 changes: 10 additions & 0 deletions pandas/core/arrays/sparse/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,16 @@ def _sparse_array_op(
left_sp_values = left.sp_values
right_sp_values = right.sp_values

if (
name in ["floordiv", "mod"]
and (right == 0).any()
and left.dtype.kind in ["i", "u"]
):
# Match the non-Sparse Series behavior
opname = f"sparse_{name}_float64"
left_sp_values = left_sp_values.astype("float64")
right_sp_values = right_sp_values.astype("float64")

sparse_op = getattr(splib, opname)

with np.errstate(all="ignore"):
Expand Down
40 changes: 15 additions & 25 deletions pandas/tests/arrays/sparse/test_arithmetics.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,26 +34,23 @@ class TestSparseArrayArithmetics:
def _assert(self, a, b):
tm.assert_numpy_array_equal(a, b)

def _check_numeric_ops(self, a, b, a_dense, b_dense, mix, op):
def _check_numeric_ops(self, a, b, a_dense, b_dense, mix: bool, op):
# Check that arithmetic behavior matches non-Sparse Series arithmetic

if isinstance(a_dense, np.ndarray):
expected = op(pd.Series(a_dense), b_dense).values
elif isinstance(b_dense, np.ndarray):
expected = op(a_dense, pd.Series(b_dense)).values
else:
raise NotImplementedError

with np.errstate(invalid="ignore", divide="ignore"):
if mix:
result = op(a, b_dense).to_dense()
else:
result = op(a, b).to_dense()

if op in [operator.truediv, ops.rtruediv]:
# pandas uses future division
expected = op(a_dense * 1.0, b_dense)
else:
expected = op(a_dense, b_dense)

if op in [operator.floordiv, ops.rfloordiv]:
# Series sets 1//0 to np.inf, which SparseArray does not do (yet)
mask = np.isinf(expected)
if mask.any():
expected[mask] = np.nan

self._assert(result, expected)
self._assert(result, expected)

def _check_bool_result(self, res):
assert isinstance(res, self._klass)
Expand Down Expand Up @@ -125,7 +122,7 @@ def test_float_scalar(
):
op = all_arithmetic_functions

if not np_version_under1p20:
if np_version_under1p20:
if op in [operator.floordiv, ops.rfloordiv]:
if op is operator.floordiv and scalar != 0:
pass
Expand Down Expand Up @@ -158,9 +155,7 @@ def test_float_scalar_comparison(self, kind):
self._check_comparison_ops(a, 0, values, 0)
self._check_comparison_ops(a, 3, values, 3)

def test_float_same_index_without_nans(
self, kind, mix, all_arithmetic_functions, request
):
def test_float_same_index_without_nans(self, kind, mix, all_arithmetic_functions):
# when sp_index are the same
op = all_arithmetic_functions

Expand All @@ -178,13 +173,12 @@ def test_float_same_index_with_nans(
op = all_arithmetic_functions

if (
not np_version_under1p20
np_version_under1p20
and op is ops.rfloordiv
and not (mix and kind == "block")
):
mark = pytest.mark.xfail(raises=AssertionError, reason="GH#38172")
request.node.add_marker(mark)

values = self._base([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])
rvalues = self._base([np.nan, 2, 3, 4, np.nan, 0, 1, 3, 2, np.nan])

Expand Down Expand Up @@ -360,11 +354,7 @@ def test_bool_array_logical(self, kind, fill_value):
def test_mixed_array_float_int(self, kind, mix, all_arithmetic_functions, request):
op = all_arithmetic_functions

if (
not np_version_under1p20
and op in [operator.floordiv, ops.rfloordiv]
and mix
):
if np_version_under1p20 and op in [operator.floordiv, ops.rfloordiv] and mix:
mark = pytest.mark.xfail(raises=AssertionError, reason="GH#38172")
request.node.add_marker(mark)

Expand Down