diff --git a/doc/source/whatsnew/v0.24.2.rst b/doc/source/whatsnew/v0.24.2.rst index 6ad299de45e2a..c3b442e2352bb 100644 --- a/doc/source/whatsnew/v0.24.2.rst +++ b/doc/source/whatsnew/v0.24.2.rst @@ -49,6 +49,12 @@ Bug Fixes - Bug in reading a JSON with ``orient='table'`` generated by :meth:`DataFrame.to_json` with ``index=False`` (:issue:`25170`) - Bug where float indexes could have misaligned values when printing (:issue:`25061`) +**Categorical** + +- Bug where calling :meth:`Series.replace` on categorical data could return a ``Series`` with incorrect dimensions (:issue:`24971`) +- +- + **Reshaping** - Bug in :meth:`~pandas.core.groupby.GroupBy.transform` where applying a function to a timezone aware column would return a timezone naive result (:issue:`24198`) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index e2ecb00f46df8..a61bc30a126e6 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -739,7 +739,7 @@ def copy(self, deep=True): values = self.values if deep: values = values.copy() - return self.make_block_same_class(values) + return self.make_block_same_class(values, ndim=self.ndim) def replace(self, to_replace, value, inplace=False, filter=None, regex=False, convert=True): diff --git a/pandas/tests/series/test_replace.py b/pandas/tests/series/test_replace.py index 2e7b746f6c9f2..d59927993debb 100644 --- a/pandas/tests/series/test_replace.py +++ b/pandas/tests/series/test_replace.py @@ -281,6 +281,20 @@ def test_replace_mixed_types_with_string(self): expected = pd.Series([1, np.nan, 3, np.nan, 4, 5]) tm.assert_series_equal(expected, result) + @pytest.mark.parametrize("categorical, numeric", [ + (pd.Categorical('A', categories=['A', 'B']), [1]), + (pd.Categorical(('A', ), categories=['A', 'B']), [1]), + (pd.Categorical(('A', 'B'), categories=['A', 'B']), [1, 2]), + ]) + def test_replace_categorical(self, categorical, numeric): + # GH 24971 + # Do not check if dtypes are equal due to a known issue that + # Categorical.replace sometimes coerces to object (GH 23305) + s = pd.Series(categorical) + result = s.replace({'A': 1, 'B': 2}) + expected = pd.Series(numeric) + tm.assert_series_equal(expected, result, check_dtype=False) + def test_replace_with_no_overflowerror(self): # GH 25616 # casts to object without Exception from OverflowError