diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 450ecc85c725b..d2683ebf4694a 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -276,7 +276,7 @@ Timedelta Timezones ^^^^^^^^^ -- +- Bug in :meth:`Series.dt.tz_convert` resetting index in a :class:`Series` with :class:`CategoricalIndex` (:issue:`43080`) - Numeric @@ -315,6 +315,7 @@ Indexing - Bug in :meth:`DataFrame.drop` where the error message did not show missing labels with commas when raising ``KeyError`` (:issue:`42881`) - + Missing ^^^^^^^ - Bug in :meth:`DataFrame.fillna` with limit and no method ignores axis='columns' or ``axis = 1`` (:issue:`40989`) diff --git a/pandas/core/indexes/accessors.py b/pandas/core/indexes/accessors.py index 516c63e0e3727..b8f4b5f9d3423 100644 --- a/pandas/core/indexes/accessors.py +++ b/pandas/core/indexes/accessors.py @@ -492,6 +492,7 @@ def __new__(cls, data: Series): name=orig.name, copy=False, dtype=orig._values.categories.dtype, + index=orig.index, ) if is_datetime64_dtype(data.dtype): diff --git a/pandas/tests/series/accessors/test_dt_accessor.py b/pandas/tests/series/accessors/test_dt_accessor.py index 61a22dad5d09b..eb7e1d4268605 100644 --- a/pandas/tests/series/accessors/test_dt_accessor.py +++ b/pandas/tests/series/accessors/test_dt_accessor.py @@ -691,6 +691,19 @@ def test_isocalendar(self, input_series, expected_output): ) tm.assert_frame_equal(result, expected_frame) + def test_hour_index(self): + dt_series = Series( + date_range(start="2021-01-01", periods=5, freq="h"), + index=[2, 6, 7, 8, 11], + dtype="category", + ) + result = dt_series.dt.hour + expected = Series( + [0, 1, 2, 3, 4], + index=[2, 6, 7, 8, 11], + ) + tm.assert_series_equal(result, expected) + class TestSeriesPeriodValuesDtAccessor: @pytest.mark.parametrize( diff --git a/pandas/tests/series/methods/test_tz_localize.py b/pandas/tests/series/methods/test_tz_localize.py index 4d7f26076e060..a32c1fb8df502 100644 --- a/pandas/tests/series/methods/test_tz_localize.py +++ b/pandas/tests/series/methods/test_tz_localize.py @@ -41,6 +41,23 @@ def test_series_tz_localize_ambiguous_bool(self): result = ser.dt.tz_localize("US/Central", ambiguous=[False]) tm.assert_series_equal(result, expected1) + def test_series_tz_localize_matching_index(self): + # Matching the index of the result with that of the original series + # GH 43080 + dt_series = Series( + date_range(start="2021-01-01T02:00:00", periods=5, freq="1D"), + index=[2, 6, 7, 8, 11], + dtype="category", + ) + result = dt_series.dt.tz_localize("Europe/Berlin") + expected = Series( + date_range( + start="2021-01-01T02:00:00", periods=5, freq="1D", tz="Europe/Berlin" + ), + index=[2, 6, 7, 8, 11], + ) + tm.assert_series_equal(result, expected) + @pytest.mark.parametrize("tz", ["Europe/Warsaw", "dateutil/Europe/Warsaw"]) @pytest.mark.parametrize( "method, exp",