Skip to content

Commit f0718fa

Browse files
committed
BUG: Fixed PandasArray.__setitem__ with str
Closes pandas-dev#28118
1 parent 347ad85 commit f0718fa

File tree

3 files changed

+17
-2
lines changed

3 files changed

+17
-2
lines changed

doc/source/whatsnew/v1.0.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,7 @@ Build Changes
198198
ExtensionArray
199199
^^^^^^^^^^^^^^
200200

201-
-
201+
- Bug in :class:`arrays.PandasArray` when setting a scalar string (:issue:`28118`)
202202
-
203203

204204

pandas/core/arrays/numpy_.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from pandas.util._decorators import Appender
99
from pandas.util._validators import validate_fillna_kwargs
1010

11+
from pandas.core.dtypes.common import is_object_dtype
1112
from pandas.core.dtypes.dtypes import ExtensionDtype
1213
from pandas.core.dtypes.generic import ABCIndexClass, ABCSeries
1314
from pandas.core.dtypes.inference import is_array_like, is_list_like
@@ -236,7 +237,13 @@ def __setitem__(self, key, value):
236237
value = np.asarray(value)
237238

238239
values = self._ndarray
239-
t = np.result_type(value, values)
240+
if isinstance(value, str):
241+
if is_object_dtype(self.dtype._dtype):
242+
t = np.dtype(object)
243+
else:
244+
t = self.dtype._dtype
245+
else:
246+
t = np.result_type(value, values)
240247
if t != self._ndarray.dtype:
241248
values = values.astype(t, casting="safe")
242249
values[key] = value

pandas/tests/arrays/test_numpy.py

+8
Original file line numberDiff line numberDiff line change
@@ -211,3 +211,11 @@ 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)

0 commit comments

Comments
 (0)