Skip to content

BUG: TimedeltaIndex.union with sort=False #30701

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 1 commit into from
Jan 4, 2020
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
13 changes: 11 additions & 2 deletions pandas/core/indexes/timedeltas.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,15 +260,15 @@ def _union(self, other, sort):
this, other = self, other

if this._can_fast_union(other):
return this._fast_union(other)
return this._fast_union(other, sort=sort)
else:
result = Index._union(this, other, sort=sort)
if isinstance(result, TimedeltaIndex):
if result.freq is None:
result._set_freq("infer")
return result

def _fast_union(self, other):
def _fast_union(self, other, sort=None):
if len(other) == 0:
return self.view(type(self))

Expand All @@ -278,6 +278,15 @@ def _fast_union(self, other):
# to make our life easier, "sort" the two ranges
if self[0] <= other[0]:
left, right = self, other
elif sort is False:
# TDIs are not in the "correct" order and we don't want
# to sort but want to remove overlaps
left, right = self, other
left_start = left[0]
loc = right.searchsorted(left_start, side="left")
right_chunk = right.values[:loc]
dates = concat_compat((left.values, right_chunk))
return self._shallow_copy(dates)
else:
left, right = other, self

Expand Down
16 changes: 16 additions & 0 deletions pandas/tests/indexes/timedeltas/test_setops.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,22 @@ def test_union(self):
i1.union(i2) # Works
i2.union(i1) # Fails with "AttributeError: can't set attribute"

def test_union_sort_false(self):
tdi = timedelta_range("1day", periods=5)

left = tdi[3:]
right = tdi[:3]

# Check that we are testing the desired code path
assert left._can_fast_union(right)

result = left.union(right)
tm.assert_index_equal(result, tdi)

result = left.union(right, sort=False)
expected = pd.TimedeltaIndex(["4 Days", "5 Days", "1 Days", "2 Day", "3 Days"])
tm.assert_index_equal(result, expected)

def test_union_coverage(self):

idx = TimedeltaIndex(["3d", "1d", "2d"])
Expand Down