Skip to content

BUG: TimedeltaIndex.shift() infers freq when possible (GH#62094) #62095

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 7 additions & 20 deletions pandas/core/arrays/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -1070,26 +1070,13 @@ def _get_arithmetic_result_freq(self, other) -> BaseOffset | None:
elif isinstance(self.freq, Tick):
# In these cases
return self.freq
elif self.dtype.kind == "m" and isinstance(other, Timedelta):
return self.freq
elif (
self.dtype.kind == "m"
and isinstance(other, Timestamp)
and (other.tz is None or timezones.is_utc(other.tz))
):
# e.g. test_td64arr_add_sub_datetimelike_scalar tdarr + timestamp
# gives a DatetimeArray. As long as the timestamp has no timezone
# or UTC, the result can retain a Day freq.
return self.freq
elif (
lib.is_np_dtype(self.dtype, "M")
and isinstance(self.freq, Day)
and isinstance(other, Timedelta)
):
# e.g. TestTimedelta64ArithmeticUnsorted::test_timedelta
# Day is unambiguously 24h
return self.freq

# If no explicit freq, use inferred_freq when the index is regular
elif self.freq is None:
inferred = self.inferred_freq
if inferred is not None:
offset = to_offset(inferred)
if isinstance(offset, Tick):
return offset
return None

@final
Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/indexes/timedeltas/test_arithmetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# Other cases can be shared in tests.arithmetic.test_timedelta64
import numpy as np

import pandas as pd
from pandas import (
NaT,
Timedelta,
Expand Down Expand Up @@ -49,3 +50,11 @@ def test_tdi_division(self, index_or_series):
[31 * 86400, 31 * 86400, 31 * 86400 + 5 * 60 + 3, np.nan]
)
tm.assert_equal(result, expected)

def test_timedeltaindex_shift_infers_freq(self):
# GH#62094: TimedeltaIndex.shift() should work if freq can be inferred
ind = pd.date_range("1/1/2021", "1/5/2021") - pd.Timestamp("1/3/2019")
shifted = ind.shift(1)
expected = ind + Timedelta(days=1)
tm.assert_index_equal(shifted, expected)
assert shifted.freq == pd.tseries.frequencies.to_offset("D")
Loading