Skip to content

BUG: Fix for .str.replace with invalid input #13460

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

Closed
wants to merge 1 commit into from
Closed
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/v0.18.2.txt
Original file line number Diff line number Diff line change
Expand Up @@ -424,3 +424,4 @@ Bug Fixes


- Bug in ``Categorical.remove_unused_categories()`` changes ``.codes`` dtype to platform int (:issue:`13261`)
- Bug in ``.str.replace`` does not raise TypeError for invalid replacement (:issue:`13438`)
4 changes: 3 additions & 1 deletion pandas/core/strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from pandas.core.common import (isnull, notnull, _values_from_object,
is_bool_dtype,
is_list_like, is_categorical_dtype,
is_object_dtype)
is_object_dtype, is_string_like)
from pandas.core.algorithms import take_1d
import pandas.compat as compat
from pandas.core.base import AccessorProperty, NoNewAttributesMixin
Expand Down Expand Up @@ -309,6 +309,8 @@ def str_replace(arr, pat, repl, n=-1, case=True, flags=0):
-------
replaced : Series/Index of objects
"""
if not is_string_like(repl): # Check whether repl is valid (GH 13438)
raise TypeError("repl must be a string")
use_re = not case or len(pat) > 1 or flags

if use_re:
Expand Down
7 changes: 7 additions & 0 deletions pandas/tests/test_strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +430,13 @@ def test_replace(self):
result = values.str.replace("(?<=\w),(?=\w)", ", ", flags=re.UNICODE)
tm.assert_series_equal(result, exp)

# GH 13438
for pdClass in (Series, Index):
for repl in (None, 3, {'a': 'b'}):
for data in (['a', 'b', None], ['a', 'b', 'c', 'ad']):
values = pdClass(data)
self.assertRaises(TypeError, values.str.replace, 'a', repl)

def test_repeat(self):
values = Series(['a', 'b', NA, 'c', NA, 'd'])

Expand Down