Skip to content

Commit a956f9b

Browse files
committed
Preserve freq in TimedeltaIndex subtraction
1 parent 3e1d6d5 commit a956f9b

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

pandas/core/arrays/datetimelike.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1089,6 +1089,8 @@ def _get_arithmetic_result_freq(self, other) -> BaseOffset | None:
10891089
# e.g. TestTimedelta64ArithmeticUnsorted::test_timedelta
10901090
# Day is unambiguously 24h
10911091
return self.freq
1092+
elif lib.is_np_dtype(self.dtype, "M") and isinstance(other, Timestamp):
1093+
return self.freq
10921094

10931095
return None
10941096

pandas/tests/arrays/test_datetimelike.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1356,3 +1356,40 @@ def test_from_pandas_array(dtype):
13561356
result = idx_cls(arr)
13571357
expected = idx_cls(data)
13581358
tm.assert_index_equal(result, expected)
1359+
1360+
1361+
@pytest.mark.parametrize(
1362+
"dti, ts",
1363+
[
1364+
(
1365+
pd.date_range("2021-01-01", periods=5, freq="D"),
1366+
Timestamp("2019-01-03"),
1367+
),
1368+
(
1369+
pd.date_range("2020-02-10 10:00", periods=5, freq="h"),
1370+
Timestamp("2020-02-10 08:00"),
1371+
),
1372+
(
1373+
pd.date_range("2022-01-01", periods=5, freq="D"),
1374+
Timestamp("2020-01-01"),
1375+
),
1376+
(
1377+
pd.date_range("2018-01-01", periods=5, freq="D"),
1378+
Timestamp("2019-01-01"),
1379+
),
1380+
],
1381+
)
1382+
@pytest.mark.parametrize("periods", [1, -2, 0])
1383+
def test_shift_after_dti_sub_timestamp_various_inputs(dti, ts, periods):
1384+
# https://github.com/pandas-dev/pandas/issues/62094
1385+
ind = dti - ts
1386+
1387+
assert ind.freq is not None
1388+
assert ind.freq == dti.freq
1389+
1390+
result = ind.shift(periods)
1391+
1392+
offset = pd.Timedelta(periods, unit=ind.freq.name)
1393+
expected = ind + offset
1394+
1395+
tm.assert_index_equal(result, expected)

0 commit comments

Comments
 (0)