Skip to content

Commit 5dc83c6

Browse files
committed
BUG: TimedeltaIndex.shift() infers freq when possible (GH#62094)
1 parent d42575f commit 5dc83c6

File tree

2 files changed

+16
-20
lines changed

2 files changed

+16
-20
lines changed

pandas/core/arrays/datetimelike.py

Lines changed: 7 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1070,26 +1070,13 @@ def _get_arithmetic_result_freq(self, other) -> BaseOffset | None:
10701070
elif isinstance(self.freq, Tick):
10711071
# In these cases
10721072
return self.freq
1073-
elif self.dtype.kind == "m" and isinstance(other, Timedelta):
1074-
return self.freq
1075-
elif (
1076-
self.dtype.kind == "m"
1077-
and isinstance(other, Timestamp)
1078-
and (other.tz is None or timezones.is_utc(other.tz))
1079-
):
1080-
# e.g. test_td64arr_add_sub_datetimelike_scalar tdarr + timestamp
1081-
# gives a DatetimeArray. As long as the timestamp has no timezone
1082-
# or UTC, the result can retain a Day freq.
1083-
return self.freq
1084-
elif (
1085-
lib.is_np_dtype(self.dtype, "M")
1086-
and isinstance(self.freq, Day)
1087-
and isinstance(other, Timedelta)
1088-
):
1089-
# e.g. TestTimedelta64ArithmeticUnsorted::test_timedelta
1090-
# Day is unambiguously 24h
1091-
return self.freq
1092-
1073+
# If no explicit freq, use inferred_freq when the index is regular
1074+
elif self.freq is None:
1075+
inferred = self.inferred_freq
1076+
if inferred is not None:
1077+
offset = to_offset(inferred)
1078+
if isinstance(offset, Tick):
1079+
return offset
10931080
return None
10941081

10951082
@final

pandas/tests/indexes/timedeltas/test_arithmetic.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
# Other cases can be shared in tests.arithmetic.test_timedelta64
33
import numpy as np
44

5+
import pandas as pd
56
from pandas import (
67
NaT,
78
Timedelta,
@@ -49,3 +50,11 @@ def test_tdi_division(self, index_or_series):
4950
[31 * 86400, 31 * 86400, 31 * 86400 + 5 * 60 + 3, np.nan]
5051
)
5152
tm.assert_equal(result, expected)
53+
54+
def test_timedeltaindex_shift_infers_freq(self):
55+
# GH#62094: TimedeltaIndex.shift() should work if freq can be inferred
56+
ind = pd.date_range("1/1/2021", "1/5/2021") - pd.Timestamp("1/3/2019")
57+
shifted = ind.shift(1)
58+
expected = ind + Timedelta(days=1)
59+
tm.assert_index_equal(shifted, expected)
60+
assert shifted.freq == pd.tseries.frequencies.to_offset("D")

0 commit comments

Comments
 (0)