From ec325a63bb5ea6ee7a0e2dc8aa8b96a3abd9df79 Mon Sep 17 00:00:00 2001 From: Tom Augspurger Date: Mon, 15 Jun 2020 14:21:19 -0500 Subject: [PATCH] Backport PR #34733 on branch 1.0.x (BUG: Fixed Series.replace for EA with casting) --- doc/source/whatsnew/v1.0.5.rst | 2 ++ pandas/core/internals/blocks.py | 6 +++++- pandas/tests/series/methods/test_replace.py | 5 +++++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/doc/source/whatsnew/v1.0.5.rst b/doc/source/whatsnew/v1.0.5.rst index 7dfac54279e6f..fdf08dd381050 100644 --- a/doc/source/whatsnew/v1.0.5.rst +++ b/doc/source/whatsnew/v1.0.5.rst @@ -24,6 +24,8 @@ Note this disables the ability to read Parquet files from directories on S3 again (:issue:`26388`, :issue:`34632`), which was added in the 1.0.4 release, but is now targeted for pandas 1.1.0. +- Fixed regression in :meth:`~DataFrame.replace` raising an ``AssertionError`` when replacing values in an extension dtype with values of a different dtype (:issue:`34530`) + .. _whatsnew_105.bug_fixes: Bug fixes diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 84dd189a8a512..317d3c303011b 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -779,7 +779,11 @@ def replace( if is_object_dtype(self): raise - assert not self._can_hold_element(value), value + if not self.is_extension: + # TODO: https://github.com/pandas-dev/pandas/issues/32586 + # Need an ExtensionArray._can_hold_element to indicate whether + # a scalar value can be placed in the array. + assert not self._can_hold_element(value), value # try again with a compatible block block = self.astype(object) diff --git a/pandas/tests/series/methods/test_replace.py b/pandas/tests/series/methods/test_replace.py index b20baa2836363..e5ccf16685c4c 100644 --- a/pandas/tests/series/methods/test_replace.py +++ b/pandas/tests/series/methods/test_replace.py @@ -362,3 +362,8 @@ def test_replace_no_cast(self, ser, exp): expected = pd.Series(exp) tm.assert_series_equal(result, expected) + + def test_replace_extension_other(self): + # https://github.com/pandas-dev/pandas/issues/34530 + ser = pd.Series(pd.array([1, 2, 3], dtype="Int64")) + ser.replace("", "") # no exception