Skip to content

Commit 0cea15b

Browse files
mzeitlin11rhshadrach
authored andcommitted
BUG/ERR: sparse array cmp methods mismatched len (pandas-dev#43863)
1 parent d412b4f commit 0cea15b

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

doc/source/whatsnew/v1.4.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -511,6 +511,7 @@ Sparse
511511
- Bug in :meth:`DataFrame.sparse.to_coo` raising ``AttributeError`` when column names are not unique (:issue:`29564`)
512512
- Bug in :meth:`SparseArray.max` and :meth:`SparseArray.min` raising ``ValueError`` for arrays with 0 non-null elements (:issue:`43527`)
513513
- Bug in :meth:`DataFrame.sparse.to_coo` silently converting non-zero fill values to zero (:issue:`24817`)
514+
- 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`)
514515
-
515516

516517
ExtensionArray

pandas/core/arrays/sparse/array.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -1642,11 +1642,14 @@ def _cmp_method(self, other, op) -> SparseArray:
16421642

16431643
if isinstance(other, np.ndarray):
16441644
# TODO: make this more flexible than just ndarray...
1645-
if len(self) != len(other):
1646-
raise AssertionError(f"length mismatch: {len(self)} vs. {len(other)}")
16471645
other = SparseArray(other, fill_value=self.fill_value)
16481646

16491647
if isinstance(other, SparseArray):
1648+
if len(self) != len(other):
1649+
raise ValueError(
1650+
f"operands have mismatched length {len(self)} and {len(other)}"
1651+
)
1652+
16501653
op_name = op.__name__.strip("_")
16511654
return _sparse_array_op(self, other, op, op_name)
16521655
else:

pandas/tests/arrays/sparse/test_arithmetics.py

+8
Original file line numberDiff line numberDiff line change
@@ -529,3 +529,11 @@ def test_unary_op(op, fill_value):
529529
result = op(sparray)
530530
expected = SparseArray(op(arr), fill_value=op(fill_value))
531531
tm.assert_sp_array_equal(result, expected)
532+
533+
534+
@pytest.mark.parametrize("cons", [list, np.array, SparseArray])
535+
def test_mismatched_length_cmp_op(cons):
536+
left = SparseArray([True, True])
537+
right = cons([True, True, True])
538+
with pytest.raises(ValueError, match="operands have mismatched length"):
539+
left & right

0 commit comments

Comments
 (0)