Skip to content

Commit fca35fb

Browse files
priyankjainjreback
authored andcommitted
BUG: Fix for .str.replace with invalid input
closes #13438 Author: priyankjain <[email protected]> Closes #13460 from priyankjain/13438 and squashes the following commits: d5c3f1b [priyankjain] BUG: Fix for .str.replace with invalid input
1 parent d814f43 commit fca35fb

File tree

3 files changed

+13
-2
lines changed

3 files changed

+13
-2
lines changed

doc/source/whatsnew/v0.18.2.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -391,7 +391,7 @@ Bug Fixes
391391

392392
- Bug in ``DataFrame.to_csv()`` in which float values were being quoted even though quotations were specified for non-numeric values only (:issue:`12922`, :issue:`13259`)
393393
- Bug in ``MultiIndex`` slicing where extra elements were returned when level is non-unique (:issue:`12896`)
394-
394+
- Bug in ``.str.replace`` does not raise ``TypeError`` for invalid replacement (:issue:`13438`)
395395

396396

397397
- Bug in ``pd.read_csv()`` with ``engine='python'`` in which ``NaN`` values weren't being detected after data was converted to numeric values (:issue:`13314`)

pandas/core/strings.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from pandas.core.common import (isnull, notnull, _values_from_object,
55
is_bool_dtype,
66
is_list_like, is_categorical_dtype,
7-
is_object_dtype)
7+
is_object_dtype, is_string_like)
88
from pandas.core.algorithms import take_1d
99
import pandas.compat as compat
1010
from pandas.core.base import AccessorProperty, NoNewAttributesMixin
@@ -309,6 +309,10 @@ def str_replace(arr, pat, repl, n=-1, case=True, flags=0):
309309
-------
310310
replaced : Series/Index of objects
311311
"""
312+
313+
# Check whether repl is valid (GH 13438)
314+
if not is_string_like(repl):
315+
raise TypeError("repl must be a string")
312316
use_re = not case or len(pat) > 1 or flags
313317

314318
if use_re:

pandas/tests/test_strings.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -430,6 +430,13 @@ def test_replace(self):
430430
result = values.str.replace("(?<=\w),(?=\w)", ", ", flags=re.UNICODE)
431431
tm.assert_series_equal(result, exp)
432432

433+
# GH 13438
434+
for klass in (Series, Index):
435+
for repl in (None, 3, {'a': 'b'}):
436+
for data in (['a', 'b', None], ['a', 'b', 'c', 'ad']):
437+
values = klass(data)
438+
self.assertRaises(TypeError, values.str.replace, 'a', repl)
439+
433440
def test_repeat(self):
434441
values = Series(['a', 'b', NA, 'c', NA, 'd'])
435442

0 commit comments

Comments
 (0)