diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 61715397e8e0b..8fe3a32fe3d39 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -94,10 +94,8 @@ ) from pandas.core.dtypes.generic import ( ABCDataFrame, - ABCDatetimeIndex, ABCIndexClass, ABCMultiIndex, - ABCPeriodIndex, ABCSeries, ) from pandas.core.dtypes.missing import isna, notna @@ -8245,7 +8243,9 @@ def quantile(self, q=0.5, axis=0, numeric_only=True, interpolation="linear"): return result - def to_timestamp(self, freq=None, how="start", axis=0, copy=True) -> "DataFrame": + def to_timestamp( + self, freq=None, how: str = "start", axis: Axis = 0, copy: bool = True + ) -> "DataFrame": """ Cast to DatetimeIndex of timestamps, at *beginning* of period. @@ -8265,23 +8265,16 @@ def to_timestamp(self, freq=None, how="start", axis=0, copy=True) -> "DataFrame" ------- DataFrame with DatetimeIndex """ - new_data = self._data - if copy: - new_data = new_data.copy() + new_obj = self.copy(deep=copy) - axis = self._get_axis_number(axis) - if axis == 0: - assert isinstance(self.index, (ABCDatetimeIndex, ABCPeriodIndex)) - new_data.set_axis(1, self.index.to_timestamp(freq=freq, how=how)) - elif axis == 1: - assert isinstance(self.columns, (ABCDatetimeIndex, ABCPeriodIndex)) - new_data.set_axis(0, self.columns.to_timestamp(freq=freq, how=how)) - else: # pragma: no cover - raise AssertionError(f"Axis must be 0 or 1. Got {axis}") + axis_name = self._get_axis_name(axis) + old_ax = getattr(self, axis_name) + new_ax = old_ax.to_timestamp(freq=freq, how=how) - return self._constructor(new_data) + setattr(new_obj, axis_name, new_ax) + return new_obj - def to_period(self, freq=None, axis=0, copy=True) -> "DataFrame": + def to_period(self, freq=None, axis: Axis = 0, copy: bool = True) -> "DataFrame": """ Convert DataFrame from DatetimeIndex to PeriodIndex. @@ -8299,23 +8292,16 @@ def to_period(self, freq=None, axis=0, copy=True) -> "DataFrame": Returns ------- - TimeSeries with PeriodIndex + DataFrame with PeriodIndex """ - new_data = self._data - if copy: - new_data = new_data.copy() + new_obj = self.copy(deep=copy) - axis = self._get_axis_number(axis) - if axis == 0: - assert isinstance(self.index, ABCDatetimeIndex) - new_data.set_axis(1, self.index.to_period(freq=freq)) - elif axis == 1: - assert isinstance(self.columns, ABCDatetimeIndex) - new_data.set_axis(0, self.columns.to_period(freq=freq)) - else: # pragma: no cover - raise AssertionError(f"Axis must be 0 or 1. Got {axis}") + axis_name = self._get_axis_name(axis) + old_ax = getattr(self, axis_name) + new_ax = old_ax.to_period(freq=freq) - return self._constructor(new_data) + setattr(new_obj, axis_name, new_ax) + return new_obj def isin(self, values) -> "DataFrame": """