Skip to content

Commit 025c56f

Browse files
authored
BUG: TDI divison giving bogus .freq (#51575)
* BUG: TDI divison giving bogus .freq * GH ref
1 parent b99e296 commit 025c56f

File tree

3 files changed

+26
-11
lines changed

3 files changed

+26
-11
lines changed

doc/source/whatsnew/v2.1.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,7 @@ Datetimelike
125125
Timedelta
126126
^^^^^^^^^
127127
- Bug in :meth:`Timedelta.round` with values close to the implementation bounds returning incorrect results instead of raising ``OutOfBoundsTimedelta`` (:issue:`51494`)
128+
- Bug in :class:`TimedeltaIndex` division or multiplication leading to ``.freq`` of "0 Days" instead of ``None`` (:issue:`51575`)
128129
-
129130

130131
Timezones

pandas/core/arrays/timedeltas.py

+7-11
Original file line numberDiff line numberDiff line change
@@ -467,6 +467,9 @@ def __mul__(self, other) -> TimedeltaArray:
467467
freq = None
468468
if self.freq is not None and not isna(other):
469469
freq = self.freq * other
470+
if freq.n == 0:
471+
# GH#51575 Better to have no freq than an incorrect one
472+
freq = None
470473
return type(self)._simple_new(result, dtype=result.dtype, freq=freq)
471474

472475
if not hasattr(other, "dtype"):
@@ -526,17 +529,10 @@ def _scalar_divlike_op(self, other, op):
526529
# Note: freq gets division, not floor-division, even if op
527530
# is floordiv.
528531
freq = self.freq / other
529-
530-
# TODO: 2022-12-24 test_ufunc_coercions, test_tdi_ops_attributes
531-
# get here for truediv, no tests for floordiv
532-
533-
if op is operator.floordiv:
534-
if freq.nanos == 0 and self.freq.nanos != 0:
535-
# e.g. if self.freq is Nano(1) then dividing by 2
536-
# rounds down to zero
537-
# TODO: 2022-12-24 should implement the same check
538-
# for truediv case
539-
freq = None
532+
if freq.nanos == 0 and self.freq.nanos != 0:
533+
# e.g. if self.freq is Nano(1) then dividing by 2
534+
# rounds down to zero
535+
freq = None
540536

541537
return type(self)._simple_new(result, dtype=result.dtype, freq=freq)
542538

pandas/tests/indexes/timedeltas/test_timedelta.py

+18
Original file line numberDiff line numberDiff line change
@@ -157,3 +157,21 @@ def test_freq_conversion(self, index_or_series):
157157
assert expected.dtype == "m8[s]"
158158
result = td.astype("timedelta64[s]")
159159
tm.assert_equal(result, expected)
160+
161+
def test_arithmetic_zero_freq(self):
162+
# GH#51575 don't get a .freq with freq.n = 0
163+
tdi = timedelta_range(0, periods=100, freq="ns")
164+
result = tdi / 2
165+
assert result.freq is None
166+
expected = tdi[:50].repeat(2)
167+
tm.assert_index_equal(result, expected)
168+
169+
result2 = tdi // 2
170+
assert result2.freq is None
171+
expected2 = expected
172+
tm.assert_index_equal(result2, expected2)
173+
174+
result3 = tdi * 0
175+
assert result3.freq is None
176+
expected3 = tdi[:1].repeat(100)
177+
tm.assert_index_equal(result3, expected3)

0 commit comments

Comments
 (0)