Skip to content

Commit caea50e

Browse files
TomAugspurgerproost
authored andcommitted
BUG: Fixed PandasArray.__setitem__ with str (pandas-dev#28119)
* BUG: Fixed PandasArray.__setitem__ with str Closes pandas-dev#28118
1 parent c2d32ac commit caea50e

File tree

3 files changed

+18
-10
lines changed

3 files changed

+18
-10
lines changed

doc/source/whatsnew/v1.0.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -240,7 +240,7 @@ Sparse
240240
ExtensionArray
241241
^^^^^^^^^^^^^^
242242

243-
-
243+
- Bug in :class:`arrays.PandasArray` when setting a scalar string (:issue:`28118`, :issue:`28150`).
244244
-
245245

246246

pandas/core/arrays/numpy_.py

+2-9
Original file line numberDiff line numberDiff line change
@@ -235,15 +235,8 @@ def __setitem__(self, key, value):
235235
if not lib.is_scalar(value):
236236
value = np.asarray(value)
237237

238-
values = self._ndarray
239-
t = np.result_type(value, values)
240-
if t != self._ndarray.dtype:
241-
values = values.astype(t, casting="safe")
242-
values[key] = value
243-
self._dtype = PandasDtype(t)
244-
self._ndarray = values
245-
else:
246-
self._ndarray[key] = value
238+
value = np.asarray(value, dtype=self._ndarray.dtype)
239+
self._ndarray[key] = value
247240

248241
def __len__(self) -> int:
249242
return len(self._ndarray)

pandas/tests/arrays/test_numpy.py

+15
Original file line numberDiff line numberDiff line change
@@ -211,3 +211,18 @@ def test_basic_binop():
211211
result = x + x
212212
expected = PandasArray(np.array([2, 4, 6]))
213213
tm.assert_extension_array_equal(result, expected)
214+
215+
216+
@pytest.mark.parametrize("dtype", [None, object])
217+
def test_setitem_object_typecode(dtype):
218+
arr = PandasArray(np.array(["a", "b", "c"], dtype=dtype))
219+
arr[0] = "t"
220+
expected = PandasArray(np.array(["t", "b", "c"], dtype=dtype))
221+
tm.assert_extension_array_equal(arr, expected)
222+
223+
224+
def test_setitem_no_coercion():
225+
# https://github.com/pandas-dev/pandas/issues/28150
226+
arr = PandasArray(np.array([1, 2, 3]))
227+
with pytest.raises(ValueError, match="int"):
228+
arr[0] = "a"

0 commit comments

Comments
 (0)