Skip to content

BUG: RangeIndex.union #44019

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
Oct 16, 2021
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.4.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -548,6 +548,7 @@ Styler
Other
^^^^^
- Bug in :meth:`CustomBusinessMonthBegin.__add__` (:meth:`CustomBusinessMonthEnd.__add__`) not applying the extra ``offset`` parameter when beginning (end) of the target month is already a business day (:issue:`41356`)
- Bug in :meth:`RangeIndex.union` with another ``RangeIndex`` with matching (even) ``step`` and starts differing by strictly less than ``step / 2`` (:issue:`44019`)

.. ***DO NOT USE THIS SECTION***

Expand Down
7 changes: 5 additions & 2 deletions pandas/core/indexes/range.py
Original file line number Diff line number Diff line change
Expand Up @@ -635,10 +635,13 @@ def _union(self, other: Index, sort):
return type(self)(start_r, end_r + step_s, step_s)
if (
(step_s % 2 == 0)
and (abs(start_s - start_o) <= step_s / 2)
and (abs(end_s - end_o) <= step_s / 2)
and (abs(start_s - start_o) == step_s / 2)
and (abs(end_s - end_o) == step_s / 2)
):
# e.g. range(0, 10, 2) and range(1, 11, 2)
# but not range(0, 20, 4) and range(1, 21, 4) GH#44019
return type(self)(start_r, end_r + step_s / 2, step_s / 2)

elif step_o % step_s == 0:
if (
(start_o - start_s) % step_s == 0
Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/indexes/ranges/test_setops.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,15 @@ def test_union_sorted(self, unions):
tm.assert_index_equal(res2, expected_sorted, exact=True)
tm.assert_index_equal(res3, expected_sorted, exact="equiv")

def test_union_same_step_misaligned(self):
# GH#44019
left = RangeIndex(range(0, 20, 4))
right = RangeIndex(range(1, 21, 4))

result = left.union(right)
expected = Int64Index([0, 1, 4, 5, 8, 9, 12, 13, 16, 17])
tm.assert_index_equal(result, expected, exact=True)

def test_difference(self):
# GH#12034 Cases where we operate against another RangeIndex and may
# get back another RangeIndex
Expand Down