diff --git a/doc/source/user_guide/10min.rst b/doc/source/user_guide/10min.rst index 2c612e31d33b6..0f5d8162ce275 100644 --- a/doc/source/user_guide/10min.rst +++ b/doc/source/user_guide/10min.rst @@ -614,22 +614,6 @@ financial applications. See the :ref:`Time Series section `. ts = pd.Series(np.random.randint(0, 500, len(rng)), index=rng) ts.resample("5Min").sum() -:meth:`Series.tz_localize` localizes a time series to a time zone: - -.. ipython:: python - - rng = pd.date_range("3/6/2012 00:00", periods=5, freq="D") - ts = pd.Series(np.random.randn(len(rng)), rng) - ts - ts_utc = ts.tz_localize("UTC") - ts_utc - -:meth:`Series.tz_convert` converts a timezones aware time series to another time zone: - -.. ipython:: python - - ts_utc.tz_convert("US/Eastern") - Adding a non-fixed duration (:class:`~pandas.tseries.offsets.BusinessDay`) to a time series: .. ipython:: python diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index ef59c86a21598..12f0caf6488fc 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -235,6 +235,7 @@ Other Deprecations ^^^^^^^^^^^^^^^^^^ - Changed :meth:`Timedelta.resolution_string` to return ``h``, ``min``, ``s``, ``ms``, ``us``, and ``ns`` instead of ``H``, ``T``, ``S``, ``L``, ``U``, and ``N``, for compatibility with respective deprecations in frequency aliases (:issue:`52536`) - Deprecated :meth:`Index.format`, use ``index.astype(str)`` or ``index.map(formatter)`` instead (:issue:`55413`) +- Deprecated :meth:`Series.to_period`, :meth:`DataFrame.to_period`, :meth:`Series.to_timestamp`, :meth:`DataFrame.to_timestamp`, :meth:`Series.tz_localize`, :meth:`DataFrame.tz_localize`, :meth:`Series.tz_convert`, :meth:`DataFrame.tz_convert`, use the relevant methods on ``obj.set_axis(obj.index.relevant_method(...))`` instead (:issue:`52110`) - Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_clipboard`. (:issue:`54229`) - Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_csv` except ``path_or_buf``. (:issue:`54229`) - Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_dict`. (:issue:`54229`) diff --git a/pandas/conftest.py b/pandas/conftest.py index 62f22921f0482..ef2f7f8b44d72 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -146,6 +146,11 @@ def pytest_collection_modifyitems(items, config) -> None: ("NDFrame.replace", "The 'method' keyword"), ("NDFrame.replace", "Series.replace without 'value'"), ("NDFrame.clip", "Downcasting behavior in Series and DataFrame methods"), + ("Series.to_timestamp", "Series.to_timestamp is deprecated"), + ("Series.to_period", "Series.to_period is deprecated"), + ("Series.tz_localize", "Series.tz_localize is deprecated"), + ("Series.tz_convert", "Series.tz_convert is deprecated"), + ("DataFrame.to_timestamp", "DataFrame.to_timestamp is deprecated"), ("Series.idxmin", "The behavior of Series.idxmin"), ("Series.idxmax", "The behavior of Series.idxmax"), ("SeriesGroupBy.idxmin", "The behavior of Series.idxmin"), diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 09c43822e11e4..8a69466cbd0be 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -12103,6 +12103,15 @@ def to_timestamp( >>> df2.index DatetimeIndex(['2023-01-31', '2024-01-31'], dtype='datetime64[ns]', freq=None) """ + warnings.warn( + # GH#52110 + f"{type(self).__name__}.to_timestamp is deprecated and will be " + "removed in a future version. Use " + "obj.set_axis(obj.index.to_timestamp(...)) instead", + FutureWarning, + stacklevel=find_stack_level(), + ) + new_obj = self.copy(deep=copy and not using_copy_on_write()) axis_name = self._get_axis_name(axis) @@ -12160,6 +12169,15 @@ def to_period( >>> idx.to_period("Y") PeriodIndex(['2001', '2002', '2003'], dtype='period[Y-DEC]') """ + warnings.warn( + # GH#52110 + f"{type(self).__name__}.to_period is deprecated and will be " + "removed in a future version. Use " + "obj.set_axis(obj.index.to_period(freq)) instead", + FutureWarning, + stacklevel=find_stack_level(), + ) + new_obj = self.copy(deep=copy and not using_copy_on_write()) axis_name = self._get_axis_name(axis) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index f1ecc57335a51..eb7e6ca1dd33f 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -11217,6 +11217,14 @@ def tz_convert( 2018-09-14 23:30:00 1 dtype: int64 """ + warnings.warn( + # GH#52110 + f"{type(self).__name__}.tz_convert is deprecated and will be " + "removed in a future version. Use " + "obj.set_axis(obj.index.tz_convert(tz)) instead", + FutureWarning, + stacklevel=find_stack_level(), + ) axis = self._get_axis_number(axis) ax = self._get_axis(axis) @@ -11389,6 +11397,15 @@ def tz_localize( 2015-03-29 03:30:00+02:00 1 dtype: int64 """ + warnings.warn( + # GH#52110 + f"{type(self).__name__}.tz_localize is deprecated and will be " + "removed in a future version. Use " + "obj.set_axis(obj.index.tz_localize(tz)) instead", + FutureWarning, + stacklevel=find_stack_level(), + ) + nonexistent_options = ("raise", "NaT", "shift_forward", "shift_backward") if nonexistent not in nonexistent_options and not isinstance( nonexistent, dt.timedelta diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 969748209772a..be502727e2328 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -1868,7 +1868,8 @@ def _convert_obj(self, obj: NDFrameT) -> NDFrameT: # convert to timestamp if self.kind == "timestamp": - obj = obj.to_timestamp(how=self.convention) + dti = obj.index.to_timestamp(how=self.convention) + obj = obj.set_axis(dti) return obj diff --git a/pandas/core/series.py b/pandas/core/series.py index fdd03debf6de4..cadf63b1885de 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -5741,6 +5741,15 @@ def to_timestamp( 2025-01-31 3 Freq: Y-JAN, dtype: int64 """ + warnings.warn( + # GH#52110 + f"{type(self).__name__}.to_timestamp is deprecated and will be " + "removed in a future version. Use " + "obj.set_axis(obj.index.to_timestamp(...)) instead", + FutureWarning, + stacklevel=find_stack_level(), + ) + if not isinstance(self.index, PeriodIndex): raise TypeError(f"unsupported Type {type(self.index).__name__}") @@ -5781,6 +5790,15 @@ def to_period(self, freq: str | None = None, copy: bool | None = None) -> Series >>> s.index PeriodIndex(['2023', '2024', '2025'], dtype='period[Y-DEC]') """ + warnings.warn( + # GH#52110 + f"{type(self).__name__}.to_period is deprecated and will be " + "removed in a future version. Use " + "obj.set_axis(obj.index.to_period(freq)) instead", + FutureWarning, + stacklevel=find_stack_level(), + ) + if not isinstance(self.index, DatetimeIndex): raise TypeError(f"unsupported Type {type(self.index).__name__}") diff --git a/pandas/plotting/_matplotlib/timeseries.py b/pandas/plotting/_matplotlib/timeseries.py index 77de5c1ad7b42..1a4b725c9b73c 100644 --- a/pandas/plotting/_matplotlib/timeseries.py +++ b/pandas/plotting/_matplotlib/timeseries.py @@ -295,7 +295,7 @@ def maybe_convert_index(ax: Axes, data): ) if isinstance(data.index, ABCDatetimeIndex): - data = data.tz_localize(None).to_period(freq=freq_str) + data.index = data.index.tz_localize(None).to_period(freq=freq_str) elif isinstance(data.index, ABCPeriodIndex): data.index = data.index.asfreq(freq=freq_str) return data diff --git a/pandas/tests/apply/test_series_apply.py b/pandas/tests/apply/test_series_apply.py index 643b9220999f7..9a178bdfde7da 100644 --- a/pandas/tests/apply/test_series_apply.py +++ b/pandas/tests/apply/test_series_apply.py @@ -513,10 +513,9 @@ def test_series_apply_no_suffix_index(by_row): def test_apply_series_on_date_time_index_aware_series(dti, exp, aware): # GH 25959 # Calling apply on a localized time series should not cause an error + index = dti.index if aware: - index = dti.tz_localize("UTC").index - else: - index = dti.index + index = index.tz_localize("UTC") result = Series(index).apply(lambda x: Series([1, 2])) tm.assert_frame_equal(result, exp) @@ -527,7 +526,8 @@ def test_apply_series_on_date_time_index_aware_series(dti, exp, aware): def test_apply_scalar_on_date_time_index_aware_series(by_row, expected): # GH 25959 # Calling apply on a localized time series should not cause an error - series = tm.makeTimeSeries(nper=30).tz_localize("UTC") + series = tm.makeTimeSeries(nper=30) + series.index = series.index.tz_localize("UTC") result = Series(series.index).apply(lambda x: 1, by_row=by_row) tm.assert_equal(result, expected) diff --git a/pandas/tests/copy_view/test_methods.py b/pandas/tests/copy_view/test_methods.py index 45bfc6a6fcf9b..563d0e458eaa8 100644 --- a/pandas/tests/copy_view/test_methods.py +++ b/pandas/tests/copy_view/test_methods.py @@ -136,6 +136,22 @@ def test_methods_copy_keyword( msg = "'DataFrame.swapaxes' is deprecated" with tm.assert_produces_warning(FutureWarning, match=msg): df2 = method(df, copy=copy) + elif "tz_convert" in request.node.callspec.id: + msg = "DataFrame.tz_convert is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + df2 = method(df, copy=copy) + elif "tz_localize" in request.node.callspec.id: + msg = "DataFrame.tz_localize is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + df2 = method(df, copy=copy) + elif "to_timestamp" in request.node.callspec.id: + msg = "DataFrame.to_timestamp is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + df2 = method(df, copy=copy) + elif "to_period" in request.node.callspec.id: + msg = "DataFrame.to_period is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + df2 = method(df, copy=copy) else: df2 = method(df, copy=copy) @@ -213,6 +229,22 @@ def test_methods_series_copy_keyword(request, method, copy, using_copy_on_write) msg = "'Series.swapaxes' is deprecated" with tm.assert_produces_warning(FutureWarning, match=msg): ser2 = method(ser, copy=copy) + elif "tz_convert" in request.node.callspec.id: + msg = "Series.tz_convert is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + ser2 = method(ser, copy=copy) + elif "tz_localize" in request.node.callspec.id: + msg = "Series.tz_localize is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + ser2 = method(ser, copy=copy) + elif "to_timestamp" in request.node.callspec.id: + msg = "Series.to_timestamp is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + ser2 = method(ser, copy=copy) + elif "to_period" in request.node.callspec.id: + msg = "Series.to_period is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + ser2 = method(ser, copy=copy) else: ser2 = method(ser, copy=copy) @@ -766,7 +798,9 @@ def test_to_timestamp(using_copy_on_write, obj): obj.index = Index([Period("2012-1-1", freq="D"), Period("2012-1-2", freq="D")]) obj_orig = obj.copy() - obj2 = obj.to_timestamp() + depr_msg = f"{type(obj).__name__}.to_timestamp is deprecated" + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + obj2 = obj.to_timestamp() if using_copy_on_write: assert np.shares_memory(get_array(obj2, "a"), get_array(obj, "a")) @@ -784,7 +818,9 @@ def test_to_period(using_copy_on_write, obj): obj.index = Index([Timestamp("2019-12-31"), Timestamp("2020-12-31")]) obj_orig = obj.copy() - obj2 = obj.to_period(freq="Y") + depr_msg = f"{type(obj).__name__}.to_period is deprecated" + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + obj2 = obj.to_period(freq="Y") if using_copy_on_write: assert np.shares_memory(get_array(obj2, "a"), get_array(obj, "a")) @@ -1314,7 +1350,9 @@ def test_tz_convert_localize(using_copy_on_write, func, tz): [1, 2], index=date_range(start="2014-08-01 09:00", freq="h", periods=2, tz=tz) ) ser_orig = ser.copy() - ser2 = getattr(ser, func)("US/Central") + depr_msg = f"Series.{func} is deprecated" + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + ser2 = getattr(ser, func)("US/Central") if using_copy_on_write: assert np.shares_memory(ser.values, ser2.values) diff --git a/pandas/tests/frame/methods/test_align.py b/pandas/tests/frame/methods/test_align.py index 25eb2ccb18361..f86958aa50e9f 100644 --- a/pandas/tests/frame/methods/test_align.py +++ b/pandas/tests/frame/methods/test_align.py @@ -34,7 +34,7 @@ def test_frame_align_aware(self): # different timezones convert to UTC # frame with frame - df1_central = df1.tz_convert("US/Central") + df1_central = df1.set_axis(df1.index.tz_convert("US/Central")) new1, new2 = df1.align(df1_central) assert new1.index.tz is timezone.utc assert new2.index.tz is timezone.utc diff --git a/pandas/tests/frame/methods/test_asof.py b/pandas/tests/frame/methods/test_asof.py index 4a8adf89b3aef..d1a2d6e9a99a2 100644 --- a/pandas/tests/frame/methods/test_asof.py +++ b/pandas/tests/frame/methods/test_asof.py @@ -97,7 +97,7 @@ def test_missing(self, date_range_frame): # Check that we handle PeriodIndex correctly, dont end up with # period.ordinal for series name - df = df.to_period("D") + df = df.set_axis(df.index.to_period("D")) result = df.asof("1989-12-31") assert isinstance(result.name, Period) diff --git a/pandas/tests/frame/methods/test_at_time.py b/pandas/tests/frame/methods/test_at_time.py index 4c1434bd66aff..153d325ae36ac 100644 --- a/pandas/tests/frame/methods/test_at_time.py +++ b/pandas/tests/frame/methods/test_at_time.py @@ -23,10 +23,11 @@ def test_localized_at_time(self, tzstr, frame_or_series): np.random.default_rng(2).standard_normal(len(rng)), index=rng ) - ts_local = ts.tz_localize(tzstr) + ts_local = ts.set_axis(ts.index.tz_localize(tzstr)) result = ts_local.at_time(time(10, 0)) - expected = ts.at_time(time(10, 0)).tz_localize(tzstr) + expected = ts.at_time(time(10, 0)) + expected = expected.set_axis(expected.index.tz_localize(tzstr)) tm.assert_equal(result, expected) assert timezones.tz_compare(result.index.tz, tz) diff --git a/pandas/tests/frame/methods/test_between_time.py b/pandas/tests/frame/methods/test_between_time.py index 74d6291707e19..882654ccadbb0 100644 --- a/pandas/tests/frame/methods/test_between_time.py +++ b/pandas/tests/frame/methods/test_between_time.py @@ -51,11 +51,12 @@ def test_localized_between_time(self, tzstr, frame_or_series): if frame_or_series is DataFrame: ts = ts.to_frame() - ts_local = ts.tz_localize(tzstr) + ts_local = ts.set_axis(ts.index.tz_localize(tzstr)) t1, t2 = time(10, 0), time(11, 0) result = ts_local.between_time(t1, t2) - expected = ts.between_time(t1, t2).tz_localize(tzstr) + expected = ts.between_time(t1, t2) + expected = expected.set_axis(expected.index.tz_localize(tzstr)) tm.assert_equal(result, expected) assert timezones.tz_compare(result.index.tz, tz) diff --git a/pandas/tests/frame/methods/test_to_period.py b/pandas/tests/frame/methods/test_to_period.py index 6a3e6b8c0e059..33a53bc3e6372 100644 --- a/pandas/tests/frame/methods/test_to_period.py +++ b/pandas/tests/frame/methods/test_to_period.py @@ -25,12 +25,15 @@ def test_to_period(self, frame_or_series): obj["mix"] = "a" obj = tm.get_obj(obj, frame_or_series) - pts = obj.to_period() + msg = "(Series|DataFrame).to_period is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + pts = obj.to_period() exp = obj.copy() exp.index = period_range("1/1/2000", "1/1/2001") tm.assert_equal(pts, exp) - pts = obj.to_period("M") + with tm.assert_produces_warning(FutureWarning, match=msg): + pts = obj.to_period("M") exp.index = exp.index.asfreq("M") tm.assert_equal(pts, exp) @@ -47,12 +50,17 @@ def test_to_period_without_freq(self, frame_or_series): obj = tm.get_obj(obj, frame_or_series) expected = obj.copy() expected.index = exp_idx - tm.assert_equal(obj.to_period(), expected) + msg = f"{type(expected).__name__}.to_period is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + res = obj.to_period() + tm.assert_equal(res, expected) if frame_or_series is DataFrame: expected = obj.copy() expected.columns = exp_idx - tm.assert_frame_equal(obj.to_period(axis=1), expected) + with tm.assert_produces_warning(FutureWarning, match=msg): + res = obj.to_period(axis=1) + tm.assert_frame_equal(res, expected) def test_to_period_columns(self): dr = date_range("1/1/2000", "1/1/2001") @@ -60,12 +68,15 @@ def test_to_period_columns(self): df["mix"] = "a" df = df.T - pts = df.to_period(axis=1) + msg = "DataFrame.to_period is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + pts = df.to_period(axis=1) exp = df.copy() exp.columns = period_range("1/1/2000", "1/1/2001") tm.assert_frame_equal(pts, exp) - pts = df.to_period("M", axis=1) + with tm.assert_produces_warning(FutureWarning, match=msg): + pts = df.to_period("M", axis=1) tm.assert_index_equal(pts.columns, exp.columns.asfreq("M")) def test_to_period_invalid_axis(self): @@ -74,8 +85,10 @@ def test_to_period_invalid_axis(self): df["mix"] = "a" msg = "No axis named 2 for object type DataFrame" + depr_msg = "DataFrame.to_period is deprecated" with pytest.raises(ValueError, match=msg): - df.to_period(axis=2) + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + df.to_period(axis=2) def test_to_period_raises(self, index, frame_or_series): # https://github.com/pandas-dev/pandas/issues/33327 @@ -83,7 +96,9 @@ def test_to_period_raises(self, index, frame_or_series): if frame_or_series is DataFrame: obj = obj.to_frame() + depr_msg = rf"{type(obj).__name__}\.to_period is deprecated" if not isinstance(index, DatetimeIndex): msg = f"unsupported Type {type(index).__name__}" with pytest.raises(TypeError, match=msg): - obj.to_period() + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + obj.to_period() diff --git a/pandas/tests/frame/methods/test_to_records.py b/pandas/tests/frame/methods/test_to_records.py index fab90b112fa94..680fd8b5b92d9 100644 --- a/pandas/tests/frame/methods/test_to_records.py +++ b/pandas/tests/frame/methods/test_to_records.py @@ -517,7 +517,7 @@ def test_to_records_datetimeindex_with_tz(self, tz): df = DataFrame({"datetime": dr}, index=dr) expected = df.to_records() - result = df.tz_convert("UTC").to_records() + result = df.set_axis(df.index.tz_convert("UTC")).to_records() # both converted to UTC, so they are equal tm.assert_numpy_array_equal(result, expected) diff --git a/pandas/tests/frame/methods/test_to_timestamp.py b/pandas/tests/frame/methods/test_to_timestamp.py index 859dc56de4a25..9f0549b38b768 100644 --- a/pandas/tests/frame/methods/test_to_timestamp.py +++ b/pandas/tests/frame/methods/test_to_timestamp.py @@ -38,32 +38,39 @@ def test_to_timestamp(self, frame_or_series): exp_index = date_range("1/1/2001", end="12/31/2009", freq="Y-DEC") exp_index = exp_index + Timedelta(1, "D") - Timedelta(1, "ns") - result = obj.to_timestamp("D", "end") + msg = rf"{type(obj).__name__}\.to_timestamp is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = obj.to_timestamp("D", "end") tm.assert_index_equal(result.index, exp_index) tm.assert_numpy_array_equal(result.values, obj.values) if frame_or_series is Series: assert result.name == "A" exp_index = date_range("1/1/2001", end="1/1/2009", freq="YS-JAN") - result = obj.to_timestamp("D", "start") + with tm.assert_produces_warning(FutureWarning, match=msg): + result = obj.to_timestamp("D", "start") tm.assert_index_equal(result.index, exp_index) - result = obj.to_timestamp(how="start") + with tm.assert_produces_warning(FutureWarning, match=msg): + result = obj.to_timestamp(how="start") tm.assert_index_equal(result.index, exp_index) delta = timedelta(hours=23) - result = obj.to_timestamp("H", "end") + with tm.assert_produces_warning(FutureWarning, match=msg): + result = obj.to_timestamp("H", "end") exp_index = _get_with_delta(delta) exp_index = exp_index + Timedelta(1, "h") - Timedelta(1, "ns") tm.assert_index_equal(result.index, exp_index) delta = timedelta(hours=23, minutes=59) - result = obj.to_timestamp("T", "end") + with tm.assert_produces_warning(FutureWarning, match=msg): + result = obj.to_timestamp("T", "end") exp_index = _get_with_delta(delta) exp_index = exp_index + Timedelta(1, "m") - Timedelta(1, "ns") tm.assert_index_equal(result.index, exp_index) - result = obj.to_timestamp("S", "end") + with tm.assert_produces_warning(FutureWarning, match=msg): + result = obj.to_timestamp("S", "end") delta = timedelta(hours=23, minutes=59, seconds=59) exp_index = _get_with_delta(delta) exp_index = exp_index + Timedelta(1, "s") - Timedelta(1, "ns") @@ -82,36 +89,44 @@ def test_to_timestamp_columns(self): # columns df = df.T + msg = r"DataFrame\.to_timestamp is deprecated" + exp_index = date_range("1/1/2001", end="12/31/2009", freq="Y-DEC") exp_index = exp_index + Timedelta(1, "D") - Timedelta(1, "ns") - result = df.to_timestamp("D", "end", axis=1) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.to_timestamp("D", "end", axis=1) tm.assert_index_equal(result.columns, exp_index) tm.assert_numpy_array_equal(result.values, df.values) exp_index = date_range("1/1/2001", end="1/1/2009", freq="YS-JAN") - result = df.to_timestamp("D", "start", axis=1) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.to_timestamp("D", "start", axis=1) tm.assert_index_equal(result.columns, exp_index) delta = timedelta(hours=23) - result = df.to_timestamp("H", "end", axis=1) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.to_timestamp("H", "end", axis=1) exp_index = _get_with_delta(delta) exp_index = exp_index + Timedelta(1, "h") - Timedelta(1, "ns") tm.assert_index_equal(result.columns, exp_index) delta = timedelta(hours=23, minutes=59) - result = df.to_timestamp("min", "end", axis=1) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.to_timestamp("min", "end", axis=1) exp_index = _get_with_delta(delta) exp_index = exp_index + Timedelta(1, "m") - Timedelta(1, "ns") tm.assert_index_equal(result.columns, exp_index) - result = df.to_timestamp("S", "end", axis=1) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.to_timestamp("S", "end", axis=1) delta = timedelta(hours=23, minutes=59, seconds=59) exp_index = _get_with_delta(delta) exp_index = exp_index + Timedelta(1, "s") - Timedelta(1, "ns") tm.assert_index_equal(result.columns, exp_index) - result1 = df.to_timestamp("5min", axis=1) - result2 = df.to_timestamp("min", axis=1) + with tm.assert_produces_warning(FutureWarning, match=msg): + result1 = df.to_timestamp("5min", axis=1) + result2 = df.to_timestamp("min", axis=1) expected = date_range("2001-01-01", "2009-01-01", freq="YS") assert isinstance(result1.columns, DatetimeIndex) assert isinstance(result2.columns, DatetimeIndex) @@ -128,8 +143,10 @@ def test_to_timestamp_invalid_axis(self): ) # invalid axis + msg = rf"{type(obj).__name__}\.to_timestamp is deprecated" with pytest.raises(ValueError, match="axis"): - obj.to_timestamp(axis=2) + with tm.assert_produces_warning(FutureWarning, match=msg): + obj.to_timestamp(axis=2) def test_to_timestamp_hourly(self, frame_or_series): index = period_range(freq="h", start="1/1/2001", end="1/2/2001") @@ -138,7 +155,9 @@ def test_to_timestamp_hourly(self, frame_or_series): obj = obj.to_frame() exp_index = date_range("1/1/2001 00:59:59", end="1/2/2001 00:59:59", freq="h") - result = obj.to_timestamp(how="end") + msg = rf"{type(obj).__name__}\.to_timestamp is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = obj.to_timestamp(how="end") exp_index = exp_index + Timedelta(1, "s") - Timedelta(1, "ns") tm.assert_index_equal(result.index, exp_index) if frame_or_series is Series: @@ -148,7 +167,9 @@ def test_to_timestamp_raises(self, index, frame_or_series): # GH#33327 obj = frame_or_series(index=index, dtype=object) + depr_msg = r"\.to_timestamp is deprecated" if not isinstance(index, PeriodIndex): msg = f"unsupported Type {type(index).__name__}" with pytest.raises(TypeError, match=msg): - obj.to_timestamp() + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + obj.to_timestamp() diff --git a/pandas/tests/frame/methods/test_tz_convert.py b/pandas/tests/frame/methods/test_tz_convert.py index bcb8e423980fd..f53734a9fc5dd 100644 --- a/pandas/tests/frame/methods/test_tz_convert.py +++ b/pandas/tests/frame/methods/test_tz_convert.py @@ -10,6 +10,9 @@ ) import pandas._testing as tm +depr_msg1 = "(Series|DataFrame).tz_localize is deprecated" +depr_msg2 = "(Series|DataFrame).tz_convert is deprecated" + class TestTZConvert: def test_tz_convert(self, frame_or_series): @@ -18,7 +21,8 @@ def test_tz_convert(self, frame_or_series): obj = DataFrame({"a": 1}, index=rng) obj = tm.get_obj(obj, frame_or_series) - result = obj.tz_convert("Europe/Berlin") + with tm.assert_produces_warning(FutureWarning, match=depr_msg2): + result = obj.tz_convert("Europe/Berlin") expected = DataFrame({"a": 1}, rng.tz_convert("Europe/Berlin")) expected = tm.get_obj(expected, frame_or_series) @@ -31,7 +35,8 @@ def test_tz_convert_axis1(self): obj = DataFrame({"a": 1}, index=rng) obj = obj.T - result = obj.tz_convert("Europe/Berlin", axis=1) + with tm.assert_produces_warning(FutureWarning, match=depr_msg2): + result = obj.tz_convert("Europe/Berlin", axis=1) assert result.columns.tz.zone == "Europe/Berlin" expected = DataFrame({"a": 1}, rng.tz_convert("Europe/Berlin")) @@ -45,7 +50,8 @@ def test_tz_convert_naive(self, frame_or_series): ts = frame_or_series(ts) with pytest.raises(TypeError, match="Cannot convert tz-naive"): - ts.tz_convert("US/Eastern") + with tm.assert_produces_warning(FutureWarning, match=depr_msg2): + ts.tz_convert("US/Eastern") @pytest.mark.parametrize("fn", ["tz_localize", "tz_convert"]) def test_tz_convert_and_localize(self, fn): @@ -63,7 +69,8 @@ def test_tz_convert_and_localize(self, fn): l1_expected = getattr(idx, fn)("US/Pacific") df1 = DataFrame(np.ones(5), index=l0) - df1 = getattr(df1, fn)("US/Pacific") + with tm.assert_produces_warning(FutureWarning, match="deprecated"): + df1 = getattr(df1, fn)("US/Pacific") tm.assert_index_equal(df1.index, l0_expected) # MultiIndex @@ -76,13 +83,15 @@ def test_tz_convert_and_localize(self, fn): l1 = l1._with_freq(None) l0 = l0._with_freq(None) - df3 = getattr(df2, fn)("US/Pacific", level=0) + with tm.assert_produces_warning(FutureWarning, match="deprecated"): + df3 = getattr(df2, fn)("US/Pacific", level=0) assert not df3.index.levels[0].equals(l0) tm.assert_index_equal(df3.index.levels[0], l0_expected) tm.assert_index_equal(df3.index.levels[1], l1) assert not df3.index.levels[1].equals(l1_expected) - df3 = getattr(df2, fn)("US/Pacific", level=1) + with tm.assert_produces_warning(FutureWarning, match="deprecated"): + df3 = getattr(df2, fn)("US/Pacific", level=1) tm.assert_index_equal(df3.index.levels[0], l0) assert not df3.index.levels[0].equals(l0_expected) tm.assert_index_equal(df3.index.levels[1], l1_expected) @@ -91,7 +100,8 @@ def test_tz_convert_and_localize(self, fn): df4 = DataFrame(np.ones(5), MultiIndex.from_arrays([int_idx, l0])) # TODO: untested - getattr(df4, fn)("US/Pacific", level=1) + with tm.assert_produces_warning(FutureWarning, match="deprecated"): + getattr(df4, fn)("US/Pacific", level=1) tm.assert_index_equal(df3.index.levels[0], l0) assert not df3.index.levels[0].equals(l0_expected) @@ -103,17 +113,20 @@ def test_tz_convert_and_localize(self, fn): # Not DatetimeIndex / PeriodIndex with pytest.raises(TypeError, match="DatetimeIndex"): df = DataFrame(index=int_idx) - getattr(df, fn)("US/Pacific") + with tm.assert_produces_warning(FutureWarning, match="deprecated"): + getattr(df, fn)("US/Pacific") # Not DatetimeIndex / PeriodIndex with pytest.raises(TypeError, match="DatetimeIndex"): df = DataFrame(np.ones(5), MultiIndex.from_arrays([int_idx, l0])) - getattr(df, fn)("US/Pacific", level=0) + with tm.assert_produces_warning(FutureWarning, match="deprecated"): + getattr(df, fn)("US/Pacific", level=0) # Invalid level with pytest.raises(ValueError, match="not valid"): df = DataFrame(index=l0) - getattr(df, fn)("US/Pacific", level=1) + with tm.assert_produces_warning(FutureWarning, match="deprecated"): + getattr(df, fn)("US/Pacific", level=1) @pytest.mark.parametrize("copy", [True, False]) def test_tz_convert_copy_inplace_mutate(self, copy, frame_or_series): @@ -123,7 +136,8 @@ def test_tz_convert_copy_inplace_mutate(self, copy, frame_or_series): index=date_range("20131027", periods=5, freq="h", tz="Europe/Berlin"), ) orig = obj.copy() - result = obj.tz_convert("UTC", copy=copy) + with tm.assert_produces_warning(FutureWarning, match=depr_msg2): + result = obj.tz_convert("UTC", copy=copy) expected = frame_or_series(np.arange(0, 5), index=obj.index.tz_convert("UTC")) tm.assert_equal(result, expected) tm.assert_equal(obj, orig) diff --git a/pandas/tests/frame/methods/test_tz_localize.py b/pandas/tests/frame/methods/test_tz_localize.py index b167afc17f484..dfde47e8ad8c9 100644 --- a/pandas/tests/frame/methods/test_tz_localize.py +++ b/pandas/tests/frame/methods/test_tz_localize.py @@ -10,6 +10,8 @@ ) import pandas._testing as tm +depr_msg = "(Series|DataFrame).tz_localize is deprecated" + class TestTZLocalize: # See also: @@ -21,7 +23,8 @@ def test_tz_localize(self, frame_or_series): obj = DataFrame({"a": 1}, index=rng) obj = tm.get_obj(obj, frame_or_series) - result = obj.tz_localize("utc") + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + result = obj.tz_localize("utc") expected = DataFrame({"a": 1}, rng.tz_localize("UTC")) expected = tm.get_obj(expected, frame_or_series) @@ -34,7 +37,8 @@ def test_tz_localize_axis1(self): df = DataFrame({"a": 1}, index=rng) df = df.T - result = df.tz_localize("utc", axis=1) + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + result = df.tz_localize("utc", axis=1) assert result.columns.tz is timezone.utc expected = DataFrame({"a": 1}, rng.tz_localize("UTC")) @@ -48,7 +52,8 @@ def test_tz_localize_naive(self, frame_or_series): ts = frame_or_series(ts) with pytest.raises(TypeError, match="Already tz-aware"): - ts.tz_localize("US/Eastern") + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + ts.tz_localize("US/Eastern") @pytest.mark.parametrize("copy", [True, False]) def test_tz_localize_copy_inplace_mutate(self, copy, frame_or_series): @@ -57,7 +62,8 @@ def test_tz_localize_copy_inplace_mutate(self, copy, frame_or_series): np.arange(0, 5), index=date_range("20131027", periods=5, freq="1h", tz=None) ) orig = obj.copy() - result = obj.tz_localize("UTC", copy=copy) + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + result = obj.tz_localize("UTC", copy=copy) expected = frame_or_series( np.arange(0, 5), index=date_range("20131027", periods=5, freq="1h", tz="UTC"), diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py index 09a5cda4b3458..ee07af067f1ff 100644 --- a/pandas/tests/frame/test_arithmetic.py +++ b/pandas/tests/frame/test_arithmetic.py @@ -1228,7 +1228,7 @@ def test_frame_add_tz_mismatch_converts_to_utc(self): np.random.default_rng(2).standard_normal(len(rng)), index=rng, columns=["a"] ) - df_moscow = df.tz_convert("Europe/Moscow") + df_moscow = df.set_axis(df.index.tz_convert("Europe/Moscow")) result = df + df_moscow assert result.index.tz is timezone.utc diff --git a/pandas/tests/frame/test_block_internals.py b/pandas/tests/frame/test_block_internals.py index 9e8d92e832d01..4028157a28db1 100644 --- a/pandas/tests/frame/test_block_internals.py +++ b/pandas/tests/frame/test_block_internals.py @@ -311,14 +311,16 @@ def test_consolidate_datetime64(self): ser_starting = df.starting ser_starting.index = ser_starting.values - ser_starting = ser_starting.tz_localize("US/Eastern") - ser_starting = ser_starting.tz_convert("UTC") + ser_starting = ser_starting.set_axis( + ser_starting.index.tz_localize("US/Eastern") + ) + ser_starting = ser_starting.set_axis(ser_starting.index.tz_convert("UTC")) ser_starting.index.name = "starting" ser_ending = df.ending ser_ending.index = ser_ending.values - ser_ending = ser_ending.tz_localize("US/Eastern") - ser_ending = ser_ending.tz_convert("UTC") + ser_ending = ser_ending.set_axis(ser_ending.index.tz_localize("US/Eastern")) + ser_ending = ser_ending.set_axis(ser_ending.index.tz_convert("UTC")) ser_ending.index.name = "ending" df.starting = ser_starting.index diff --git a/pandas/tests/generic/test_finalize.py b/pandas/tests/generic/test_finalize.py index 0f7ae998a4b2b..53a5693199a7f 100644 --- a/pandas/tests/generic/test_finalize.py +++ b/pandas/tests/generic/test_finalize.py @@ -402,6 +402,14 @@ def ndframe_method(request): @pytest.mark.filterwarnings( "ignore:DataFrame.fillna with 'method' is deprecated:FutureWarning", "ignore:last is deprecated:FutureWarning", + "ignore:DataFrame.tz_localize is deprecated:FutureWarning", + "ignore:Series.tz_localize is deprecated:FutureWarning", + "ignore:DataFrame.tz_convert is deprecated:FutureWarning", + "ignore:Series.tz_convert is deprecated:FutureWarning", + "ignore:DataFrame.to_period is deprecated:FutureWarning", + "ignore:Series.to_period is deprecated:FutureWarning", + "ignore:DataFrame.to_timestamp is deprecated:FutureWarning", + "ignore:Series.to_timestamp is deprecated:FutureWarning", ) def test_finalize_called(ndframe_method): cls, init_args, method = ndframe_method diff --git a/pandas/tests/indexes/datetimes/test_partial_slicing.py b/pandas/tests/indexes/datetimes/test_partial_slicing.py index c4e23154b7ffc..8618c0bdc2dcb 100644 --- a/pandas/tests/indexes/datetimes/test_partial_slicing.py +++ b/pandas/tests/indexes/datetimes/test_partial_slicing.py @@ -447,8 +447,8 @@ def test_getitem_with_datestring_with_UTC_offset(self, start, end): with pytest.raises(ValueError, match="Both dates must"): df[start : end[:-4] + "1:00"] + df.index = df.index.tz_localize(None) with pytest.raises(ValueError, match="The index must be timezone"): - df = df.tz_localize(None) df[start:end] def test_slice_reduce_to_series(self): diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py index 18af18ade85f4..88e9f036fb7da 100644 --- a/pandas/tests/io/excel/test_writers.py +++ b/pandas/tests/io/excel/test_writers.py @@ -757,7 +757,8 @@ def test_to_excel_periodindex(self, tsframe, path): with ExcelFile(path) as reader: rs = pd.read_excel(reader, sheet_name="sht1", index_col=0) - tm.assert_frame_equal(xp, rs.to_period("M")) + rs.index = rs.index.to_period("M") + tm.assert_frame_equal(xp, rs) def test_to_excel_multiindex(self, merge_cells, frame, path): arrays = np.arange(len(frame.index) * 2, dtype=np.int64).reshape(2, -1) diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index a384fd9cdc8f2..4a115c4327731 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -361,7 +361,7 @@ def test_business_freq(self): def test_business_freq_convert(self): bts = tm.makeTimeSeries(300).asfreq("BME") - ts = bts.to_period("M") + ts = bts.set_axis(bts.index.to_period("M")) _, ax = mpl.pyplot.subplots() bts.plot(ax=ax) assert ax.get_lines()[0].get_xydata()[0, 0] == ts.index[0].ordinal @@ -677,7 +677,8 @@ def test_secondary_y_ts(self): assert not hasattr(ax, "right_ax") axes = fig.get_axes() line = ax.get_lines()[0] - xp = Series(line.get_ydata(), line.get_xdata()).to_timestamp() + xp = Series(line.get_ydata(), line.get_xdata()) + xp.index = xp.index.to_timestamp() tm.assert_series_equal(ser, xp) assert ax.get_yaxis().get_ticks_position() == "right" assert not axes[0].get_yaxis().get_visible() diff --git a/pandas/tests/plotting/test_series.py b/pandas/tests/plotting/test_series.py index bf4474d085b11..42ed4b633d95b 100644 --- a/pandas/tests/plotting/test_series.py +++ b/pandas/tests/plotting/test_series.py @@ -162,7 +162,7 @@ def test_ts_area_lim_xcompat(self, ts): def test_ts_tz_area_lim_xcompat(self, ts): tz_ts = ts.copy() - tz_ts.index = tz_ts.tz_localize("GMT").tz_convert("CET") + tz_ts.index = tz_ts # ._values.tz_localize("GMT").tz_convert("CET") _, ax = mpl.pyplot.subplots() ax = tz_ts.plot.area(stacked=False, x_compat=True, ax=ax) xmin, xmax = ax.get_xlim() @@ -173,7 +173,7 @@ def test_ts_tz_area_lim_xcompat(self, ts): def test_ts_tz_area_lim_xcompat_secondary_y(self, ts): tz_ts = ts.copy() - tz_ts.index = tz_ts.tz_localize("GMT").tz_convert("CET") + tz_ts.index = tz_ts # .index.tz_localize("GMT").tz_convert("CET") _, ax = mpl.pyplot.subplots() ax = tz_ts.plot.area(stacked=False, secondary_y=True, ax=ax) xmin, xmax = ax.get_xlim() diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py index e0ba7902a8a6c..286a31568776d 100644 --- a/pandas/tests/resample/test_datetime_index.py +++ b/pandas/tests/resample/test_datetime_index.py @@ -925,20 +925,25 @@ def test_resample_origin_epoch_with_tz_day_vs_24h(unit): tm.assert_series_equal(result_1, result_2) # check that we have the same behavior with epoch even if we are not timezone aware - ts_no_tz = ts_1.tz_localize(None) + ts_no_tz = ts_1.set_axis(ts_1.index.tz_localize(None)) result_3 = ts_no_tz.resample("D", origin="epoch").mean() + result_3.index = result_3.index.tz_localize(rng.tz) result_4 = ts_no_tz.resample("24h", origin="epoch").mean() - tm.assert_series_equal(result_1, result_3.tz_localize(rng.tz), check_freq=False) - tm.assert_series_equal(result_1, result_4.tz_localize(rng.tz), check_freq=False) + result_4.index = result_4.index.tz_localize(rng.tz) + tm.assert_series_equal(result_1, result_3, check_freq=False) + tm.assert_series_equal(result_1, result_4, check_freq=False) # check that we have the similar results with two different timezones (+2H and +5H) start, end = "2000-10-01 23:30:00+0200", "2000-12-02 00:30:00+0200" rng = date_range(start, end, freq="7min").as_unit(unit) ts_2 = Series(random_values, index=rng) result_5 = ts_2.resample("D", origin="epoch").mean() + result_5.index = result_5.index.tz_localize(None) result_6 = ts_2.resample("24h", origin="epoch").mean() - tm.assert_series_equal(result_1.tz_localize(None), result_5.tz_localize(None)) - tm.assert_series_equal(result_1.tz_localize(None), result_6.tz_localize(None)) + result_6.index = result_6.index.tz_localize(None) + result_1.index = result_1.index.tz_localize(None) + tm.assert_series_equal(result_1, result_5) + tm.assert_series_equal(result_1, result_6) def test_resample_origin_with_day_freq_on_dst(unit): @@ -1025,7 +1030,8 @@ def test_period_with_agg(): dtype="float64", ) - expected = s2.to_timestamp().resample("D").mean().to_period() + expected = s2.set_axis(s2.index.to_timestamp()).resample("D").mean() + expected.index = expected.index.to_period() result = s2.resample("D").agg(lambda x: x.mean()) tm.assert_series_equal(result, expected) @@ -1131,7 +1137,8 @@ def test_resample_anchored_intraday(simple_date_range_series, unit): df = DataFrame(rng.month, index=rng) result = df.resample("ME").mean() - expected = df.resample("ME", kind="period").mean().to_timestamp(how="end") + expected = df.resample("ME", kind="period").mean() + expected.index = expected.index.to_timestamp(how="end") expected.index += Timedelta(1, "ns") - Timedelta(1, "D") expected.index = expected.index.as_unit(unit)._with_freq("infer") assert expected.index.freq == "ME" @@ -1139,7 +1146,7 @@ def test_resample_anchored_intraday(simple_date_range_series, unit): result = df.resample("ME", closed="left").mean() exp = df.shift(1, freq="D").resample("ME", kind="period").mean() - exp = exp.to_timestamp(how="end") + exp.index = exp.index.to_timestamp(how="end") exp.index = exp.index + Timedelta(1, "ns") - Timedelta(1, "D") exp.index = exp.index.as_unit(unit)._with_freq("infer") @@ -1150,7 +1157,8 @@ def test_resample_anchored_intraday(simple_date_range_series, unit): df = DataFrame(rng.month, index=rng) result = df.resample("Q").mean() - expected = df.resample("Q", kind="period").mean().to_timestamp(how="end") + expected = df.resample("Q", kind="period").mean() + expected.index = expected.index.to_timestamp(how="end") expected.index += Timedelta(1, "ns") - Timedelta(1, "D") expected.index._data.freq = "Q" expected.index._freq = lib.no_default @@ -1159,7 +1167,7 @@ def test_resample_anchored_intraday(simple_date_range_series, unit): result = df.resample("Q", closed="left").mean() expected = df.shift(1, freq="D").resample("Q", kind="period", closed="left").mean() - expected = expected.to_timestamp(how="end") + expected.index = expected.index.to_timestamp(how="end") expected.index += Timedelta(1, "ns") - Timedelta(1, "D") expected.index._data.freq = "Q" expected.index._freq = lib.no_default diff --git a/pandas/tests/resample/test_period_index.py b/pandas/tests/resample/test_period_index.py index 6ad09f12525b4..0efb5defcc5cd 100644 --- a/pandas/tests/resample/test_period_index.py +++ b/pandas/tests/resample/test_period_index.py @@ -49,12 +49,13 @@ def test_asfreq(self, series_and_frame, freq, kind): obj = series_and_frame if kind == "timestamp": - expected = obj.to_timestamp().resample(freq).asfreq() + expected = obj.set_axis(obj.index.to_timestamp()).resample(freq).asfreq() else: start = obj.index[0].to_timestamp(how="start") end = (obj.index[-1] + obj.index.freq).to_timestamp(how="start") new_index = date_range(start=start, end=end, freq=freq, inclusive="left") - expected = obj.to_timestamp().reindex(new_index).to_period(freq) + expected = obj.set_axis(obj.index.to_timestamp()).reindex(new_index) + expected = expected.set_axis(expected.index.to_period(freq)) result = obj.resample(freq, kind=kind).asfreq() tm.assert_almost_equal(result, expected) @@ -67,7 +68,7 @@ def test_asfreq_fill_value(self, series): (s.index[-1]).to_timestamp(how="start"), freq="1h", ) - expected = s.to_timestamp().reindex(new_index, fill_value=4.0) + expected = s.set_axis(s.index.to_timestamp()).reindex(new_index, fill_value=4.0) result = s.resample("1h", kind="timestamp").asfreq(fill_value=4.0) tm.assert_series_equal(result, expected) @@ -77,7 +78,9 @@ def test_asfreq_fill_value(self, series): (frame.index[-1]).to_timestamp(how="start"), freq="1h", ) - expected = frame.to_timestamp().reindex(new_index, fill_value=3.0) + expected = frame.set_axis(frame.index.to_timestamp()).reindex( + new_index, fill_value=3.0 + ) result = frame.resample("1h", kind="timestamp").asfreq(fill_value=3.0) tm.assert_frame_equal(result, expected) @@ -114,8 +117,9 @@ def test_annual_upsample_cases( msg = r"PeriodDtype\[B\] is deprecated" with tm.assert_produces_warning(warn, match=msg): result = getattr(ts.resample(period, convention=conv), meth)() - expected = result.to_timestamp(period, how=conv) - expected = expected.asfreq(offset, meth).to_period() + expected = result.set_axis(result.index.to_timestamp(period, how=conv)) + expected = expected.asfreq(offset, meth) + expected = expected.set_axis(expected.index.to_period()) tm.assert_series_equal(result, expected) def test_basic_downsample(self, simple_period_range_series): @@ -155,8 +159,9 @@ def test_basic_upsample(self, freq, simple_period_range_series): result = ts.resample("y-dec").mean() resampled = result.resample(freq, convention="end").ffill() - expected = result.to_timestamp(freq, how="end") - expected = expected.asfreq(freq, "ffill").to_period(freq) + expected = result.set_axis(result.index.to_timestamp(freq, how="end")) + expected = expected.asfreq(freq, "ffill") + expected = expected.set_axis(expected.index.to_period(freq)) tm.assert_series_equal(resampled, expected) def test_upsample_with_limit(self): @@ -197,8 +202,11 @@ def test_quarterly_upsample( msg = r"PeriodDtype\[B\] is deprecated" with tm.assert_produces_warning(warn, match=msg): result = ts.resample(period, convention=convention).ffill() - expected = result.to_timestamp(period, how=convention) - expected = expected.asfreq(offset, "ffill").to_period() + expected = result.set_axis( + result.index.to_timestamp(period, how=convention) + ) + expected = expected.asfreq(offset, "ffill") + expected = expected.set_axis(expected.index.to_period()) tm.assert_series_equal(result, expected) @pytest.mark.parametrize("target", ["D", "B"]) @@ -210,8 +218,11 @@ def test_monthly_upsample(self, target, convention, simple_period_range_series): msg = r"PeriodDtype\[B\] is deprecated" with tm.assert_produces_warning(warn, match=msg): result = ts.resample(target, convention=convention).ffill() - expected = result.to_timestamp(target, how=convention) - expected = expected.asfreq(target, "ffill").to_period() + expected = result.set_axis( + result.index.to_timestamp(target, how=convention) + ) + expected = expected.asfreq(target, "ffill") + expected = expected.set_axis(expected.index.to_period()) tm.assert_series_equal(result, expected) def test_resample_basic(self): @@ -227,7 +238,7 @@ def test_resample_basic(self): name="idx", ) expected = Series([34.5, 79.5], index=index) - result = s.to_period().resample("min", kind="period").mean() + result = s.set_axis(s.index.to_period()).resample("min", kind="period").mean() tm.assert_series_equal(result, expected) result2 = s.resample("min", kind="period").mean() tm.assert_series_equal(result2, expected) @@ -274,7 +285,7 @@ def test_with_local_timezone_pytz(self): index = date_range(start, end, freq="h") series = Series(1, index=index) - series = series.tz_convert(local_timezone) + series.index = series.index.tz_convert(local_timezone) result = series.resample("D", kind="period").mean() # Create the expected series @@ -315,7 +326,7 @@ def test_with_local_timezone_dateutil(self): index = date_range(start, end, freq="h", name="idx") series = Series(1, index=index) - series = series.tz_convert(local_timezone) + series.index = series.index.tz_convert(local_timezone) result = series.resample("D", kind="period").mean() # Create the expected series @@ -331,7 +342,7 @@ def test_resample_nonexistent_time_bin_edge(self): # GH 19375 index = date_range("2017-03-12", "2017-03-12 1:45:00", freq="15min") s = Series(np.zeros(len(index)), index=index) - expected = s.tz_localize("US/Pacific") + expected = s.set_axis(s.index.tz_localize("US/Pacific")) expected.index = pd.DatetimeIndex(expected.index, freq="900s") result = expected.resample("900s").mean() tm.assert_series_equal(result, expected) @@ -384,15 +395,20 @@ def test_weekly_upsample(self, day, target, convention, simple_period_range_seri msg = r"PeriodDtype\[B\] is deprecated" with tm.assert_produces_warning(warn, match=msg): result = ts.resample(target, convention=convention).ffill() - expected = result.to_timestamp(target, how=convention) - expected = expected.asfreq(target, "ffill").to_period() + expected = result.set_axis( + result.index.to_timestamp(target, how=convention) + ) + expected = expected.asfreq(target, "ffill") + expected = expected.set_axis(expected.index.to_period()) tm.assert_series_equal(result, expected) def test_resample_to_timestamps(self, simple_period_range_series): ts = simple_period_range_series("1/1/1990", "12/31/1995", freq="M") result = ts.resample("Y-DEC", kind="timestamp").mean() - expected = ts.to_timestamp(how="start").resample("Y-DEC").mean() + expected = ( + ts.set_axis(ts.index.to_timestamp(how="start")).resample("Y-DEC").mean() + ) tm.assert_series_equal(result, expected) @pytest.mark.parametrize("month", MONTHS) @@ -400,7 +416,7 @@ def test_resample_to_quarterly(self, simple_period_range_series, month): ts = simple_period_range_series("1990", "1992", freq=f"Y-{month}") quar_ts = ts.resample(f"Q-{month}").ffill() - stamps = ts.to_timestamp("D", how="start") + stamps = ts.set_axis(ts.index.to_timestamp("D", how="start")) qdates = period_range( ts.index[0].asfreq("D", "start"), ts.index[-1].asfreq("D", "end"), @@ -430,9 +446,10 @@ def test_resample_fill_missing(self): s = Series(np.random.default_rng(2).standard_normal(4), index=rng) - stamps = s.to_timestamp() + stamps = s.set_axis(s.index.to_timestamp()) filled = s.resample("Y").ffill() - expected = stamps.resample("Y").ffill().to_period("Y") + expected = stamps.resample("Y").ffill() + expected = expected.set_axis(expected.index.to_period("Y")) tm.assert_series_equal(filled, expected) def test_cant_fill_missing_dups(self): @@ -447,9 +464,9 @@ def test_cant_fill_missing_dups(self): def test_resample_5minute(self, freq, kind): rng = period_range("1/1/2000", "1/5/2000", freq="min") ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng) - expected = ts.to_timestamp().resample(freq).mean() + expected = ts.set_axis(ts.index.to_timestamp()).resample(freq).mean() if kind != "timestamp": - expected = expected.to_period(freq) + expected = expected.set_axis(expected.index.to_period(freq)) result = ts.resample(freq, kind=kind).mean() tm.assert_series_equal(result, expected) @@ -492,8 +509,8 @@ def test_resample_tz_localized(self): dr = date_range(start="2012-4-13", end="2012-5-1") ts = Series(range(len(dr)), index=dr) - ts_utc = ts.tz_localize("UTC") - ts_local = ts_utc.tz_convert("America/Los_Angeles") + ts_utc = ts.set_axis(ts.index.tz_localize("UTC")) + ts_local = ts_utc.set_axis(ts_utc.index.tz_convert("America/Los_Angeles")) result = ts_local.resample("W").mean() @@ -502,7 +519,8 @@ def test_resample_tz_localized(self): x.replace(tzinfo=None) for x in ts_local_naive.index.to_pydatetime() ] - exp = ts_local_naive.resample("W").mean().tz_localize("America/Los_Angeles") + exp = ts_local_naive.resample("W").mean() + exp.index = exp.index.tz_localize("America/Los_Angeles") exp.index = pd.DatetimeIndex(exp.index, freq="W") tm.assert_series_equal(result, exp) @@ -574,7 +592,8 @@ def test_quarterly_resampling(self): ts = Series(np.arange(10), index=rng) result = ts.resample("Y").mean() - exp = ts.to_timestamp().resample("Y").mean().to_period() + exp = ts.set_axis(ts.index.to_timestamp()).resample("Y").mean() + exp = exp.set_axis(exp.index.to_period()) tm.assert_series_equal(result, exp) def test_resample_weekly_bug_1726(self): @@ -758,7 +777,8 @@ def test_upsampling_ohlc(self, freq, period_mult, kind): # GH 13083 pi = period_range(start="2000", freq="D", periods=10) s = Series(range(len(pi)), index=pi) - expected = s.to_timestamp().resample(freq).ohlc().to_period(freq) + expected = s.set_axis(s.index.to_timestamp()).resample(freq).ohlc() + expected = expected.set_axis(expected.index.to_period(freq)) # timestamp-based resampling doesn't include all sub-periods # of the last original period, so extend accordingly: @@ -851,9 +871,13 @@ def test_resample_with_offset(self, start, end, start_freq, end_freq, offset): pi = period_range(start, end, freq=start_freq) ser = Series(np.arange(len(pi)), index=pi) result = ser.resample(end_freq, offset=offset).mean() - result = result.to_timestamp(end_freq) + result = result.set_axis(result.index.to_timestamp(end_freq)) - expected = ser.to_timestamp().resample(end_freq, offset=offset).mean() + expected = ( + ser.set_axis(ser.index.to_timestamp()) + .resample(end_freq, offset=offset) + .mean() + ) tm.assert_series_equal(result, expected) def test_resample_with_offset_month(self): @@ -861,8 +885,10 @@ def test_resample_with_offset_month(self): pi = period_range("19910905 12:00", "19910909 1:00", freq="h") ser = Series(np.arange(len(pi)), index=pi) result = ser.resample("M", offset="3h").mean() - result = result.to_timestamp("M") - expected = ser.to_timestamp().resample("ME", offset="3h").mean() + result = result.set_axis(result.index.to_timestamp("M")) + expected = ( + ser.set_axis(ser.index.to_timestamp()).resample("ME", offset="3h").mean() + ) # TODO: is non-tick the relevant characteristic? (GH 33815) expected.index = expected.index._with_freq(None) tm.assert_series_equal(result, expected) @@ -904,7 +930,7 @@ def test_sum_min_count(self): index = date_range(start="2018", freq="ME", periods=6) data = np.ones(6) data[3:6] = np.nan - s = Series(data, index).to_period() + s = Series(data, index.to_period()) result = s.resample("Q").sum(min_count=1) expected = Series( [3.0, np.nan], index=PeriodIndex(["2018Q1", "2018Q2"], freq="Q-DEC") diff --git a/pandas/tests/reshape/concat/test_concat.py b/pandas/tests/reshape/concat/test_concat.py index 74c79d20a3fb3..fce057287e320 100644 --- a/pandas/tests/reshape/concat/test_concat.py +++ b/pandas/tests/reshape/concat/test_concat.py @@ -36,8 +36,8 @@ def test_append_concat(self): s1 = Series(np.random.default_rng(2).standard_normal(10), d1) s2 = Series(np.random.default_rng(2).standard_normal(10), d2) - s1 = s1.to_period() - s2 = s2.to_period() + s1.index = s1.index.to_period() + s2.index = s2.index.to_period() # drops index result = concat([s1, s2]) diff --git a/pandas/tests/series/methods/test_align.py b/pandas/tests/series/methods/test_align.py index cb60cd2e5bcf3..e9609cb343b33 100644 --- a/pandas/tests/series/methods/test_align.py +++ b/pandas/tests/series/methods/test_align.py @@ -195,7 +195,7 @@ def test_align_with_dataframe_method(method): def test_align_dt64tzindex_mismatched_tzs(): idx1 = date_range("2001", periods=5, freq="h", tz="US/Eastern") ser = Series(np.random.default_rng(2).standard_normal(len(idx1)), index=idx1) - ser_central = ser.tz_convert("US/Central") + ser_central = ser.set_axis(ser.index.tz_convert("US/Central")) # different timezones convert to UTC new1, new2 = ser.align(ser_central) diff --git a/pandas/tests/series/methods/test_map.py b/pandas/tests/series/methods/test_map.py index ae6c62e95f696..da61d2670d3da 100644 --- a/pandas/tests/series/methods/test_map.py +++ b/pandas/tests/series/methods/test_map.py @@ -541,7 +541,8 @@ def test_map_missing_mixed(vals, mapping, exp): def test_map_scalar_on_date_time_index_aware_series(): # GH 25959 # Calling map on a localized time series should not cause an error - series = tm.makeTimeSeries(nper=30).tz_localize("UTC") + series = tm.makeTimeSeries(nper=30) + series.index = series.index.tz_localize("UTC") result = Series(series.index).map(lambda x: 1) tm.assert_series_equal(result, Series(np.ones(30), dtype="int64")) diff --git a/pandas/tests/series/methods/test_tz_localize.py b/pandas/tests/series/methods/test_tz_localize.py index c2b1569d3f391..13e71067f05b5 100644 --- a/pandas/tests/series/methods/test_tz_localize.py +++ b/pandas/tests/series/methods/test_tz_localize.py @@ -78,13 +78,17 @@ def test_tz_localize_nonexistent(self, warsaw, method, exp): ser = Series(1, index=dti) df = ser.to_frame() + depr_msg = r"\.tz_localize is deprecated" + if method == "raise": with tm.external_error_raised(pytz.NonExistentTimeError): dti.tz_localize(tz, nonexistent=method) with tm.external_error_raised(pytz.NonExistentTimeError): - ser.tz_localize(tz, nonexistent=method) + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + ser.tz_localize(tz, nonexistent=method) with tm.external_error_raised(pytz.NonExistentTimeError): - df.tz_localize(tz, nonexistent=method) + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + df.tz_localize(tz, nonexistent=method) elif exp == "invalid": msg = ( @@ -95,16 +99,20 @@ def test_tz_localize_nonexistent(self, warsaw, method, exp): with pytest.raises(ValueError, match=msg): dti.tz_localize(tz, nonexistent=method) with pytest.raises(ValueError, match=msg): - ser.tz_localize(tz, nonexistent=method) + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + ser.tz_localize(tz, nonexistent=method) with pytest.raises(ValueError, match=msg): - df.tz_localize(tz, nonexistent=method) + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + df.tz_localize(tz, nonexistent=method) else: - result = ser.tz_localize(tz, nonexistent=method) + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + result = ser.tz_localize(tz, nonexistent=method) expected = Series(1, index=DatetimeIndex([exp] * n, tz=tz)) tm.assert_series_equal(result, expected) - result = df.tz_localize(tz, nonexistent=method) + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + result = df.tz_localize(tz, nonexistent=method) expected = expected.to_frame() tm.assert_frame_equal(result, expected) @@ -116,8 +124,12 @@ def test_series_tz_localize_empty(self, tzstr): # GH#2248 ser = Series(dtype=object) - ser2 = ser.tz_localize("utc") + msg = "Series.tz_localize is deprecated" + + with tm.assert_produces_warning(FutureWarning, match=msg): + ser2 = ser.tz_localize("utc") assert ser2.index.tz == timezone.utc - ser2 = ser.tz_localize(tzstr) + with tm.assert_produces_warning(FutureWarning, match=msg): + ser2 = ser.tz_localize(tzstr) timezones.tz_compare(ser2.index.tz, timezones.maybe_get_tz(tzstr)) diff --git a/pandas/tests/series/test_arithmetic.py b/pandas/tests/series/test_arithmetic.py index e9eb906a9cf10..2947a3c943c5e 100644 --- a/pandas/tests/series/test_arithmetic.py +++ b/pandas/tests/series/test_arithmetic.py @@ -729,8 +729,8 @@ def test_series_add_tz_mismatch_converts_to_utc(self): result = ser1 + ser2 - uts1 = ser1.tz_convert("utc") - uts2 = ser2.tz_convert("utc") + uts1 = ser1.set_axis(ser1.index.tz_convert("utc")) + uts2 = ser2.set_axis(ser2.index.tz_convert("utc")) expected = uts1 + uts2 assert result.index.tz is timezone.utc @@ -740,7 +740,7 @@ def test_series_add_aware_naive_raises(self): rng = date_range("1/1/2011", periods=10, freq="h") ser = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng) - ser_utc = ser.tz_localize("utc") + ser_utc = ser.set_axis(ser.index.tz_localize("utc")) msg = "Cannot join tz-naive with tz-aware DatetimeIndex" with pytest.raises(Exception, match=msg):