Skip to content

BUG: Fix difference functionality for Period Indexes #59148

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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,7 @@ Other
- Bug in :meth:`DataFrame.sort_index` when passing ``axis="columns"`` and ``ignore_index=True`` and ``ascending=False`` not returning a :class:`RangeIndex` columns (:issue:`57293`)
- Bug in :meth:`DataFrame.transform` that was returning the wrong order unless the index was monotonically increasing. (:issue:`57069`)
- Bug in :meth:`DataFrame.where` where using a non-bool type array in the function would return a ``ValueError`` instead of a ``TypeError`` (:issue:`56330`)
- Bug in :meth:`Index.difference` returning too many values / incorrect values for period indexes (:issue:`58971`)
- Bug in :meth:`Index.sort_values` when passing a key function that turns values into tuples, e.g. ``key=natsort.natsort_key``, would raise ``TypeError`` (:issue:`56081`)
- Bug in :meth:`Series.diff` allowing non-integer values for the ``periods`` argument. (:issue:`56607`)
- Bug in :meth:`Series.dt` methods in :class:`ArrowDtype` that were returning incorrect values. (:issue:`57355`)
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3406,7 +3406,7 @@ def difference(self, other, sort=None):
return self._wrap_difference_result(other, result)

def _difference(self, other, sort):
# overridden by RangeIndex
# overridden by RangeIndex, PeriodIndex
this = self
if isinstance(self, ABCCategoricalIndex) and self.hasnans and other.hasnans:
this = this.dropna()
Expand Down
9 changes: 9 additions & 0 deletions pandas/core/indexes/period.py
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,15 @@ def shift(self, periods: int = 1, freq=None) -> Self:
)
return self + periods

def _difference(self, other, sort=None) -> PeriodIndex:
if isinstance(other, Index) and other.inferred_type == "string":
try:
other = other.astype(self.dtype)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don’t think we do this type of casting in general. In fact, I’d expect the private _difference to only be reached with matching dtypes

except (TypeError, ValueError):
pass

return super()._difference(other, sort=sort)


def period_range(
start=None,
Expand Down
13 changes: 13 additions & 0 deletions pandas/tests/indexes/period/test_setops.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,19 @@ def test_difference(self, sort):
expected = expected.sort_values()
tm.assert_index_equal(result_difference, expected)

def test_difference_mismatched_dtypes(self, sort):
# GH58971
index = period_range("2022-01-01", periods=5, freq="M")
other = pd.Index(["2022-02", "2022-03"])

idx_diff = index.difference(other, sort)
expected = PeriodIndex(["2022-01", "2022-04", "2022-05"], freq="M")
tm.assert_index_equal(idx_diff, expected)

idx_diff = other.difference(index, sort)
expected = pd.Index([])
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, the difference should be the entire ‘other’

tm.assert_index_equal(idx_diff, expected)

def test_difference_freq(self, sort):
# GH14323: difference of Period MUST preserve frequency
# but the ability to union results must be preserved
Expand Down