From 0f031b7a9b89c12728ca4e729501712a654dc768 Mon Sep 17 00:00:00 2001 From: Phillip Cloud Date: Thu, 3 Apr 2014 10:58:09 -0400 Subject: [PATCH] BUG: fix metacharacter replacement bug in DataFrame.replace() --- doc/source/release.rst | 3 ++- pandas/core/internals.py | 2 +- pandas/tests/test_frame.py | 9 +++++++++ 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/doc/source/release.rst b/doc/source/release.rst index 31cd37e4bf467..2576982d6976f 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -301,7 +301,8 @@ Bug Fixes - Bug in downcasting inference with empty arrays (:issue:`6733`) - Bug in ``obj.blocks`` on sparse containers dropping all but the last items of same for dtype (:issue:`6748`) - Bug in unpickling ``NaT (NaTType)`` (:issue:`4606`) -- Bug in setting a tz-aware index directly via ``.index`` (:issue:`6785`) +- Bug in ``DataFrame.replace()`` where regex metacharacters were being treated + as regexs even when ``regex=False`` (:issue:`6777`). pandas 0.13.1 ------------- diff --git a/pandas/core/internals.py b/pandas/core/internals.py index a548b5f61754e..e28d4029d4fa0 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -1555,7 +1555,7 @@ def replace(self, to_replace, value, inplace=False, filter=None, def _replace_single(self, to_replace, value, inplace=False, filter=None, regex=False): # to_replace is regex compilable - to_rep_re = com.is_re_compilable(to_replace) + to_rep_re = regex and com.is_re_compilable(to_replace) # regex is regex compilable regex_re = com.is_re_compilable(regex) diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 4e422b452ebf8..087e094ffbcb8 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -7857,6 +7857,15 @@ def test_regex_replace_numeric_to_object_conversion(self): assert_frame_equal(res, expec) self.assertEqual(res.a.dtype, np.object_) + def test_replace_regex_metachar(self): + metachars = '[]', '()', '\d', '\w', '\s' + + for metachar in metachars: + df = DataFrame({'a': [metachar, 'else']}) + result = df.replace({'a': {metachar: 'paren'}}) + expected = DataFrame({'a': ['paren', 'else']}) + tm.assert_frame_equal(result, expected) + def test_replace(self): self.tsframe['A'][:5] = nan self.tsframe['A'][-5:] = nan