Skip to content

BUG: IntervalIndex.unique() only contains the first interval if all interval borders are negative #61920

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

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 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
20 changes: 14 additions & 6 deletions pandas/core/arrays/interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -1990,12 +1990,20 @@ def _from_combined(self, combined: np.ndarray) -> IntervalArray:
return self._shallow_copy(left=new_left, right=new_right)

def unique(self) -> IntervalArray:
# No overload variant of "__getitem__" of "ExtensionArray" matches argument
# type "Tuple[slice, int]"
nc = unique(
self._combined.view("complex128")[:, 0] # type: ignore[call-overload]
)
nc = nc[:, None]
# Using .view("complex128") with negatives causes issues. # GH#61917
combined = self._combined
combined = np.ascontiguousarray(combined)
if combined.dtype == np.object_:
nc = unique(
self._combined.view("complex128")[:, 0] # type: ignore[call-overload]
)
nc = nc[:, None]
else:
structured = combined.view(
[("left", combined.dtype), ("right", combined.dtype)]
)[:, 0]
unique_structured = unique(structured)
nc = unique_structured.view(combined.dtype)
return self._from_combined(nc)


Expand Down
20 changes: 20 additions & 0 deletions pandas/tests/arrays/interval/test_interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,26 @@ def test_shift_datetime(self):
with pytest.raises(TypeError, match=msg):
a.shift(1, fill_value=np.timedelta64("NaT", "ns"))

def test_unique_with_negatives(self):
# GH#61917
idx_pos = IntervalIndex.from_tuples(
[(3, 4), (3, 4), (2, 3), (2, 3), (1, 2), (1, 2)]
)
result = idx_pos.unique()
assert result.shape == (3,), f"Expected shape (3,), got {result.shape}"

idx_neg = IntervalIndex.from_tuples(
[(-4, -3), (-4, -3), (-3, -2), (-3, -2), (-2, -1), (-2, -1)]
)
result = idx_neg.unique()
assert result.shape == (3,), f"Expected shape (3,), got {result.shape}"

idx_mix = IntervalIndex.from_tuples(
[(1, 2), (0, 1), (-1, 0), (-2, -1), (-3, -2), (-3, -2)]
)
result = idx_mix.unique()
assert result.shape == (5,), f"Expected shape (5,), got {result.shape}"


class TestSetitem:
def test_set_na(self, left_right_dtypes):
Expand Down
Loading