diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 8b2b3a09f8c87..bb8c8969693a9 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -240,7 +240,7 @@ Sparse ExtensionArray ^^^^^^^^^^^^^^ -- +- Bug in :class:`arrays.PandasArray` when setting a scalar string (:issue:`28118`, :issue:`28150`). - diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py index 4e2e37d88eb9a..32da0199e28f8 100644 --- a/pandas/core/arrays/numpy_.py +++ b/pandas/core/arrays/numpy_.py @@ -235,15 +235,8 @@ def __setitem__(self, key, value): if not lib.is_scalar(value): value = np.asarray(value) - values = self._ndarray - t = np.result_type(value, values) - if t != self._ndarray.dtype: - values = values.astype(t, casting="safe") - values[key] = value - self._dtype = PandasDtype(t) - self._ndarray = values - else: - self._ndarray[key] = value + value = np.asarray(value, dtype=self._ndarray.dtype) + self._ndarray[key] = value def __len__(self) -> int: return len(self._ndarray) diff --git a/pandas/tests/arrays/test_numpy.py b/pandas/tests/arrays/test_numpy.py index c4c1696ede6e6..7a150c35fea09 100644 --- a/pandas/tests/arrays/test_numpy.py +++ b/pandas/tests/arrays/test_numpy.py @@ -211,3 +211,18 @@ def test_basic_binop(): result = x + x expected = PandasArray(np.array([2, 4, 6])) tm.assert_extension_array_equal(result, expected) + + +@pytest.mark.parametrize("dtype", [None, object]) +def test_setitem_object_typecode(dtype): + arr = PandasArray(np.array(["a", "b", "c"], dtype=dtype)) + arr[0] = "t" + expected = PandasArray(np.array(["t", "b", "c"], dtype=dtype)) + tm.assert_extension_array_equal(arr, expected) + + +def test_setitem_no_coercion(): + # https://github.com/pandas-dev/pandas/issues/28150 + arr = PandasArray(np.array([1, 2, 3])) + with pytest.raises(ValueError, match="int"): + arr[0] = "a"