diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index b259f182a1197..1ae76984484af 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -185,7 +185,7 @@ Timezones Numeric ^^^^^^^ -- +- Bug in operations with array-likes with ``dtype="boolean"`` and :attr:`NA` incorrectly altering the array in-place (:issue:`45421`) - Conversion diff --git a/pandas/core/arrays/boolean.py b/pandas/core/arrays/boolean.py index 0ba98e4a377ae..5e72b2b3af631 100644 --- a/pandas/core/arrays/boolean.py +++ b/pandas/core/arrays/boolean.py @@ -494,7 +494,8 @@ def _arith_method(self, other, op): if mask is None: mask = self._mask if other is libmissing.NA: - mask |= True + # GH#45421 don't alter inplace + mask = mask | True else: mask = self._mask | mask diff --git a/pandas/tests/arrays/masked/test_arithmetic.py b/pandas/tests/arrays/masked/test_arithmetic.py index ab6e5110422ca..61775a2b94107 100644 --- a/pandas/tests/arrays/masked/test_arithmetic.py +++ b/pandas/tests/arrays/masked/test_arithmetic.py @@ -47,7 +47,7 @@ def test_array_scalar_like_equivalence(data, all_arithmetic_operators): tm.assert_extension_array_equal(result, expected) -def test_array_NA(data, all_arithmetic_operators, request): +def test_array_NA(data, all_arithmetic_operators): data, _ = data op = tm.get_op_from_name(all_arithmetic_operators) check_skip(data, all_arithmetic_operators) @@ -55,8 +55,14 @@ def test_array_NA(data, all_arithmetic_operators, request): scalar = pd.NA scalar_array = pd.array([pd.NA] * len(data), dtype=data.dtype) + mask = data._mask.copy() result = op(data, scalar) + # GH#45421 check op doesn't alter data._mask inplace + tm.assert_numpy_array_equal(mask, data._mask) + expected = op(data, scalar_array) + tm.assert_numpy_array_equal(mask, data._mask) + tm.assert_extension_array_equal(result, expected)