Skip to content

Commit 7303b12

Browse files
BUG (string dtype): replace with non-string to fall back to object dtype (pandas-dev#60285)
Co-authored-by: Matthew Roeschke <[email protected]> (cherry picked from commit 938832b)
1 parent 0808657 commit 7303b12

File tree

7 files changed

+60
-46
lines changed

7 files changed

+60
-46
lines changed

doc/source/whatsnew/v2.3.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -107,10 +107,10 @@ Conversion
107107
Strings
108108
^^^^^^^
109109
- Bug in :meth:`Series.rank` for :class:`StringDtype` with ``storage="pyarrow"`` incorrectly returning integer results in case of ``method="average"`` and raising an error if it would truncate results (:issue:`59768`)
110+
- Bug in :meth:`Series.replace` with :class:`StringDtype` when replacing with a non-string value was not upcasting to ``object`` dtype (:issue:`60282`)
110111
- Bug in :meth:`Series.str.replace` when ``n < 0`` for :class:`StringDtype` with ``storage="pyarrow"`` (:issue:`59628`)
111112
- Bug in ``ser.str.slice`` with negative ``step`` with :class:`ArrowDtype` and :class:`StringDtype` with ``storage="pyarrow"`` giving incorrect results (:issue:`59710`)
112113
- Bug in the ``center`` method on :class:`Series` and :class:`Index` object ``str`` accessors with pyarrow-backed dtype not matching the python behavior in corner cases with an odd number of fill characters (:issue:`54792`)
113-
-
114114

115115
Interval
116116
^^^^^^^^

pandas/core/arrays/string_.py

+25-18
Original file line numberDiff line numberDiff line change
@@ -726,20 +726,9 @@ def _values_for_factorize(self) -> tuple[np.ndarray, libmissing.NAType | float]:
726726

727727
return arr, self.dtype.na_value
728728

729-
def __setitem__(self, key, value) -> None:
730-
value = extract_array(value, extract_numpy=True)
731-
if isinstance(value, type(self)):
732-
# extract_array doesn't extract NumpyExtensionArray subclasses
733-
value = value._ndarray
734-
735-
key = check_array_indexer(self, key)
736-
scalar_key = lib.is_scalar(key)
737-
scalar_value = lib.is_scalar(value)
738-
if scalar_key and not scalar_value:
739-
raise ValueError("setting an array element with a sequence.")
740-
741-
# validate new items
742-
if scalar_value:
729+
def _maybe_convert_setitem_value(self, value):
730+
"""Maybe convert value to be pyarrow compatible."""
731+
if lib.is_scalar(value):
743732
if isna(value):
744733
value = self.dtype.na_value
745734
elif not isinstance(value, str):
@@ -749,8 +738,11 @@ def __setitem__(self, key, value) -> None:
749738
"instead."
750739
)
751740
else:
741+
value = extract_array(value, extract_numpy=True)
752742
if not is_array_like(value):
753743
value = np.asarray(value, dtype=object)
744+
elif isinstance(value.dtype, type(self.dtype)):
745+
return value
754746
else:
755747
# cast categories and friends to arrays to see if values are
756748
# compatible, compatibility with arrow backed strings
@@ -760,11 +752,26 @@ def __setitem__(self, key, value) -> None:
760752
"Invalid value for dtype 'str'. Value should be a "
761753
"string or missing value (or array of those)."
762754
)
755+
return value
763756

764-
mask = isna(value)
765-
if mask.any():
766-
value = value.copy()
767-
value[isna(value)] = self.dtype.na_value
757+
def __setitem__(self, key, value) -> None:
758+
value = self._maybe_convert_setitem_value(value)
759+
760+
key = check_array_indexer(self, key)
761+
scalar_key = lib.is_scalar(key)
762+
scalar_value = lib.is_scalar(value)
763+
if scalar_key and not scalar_value:
764+
raise ValueError("setting an array element with a sequence.")
765+
766+
if not scalar_value:
767+
if value.dtype == self.dtype:
768+
value = value._ndarray
769+
else:
770+
value = np.asarray(value)
771+
mask = isna(value)
772+
if mask.any():
773+
value = value.copy()
774+
value[isna(value)] = self.dtype.na_value
768775

769776
super().__setitem__(key, value)
770777

pandas/core/dtypes/cast.py

+7
Original file line numberDiff line numberDiff line change
@@ -1754,6 +1754,13 @@ def can_hold_element(arr: ArrayLike, element: Any) -> bool:
17541754
except (ValueError, TypeError):
17551755
return False
17561756

1757+
if dtype == "string":
1758+
try:
1759+
arr._maybe_convert_setitem_value(element) # type: ignore[union-attr]
1760+
return True
1761+
except (ValueError, TypeError):
1762+
return False
1763+
17571764
# This is technically incorrect, but maintains the behavior of
17581765
# ExtensionBlock._can_hold_element
17591766
return True

pandas/core/internals/blocks.py

+18-5
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@
8484
ABCNumpyExtensionArray,
8585
ABCSeries,
8686
)
87+
from pandas.core.dtypes.inference import is_re
8788
from pandas.core.dtypes.missing import (
8889
is_valid_na_for_dtype,
8990
isna,
@@ -879,7 +880,7 @@ def replace(
879880
else:
880881
return [self] if inplace else [self.copy()]
881882

882-
elif self._can_hold_element(value):
883+
elif self._can_hold_element(value) or (self.dtype == "string" and is_re(value)):
883884
# TODO(CoW): Maybe split here as well into columns where mask has True
884885
# and rest?
885886
blk = self._maybe_copy(using_cow, inplace)
@@ -980,16 +981,26 @@ def _replace_regex(
980981
-------
981982
List[Block]
982983
"""
983-
if not self._can_hold_element(to_replace):
984+
if not is_re(to_replace) and not self._can_hold_element(to_replace):
984985
# i.e. only if self.is_object is True, but could in principle include a
985986
# String ExtensionBlock
986987
if using_cow:
987988
return [self.copy(deep=False)]
988989
return [self] if inplace else [self.copy()]
989990

990-
rx = re.compile(to_replace)
991+
if is_re(to_replace) and self.dtype not in [object, "string"]:
992+
# only object or string dtype can hold strings, and a regex object
993+
# will only match strings
994+
return [self.copy(deep=False)]
995+
996+
if not (
997+
self._can_hold_element(value) or (self.dtype == "string" and is_re(value))
998+
):
999+
block = self.astype(np.dtype(object))
1000+
else:
1001+
block = self._maybe_copy(using_cow, inplace)
9911002

992-
block = self._maybe_copy(using_cow, inplace)
1003+
rx = re.compile(to_replace)
9931004

9941005
replace_regex(block.values, rx, value, mask)
9951006

@@ -1048,7 +1059,9 @@ def replace_list(
10481059

10491060
# Exclude anything that we know we won't contain
10501061
pairs = [
1051-
(x, y) for x, y in zip(src_list, dest_list) if self._can_hold_element(x)
1062+
(x, y)
1063+
for x, y in zip(src_list, dest_list)
1064+
if (self._can_hold_element(x) or (self.dtype == "string" and is_re(x)))
10521065
]
10531066
if not len(pairs):
10541067
if using_cow:

pandas/tests/frame/methods/test_replace.py

-3
Original file line numberDiff line numberDiff line change
@@ -932,7 +932,6 @@ def test_replace_input_formats_listlike(self):
932932
with pytest.raises(ValueError, match=msg):
933933
df.replace(to_rep, values[1:])
934934

935-
@pytest.mark.xfail(using_string_dtype(), reason="can't set float into string")
936935
def test_replace_input_formats_scalar(self):
937936
df = DataFrame(
938937
{"A": [np.nan, 0, np.inf], "B": [0, 2, 5], "C": ["", "asdf", "fd"]}
@@ -985,7 +984,6 @@ def test_replace_dict_no_regex(self):
985984
result = answer.replace(weights)
986985
tm.assert_series_equal(result, expected)
987986

988-
@pytest.mark.xfail(using_string_dtype(), reason="can't set float into string")
989987
def test_replace_series_no_regex(self):
990988
answer = Series(
991989
{
@@ -1367,7 +1365,6 @@ def test_replace_commutative(self, df, to_replace, exp):
13671365
result = df.replace(to_replace)
13681366
tm.assert_frame_equal(result, expected)
13691367

1370-
@pytest.mark.xfail(using_string_dtype(), reason="can't set float into string")
13711368
@pytest.mark.parametrize(
13721369
"replacer",
13731370
[

pandas/tests/series/indexing/test_setitem.py

+5-13
Original file line numberDiff line numberDiff line change
@@ -886,24 +886,16 @@ def test_index_where(self, obj, key, expected, warn, val):
886886
mask = np.zeros(obj.shape, dtype=bool)
887887
mask[key] = True
888888

889-
if obj.dtype == "string" and not (isinstance(val, str) or isna(val)):
890-
with pytest.raises(TypeError, match="Invalid value"):
891-
Index(obj, dtype=obj.dtype).where(~mask, val)
892-
else:
893-
res = Index(obj, dtype=obj.dtype).where(~mask, val)
894-
expected_idx = Index(expected, dtype=expected.dtype)
895-
tm.assert_index_equal(res, expected_idx)
889+
res = Index(obj, dtype=obj.dtype).where(~mask, val)
890+
expected_idx = Index(expected, dtype=expected.dtype)
891+
tm.assert_index_equal(res, expected_idx)
896892

897893
def test_index_putmask(self, obj, key, expected, warn, val):
898894
mask = np.zeros(obj.shape, dtype=bool)
899895
mask[key] = True
900896

901-
if obj.dtype == "string" and not (isinstance(val, str) or isna(val)):
902-
with pytest.raises(TypeError, match="Invalid value"):
903-
Index(obj, dtype=obj.dtype).putmask(mask, val)
904-
else:
905-
res = Index(obj, dtype=obj.dtype).putmask(mask, val)
906-
tm.assert_index_equal(res, Index(expected, dtype=expected.dtype))
897+
res = Index(obj, dtype=obj.dtype).putmask(mask, val)
898+
tm.assert_index_equal(res, Index(expected, dtype=expected.dtype))
907899

908900

909901
@pytest.mark.parametrize(

pandas/tests/series/methods/test_replace.py

+4-6
Original file line numberDiff line numberDiff line change
@@ -745,13 +745,11 @@ def test_replace_regex_dtype_series(self, regex):
745745
tm.assert_series_equal(result, expected)
746746

747747
@pytest.mark.parametrize("regex", [False, True])
748-
def test_replace_regex_dtype_series_string(self, regex, using_infer_string):
749-
if not using_infer_string:
750-
# then this is object dtype which is already tested above
751-
return
748+
def test_replace_regex_dtype_series_string(self, regex):
752749
series = pd.Series(["0"], dtype="str")
753-
with pytest.raises(TypeError, match="Invalid value"):
754-
series.replace(to_replace="0", value=1, regex=regex)
750+
expected = pd.Series([1], dtype=object)
751+
result = series.replace(to_replace="0", value=1, regex=regex)
752+
tm.assert_series_equal(result, expected)
755753

756754
def test_replace_different_int_types(self, any_int_numpy_dtype):
757755
# GH#45311

0 commit comments

Comments
 (0)