Skip to content

Commit 84cf2bd

Browse files
committed
BUG: TimedeltaIndex.shift() infers freq when possible (GH#62094)
1 parent 7863029 commit 84cf2bd

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

pandas/core/arrays/datetimelike.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1068,6 +1068,13 @@ def _get_arithmetic_result_freq(self, other) -> BaseOffset | None:
10681068
elif isinstance(self.freq, Tick):
10691069
# In these cases
10701070
return self.freq
1071+
# If no explicit freq, use inferred_freq when the index is regular
1072+
elif self.freq is None:
1073+
inferred = self.inferred_freq
1074+
if inferred is not None:
1075+
offset = to_offset(inferred)
1076+
if isinstance(offset, Tick):
1077+
return offset
10711078
return None
10721079

10731080
@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)