Skip to content

Commit

Permalink
Backport PR #52841 on branch 2.0.x (BUG: dt.round with equal/higher f…
Browse files Browse the repository at this point in the history
…req resolution would not noop) (#52846)

Backport PR #52841: BUG: dt.round with equal/higher freq resolution would not noop

Co-authored-by: Matthew Roeschke <10647082+mroeschke@users.noreply.github.com>
  • Loading branch information
meeseeksmachine and mroeschke committed Apr 22, 2023
1 parent e52861d commit d220466
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.0.1.rst
Expand Up @@ -27,6 +27,7 @@ Bug fixes
~~~~~~~~~
- Bug in :attr:`Series.dt.days` that would overflow ``int32`` number of days (:issue:`52391`)
- Bug in :class:`arrays.DatetimeArray` constructor returning an incorrect unit when passed a non-nanosecond numpy datetime array (:issue:`52555`)
- Bug in :func:`Series.dt.round` when passing a ``freq`` of equal or higher resolution compared to the :class:`Series` would raise a ``ZeroDivisionError`` (:issue:`52761`)
- Bug in :func:`Series.median` with :class:`ArrowDtype` returning an approximate median (:issue:`52679`)
- Bug in :func:`api.interchange.from_dataframe` was unnecessarily raising on categorical dtypes (:issue:`49889`)
- Bug in :func:`api.interchange.from_dataframe` was unnecessarily raising on large string dtypes (:issue:`52795`)
Expand Down
8 changes: 6 additions & 2 deletions pandas/core/arrays/datetimelike.py
Expand Up @@ -2005,8 +2005,12 @@ def _round(self, freq, mode, ambiguous, nonexistent):

values = self.view("i8")
values = cast(np.ndarray, values)
nanos = to_offset(freq).nanos # raises on non-fixed frequencies
nanos = delta_to_nanoseconds(to_offset(freq), self._creso)
offset = to_offset(freq)
offset.nanos # raises on non-fixed frequencies
nanos = delta_to_nanoseconds(offset, self._creso)
if nanos == 0:
# GH 52761
return self
result_i8 = round_nsint64(values, mode, nanos)
result = self._maybe_mask_results(result_i8, fill_value=iNaT)
result = result.view(self._ndarray.dtype)
Expand Down
11 changes: 11 additions & 0 deletions pandas/tests/series/accessors/test_dt_accessor.py
Expand Up @@ -381,6 +381,17 @@ def test_dt_round_tz_nonexistent(self, method, ts_str, freq):
with pytest.raises(pytz.NonExistentTimeError, match="2018-03-11 02:00:00"):
getattr(ser.dt, method)(freq, nonexistent="raise")

@pytest.mark.parametrize("freq", ["ns", "U", "1000U"])
def test_dt_round_nonnano_higher_resolution_no_op(self, freq):
# GH 52761
ser = Series(
["2020-05-31 08:00:00", "2000-12-31 04:00:05", "1800-03-14 07:30:20"],
dtype="datetime64[ms]",
)
expected = ser.copy()
result = ser.dt.round(freq)
tm.assert_series_equal(result, expected)

def test_dt_namespace_accessor_categorical(self):
# GH 19468
dti = DatetimeIndex(["20171111", "20181212"]).repeat(2)
Expand Down

0 comments on commit d220466

Please sign in to comment.