Skip to content

BUG: avoid StringArray.__setitem__ to mutate the value being set as side-effect #51299

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1229,6 +1229,7 @@ Strings
^^^^^^^
- Bug in :func:`pandas.api.types.is_string_dtype` that would not return ``True`` for :class:`StringDtype` or :class:`ArrowDtype` with ``pyarrow.string()`` (:issue:`15585`)
- Bug in converting string dtypes to "datetime64[ns]" or "timedelta64[ns]" incorrectly raising ``TypeError`` (:issue:`36153`)
- Bug in setting values in a string-dtype column with an array, mutating the array as side effect when it contains missing values (:issue:`51299`)
-

Interval
Expand Down
5 changes: 4 additions & 1 deletion pandas/core/arrays/string_.py
Original file line number Diff line number Diff line change
Expand Up @@ -423,7 +423,10 @@ def __setitem__(self, key, value):
if len(value) and not lib.is_string_array(value, skipna=True):
raise TypeError("Must provide strings.")

value[isna(value)] = libmissing.NA
mask = isna(value)
if mask.any():
value = value.copy()
value[isna(value)] = libmissing.NA

super().__setitem__(key, value)

Expand Down
13 changes: 13 additions & 0 deletions pandas/tests/arrays/string_/test_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,19 @@ def test_setitem_with_scalar_string(dtype):
tm.assert_extension_array_equal(arr, expected)


def test_setitem_with_array_with_missing(dtype):
# ensure that when setting with an array of values, we don't mutate the
# array `value` in __setitem__(self, key, value)
arr = pd.array(["a", "b", "c"], dtype=dtype)
value = np.array(["A", None])
value_orig = value.copy()
arr[[0, 1]] = value

expected = pd.array(["A", pd.NA, "c"], dtype=dtype)
tm.assert_extension_array_equal(arr, expected)
tm.assert_numpy_array_equal(value, value_orig)


def test_astype_roundtrip(dtype):
ser = pd.Series(pd.date_range("2000", periods=12))
ser[0] = None
Expand Down