Skip to content

BUG: PeriodArray.__sub__(Period) overflows #47538

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

Merged
merged 2 commits into from
Jun 28, 2022
Merged
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.5.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -904,6 +904,7 @@ Period
- Bug in constructing a :class:`Period` from a :class:`Timestamp` or ``np.datetime64`` object with non-zero nanoseconds and ``freq="ns"`` incorrectly truncating the nanoseconds (:issue:`46811`)
- Bug in adding ``np.timedelta64("NaT", "ns")`` to a :class:`Period` with a timedelta-like freq incorrectly raising ``IncompatibleFrequency`` instead of returning ``NaT`` (:issue:`47196`)
- Bug in adding an array of integers to an array with :class:`PeriodDtype` giving incorrect results when ``dtype.freq.n > 1`` (:issue:`47209`)
- Bug in subtracting a :class:`Period` from an array with :class:`PeriodDtype` returning incorrect results instead of raising ``OverflowError`` when the operation overflows (:issue:`47538`)
-

Plotting
Expand Down
5 changes: 3 additions & 2 deletions pandas/core/arrays/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -1182,8 +1182,9 @@ def _sub_period(self, other: Period) -> npt.NDArray[np.object_]:
# If the operation is well-defined, we return an object-dtype ndarray
# of DateOffsets. Null entries are filled with pd.NaT
self._check_compatible_with(other)
asi8 = self.asi8
new_i8_data = asi8 - other.ordinal # TODO: checked_add_with_arr
new_i8_data = checked_add_with_arr(
self.asi8, -other.ordinal, arr_mask=self._isnan
)
new_data = np.array([self.freq.base * x for x in new_i8_data])

if self._hasna:
Expand Down
14 changes: 14 additions & 0 deletions pandas/tests/arrays/test_period.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,20 @@ def test_sub_period():
arr - other


def test_sub_period_overflow():
# GH#47538
dti = pd.date_range("1677-09-22", periods=2, freq="D")
pi = dti.to_period("ns")

per = pd.Period._from_ordinal(10**14, pi.freq)

with pytest.raises(OverflowError, match="Overflow in int64 addition"):
pi - per

with pytest.raises(OverflowError, match="Overflow in int64 addition"):
per - pi


# ----------------------------------------------------------------------------
# Methods

Expand Down