Skip to content

Commit 1eb8918

Browse files
committed
Fixed some bugs with the new intersection logic
Added some additional tests for those cases.
1 parent 0215ab3 commit 1eb8918

File tree

2 files changed

+37
-3
lines changed

2 files changed

+37
-3
lines changed

pandas/core/indexes/datetimelike.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -880,7 +880,7 @@ def _intersect_descending(self, other, **empty_params):
880880
left, right = other, self
881881

882882
start = min(left[0], right[0])
883-
end = left[-1]
883+
end = right[-1]
884884

885885
if end > start:
886886
return type(self)(data=[], **empty_params)
@@ -932,11 +932,19 @@ def intersection(self, other):
932932
result.offset = frequencies.to_offset(result.inferred_freq)
933933
return result
934934

935-
if len(self) == 0:
935+
lenghts = len(self), len(other)
936+
if lenghts[0] == 0:
936937
return self
937-
if len(other) == 0:
938+
if lenghts[1] == 0:
938939
return other
939940

941+
# handle intersecting things like this
942+
# idx1 = pd.to_timedelta((1, 2, 3, 4, 5, 6, 7, 8), unit='s')
943+
# idx2 = pd.to_timedelta((2, 3, 4, 8), unit='s')
944+
if lenghts[0] != lenghts[1] and (
945+
max(self) != max(other) or min(self) != min(other)):
946+
return Index.intersection(self, other)
947+
940948
# coerce into same order
941949
self_ascending = self.is_monotonic_increasing
942950
if self_ascending != other.is_monotonic_increasing:

pandas/tests/indexes/timedeltas/test_setops.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import numpy as np
2+
import pytest
23

34
import pandas as pd
45
import pandas.util.testing as tm
@@ -145,3 +146,28 @@ def test_intersection_not_unique():
145146
result = idx2.intersection(idx1)
146147
expected = pd.to_timedelta((1, 2, 2, 3, 3), unit='s')
147148
tm.assert_index_equal(result, expected)
149+
150+
151+
@pytest.mark.parametrize("index1, index2, expected", [
152+
(pd.to_timedelta((1, 2, 3, 4, 5, 6, 7, 8), unit='s'),
153+
pd.to_timedelta((2, 3, 4, 8), unit='s'),
154+
pd.to_timedelta((2, 3, 4, 8), unit='s')),
155+
(pd.to_timedelta((1, 2, 3, 4, 5), unit='s'),
156+
pd.to_timedelta((2, 3, 4), unit='s'),
157+
pd.to_timedelta((2, 3, 4), unit='s')),
158+
(pd.to_timedelta((2, 4, 5, 6), unit='s'),
159+
pd.to_timedelta((2, 3, 4), unit='s'),
160+
pd.to_timedelta((2, 4), unit='s')),
161+
])
162+
def test_intersection_different_lengths(index1, index2, expected):
163+
def intersect(idx1, idx2, expected):
164+
result = idx1.intersection(idx2)
165+
tm.assert_index_equal(result, expected)
166+
result = idx2.intersection(idx1)
167+
tm.assert_index_equal(result, expected)
168+
169+
intersect(index1, index2, expected)
170+
intersect(index1.sort_values(ascending=False),
171+
index2.sort_values(ascending=False),
172+
expected.sort_values(ascending=False)
173+
)

0 commit comments

Comments
 (0)