Skip to content

Commit d6f3649

Browse files
jschendelWillAyd
authored andcommitted
IntervalArray equality follow-ups (#30715)
1 parent 6d67cf9 commit d6f3649

File tree

3 files changed

+281
-239
lines changed

3 files changed

+281
-239
lines changed

pandas/core/indexes/interval.py

+8-4
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@
5151
maybe_extract_name,
5252
)
5353
from pandas.core.indexes.datetimes import DatetimeIndex, date_range
54+
from pandas.core.indexes.extension import make_wrapped_comparison_op
5455
from pandas.core.indexes.multi import MultiIndex
5556
from pandas.core.indexes.timedeltas import TimedeltaIndex, timedelta_range
5657
from pandas.core.ops import get_op_result_name
@@ -205,9 +206,7 @@ def func(intvidx_self, other, sort=False):
205206
"__array__",
206207
"overlaps",
207208
"contains",
208-
"__eq__",
209209
"__len__",
210-
"__ne__",
211210
"set_closed",
212211
"to_tuples",
213212
],
@@ -231,8 +230,6 @@ class IntervalIndex(IntervalMixin, ExtensionIndex, accessor.PandasDelegate):
231230
"__array__",
232231
"overlaps",
233232
"contains",
234-
"__eq__",
235-
"__ne__",
236233
}
237234

238235
# --------------------------------------------------------------------
@@ -1206,7 +1203,14 @@ def _delegate_method(self, name, *args, **kwargs):
12061203
return type(self)._simple_new(res, name=self.name)
12071204
return Index(res)
12081205

1206+
@classmethod
1207+
def _add_comparison_methods(cls):
1208+
""" add in comparison methods """
1209+
cls.__eq__ = make_wrapped_comparison_op("__eq__")
1210+
cls.__ne__ = make_wrapped_comparison_op("__ne__")
1211+
12091212

1213+
IntervalIndex._add_comparison_methods()
12101214
IntervalIndex._add_logical_methods_disabled()
12111215

12121216

+273
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,273 @@
1+
import operator
2+
3+
import numpy as np
4+
import pytest
5+
6+
from pandas.core.dtypes.common import is_list_like
7+
8+
import pandas as pd
9+
from pandas import (
10+
Categorical,
11+
Index,
12+
Interval,
13+
IntervalIndex,
14+
Period,
15+
Series,
16+
Timedelta,
17+
Timestamp,
18+
date_range,
19+
period_range,
20+
timedelta_range,
21+
)
22+
import pandas._testing as tm
23+
from pandas.core.arrays import IntervalArray
24+
25+
26+
@pytest.fixture(
27+
params=[
28+
(Index([0, 2, 4, 4]), Index([1, 3, 5, 8])),
29+
(Index([0.0, 1.0, 2.0, np.nan]), Index([1.0, 2.0, 3.0, np.nan])),
30+
(
31+
timedelta_range("0 days", periods=3).insert(4, pd.NaT),
32+
timedelta_range("1 day", periods=3).insert(4, pd.NaT),
33+
),
34+
(
35+
date_range("20170101", periods=3).insert(4, pd.NaT),
36+
date_range("20170102", periods=3).insert(4, pd.NaT),
37+
),
38+
(
39+
date_range("20170101", periods=3, tz="US/Eastern").insert(4, pd.NaT),
40+
date_range("20170102", periods=3, tz="US/Eastern").insert(4, pd.NaT),
41+
),
42+
],
43+
ids=lambda x: str(x[0].dtype),
44+
)
45+
def left_right_dtypes(request):
46+
"""
47+
Fixture for building an IntervalArray from various dtypes
48+
"""
49+
return request.param
50+
51+
52+
@pytest.fixture
53+
def array(left_right_dtypes):
54+
"""
55+
Fixture to generate an IntervalArray of various dtypes containing NA if possible
56+
"""
57+
left, right = left_right_dtypes
58+
return IntervalArray.from_arrays(left, right)
59+
60+
61+
def create_categorical_intervals(left, right, closed="right"):
62+
return Categorical(IntervalIndex.from_arrays(left, right, closed))
63+
64+
65+
def create_series_intervals(left, right, closed="right"):
66+
return Series(IntervalArray.from_arrays(left, right, closed))
67+
68+
69+
def create_series_categorical_intervals(left, right, closed="right"):
70+
return Series(Categorical(IntervalIndex.from_arrays(left, right, closed)))
71+
72+
73+
class TestComparison:
74+
@pytest.fixture(params=[operator.eq, operator.ne])
75+
def op(self, request):
76+
return request.param
77+
78+
@pytest.fixture(
79+
params=[
80+
IntervalArray.from_arrays,
81+
IntervalIndex.from_arrays,
82+
create_categorical_intervals,
83+
create_series_intervals,
84+
create_series_categorical_intervals,
85+
],
86+
ids=[
87+
"IntervalArray",
88+
"IntervalIndex",
89+
"Categorical[Interval]",
90+
"Series[Interval]",
91+
"Series[Categorical[Interval]]",
92+
],
93+
)
94+
def interval_constructor(self, request):
95+
"""
96+
Fixture for all pandas native interval constructors.
97+
To be used as the LHS of IntervalArray comparisons.
98+
"""
99+
return request.param
100+
101+
def elementwise_comparison(self, op, array, other):
102+
"""
103+
Helper that performs elementwise comparisions between `array` and `other`
104+
"""
105+
other = other if is_list_like(other) else [other] * len(array)
106+
return np.array([op(x, y) for x, y in zip(array, other)])
107+
108+
def test_compare_scalar_interval(self, op, array):
109+
# matches first interval
110+
other = array[0]
111+
result = op(array, other)
112+
expected = self.elementwise_comparison(op, array, other)
113+
tm.assert_numpy_array_equal(result, expected)
114+
115+
# matches on a single endpoint but not both
116+
other = Interval(array.left[0], array.right[1])
117+
result = op(array, other)
118+
expected = self.elementwise_comparison(op, array, other)
119+
tm.assert_numpy_array_equal(result, expected)
120+
121+
def test_compare_scalar_interval_mixed_closed(self, op, closed, other_closed):
122+
array = IntervalArray.from_arrays(range(2), range(1, 3), closed=closed)
123+
other = Interval(0, 1, closed=other_closed)
124+
125+
result = op(array, other)
126+
expected = self.elementwise_comparison(op, array, other)
127+
tm.assert_numpy_array_equal(result, expected)
128+
129+
def test_compare_scalar_na(self, op, array, nulls_fixture):
130+
result = op(array, nulls_fixture)
131+
expected = self.elementwise_comparison(op, array, nulls_fixture)
132+
tm.assert_numpy_array_equal(result, expected)
133+
134+
@pytest.mark.parametrize(
135+
"other",
136+
[
137+
0,
138+
1.0,
139+
True,
140+
"foo",
141+
Timestamp("2017-01-01"),
142+
Timestamp("2017-01-01", tz="US/Eastern"),
143+
Timedelta("0 days"),
144+
Period("2017-01-01", "D"),
145+
],
146+
)
147+
def test_compare_scalar_other(self, op, array, other):
148+
result = op(array, other)
149+
expected = self.elementwise_comparison(op, array, other)
150+
tm.assert_numpy_array_equal(result, expected)
151+
152+
def test_compare_list_like_interval(
153+
self, op, array, interval_constructor,
154+
):
155+
# same endpoints
156+
other = interval_constructor(array.left, array.right)
157+
result = op(array, other)
158+
expected = self.elementwise_comparison(op, array, other)
159+
tm.assert_numpy_array_equal(result, expected)
160+
161+
# different endpoints
162+
other = interval_constructor(array.left[::-1], array.right[::-1])
163+
result = op(array, other)
164+
expected = self.elementwise_comparison(op, array, other)
165+
tm.assert_numpy_array_equal(result, expected)
166+
167+
# all nan endpoints
168+
other = interval_constructor([np.nan] * 4, [np.nan] * 4)
169+
result = op(array, other)
170+
expected = self.elementwise_comparison(op, array, other)
171+
tm.assert_numpy_array_equal(result, expected)
172+
173+
def test_compare_list_like_interval_mixed_closed(
174+
self, op, interval_constructor, closed, other_closed
175+
):
176+
array = IntervalArray.from_arrays(range(2), range(1, 3), closed=closed)
177+
other = interval_constructor(range(2), range(1, 3), closed=other_closed)
178+
179+
result = op(array, other)
180+
expected = self.elementwise_comparison(op, array, other)
181+
tm.assert_numpy_array_equal(result, expected)
182+
183+
@pytest.mark.parametrize(
184+
"other",
185+
[
186+
(
187+
Interval(0, 1),
188+
Interval(Timedelta("1 day"), Timedelta("2 days")),
189+
Interval(4, 5, "both"),
190+
Interval(10, 20, "neither"),
191+
),
192+
(0, 1.5, Timestamp("20170103"), np.nan),
193+
(
194+
Timestamp("20170102", tz="US/Eastern"),
195+
Timedelta("2 days"),
196+
"baz",
197+
pd.NaT,
198+
),
199+
],
200+
)
201+
def test_compare_list_like_object(self, op, array, other):
202+
result = op(array, other)
203+
expected = self.elementwise_comparison(op, array, other)
204+
tm.assert_numpy_array_equal(result, expected)
205+
206+
def test_compare_list_like_nan(self, op, array, nulls_fixture):
207+
other = [nulls_fixture] * 4
208+
result = op(array, other)
209+
expected = self.elementwise_comparison(op, array, other)
210+
tm.assert_numpy_array_equal(result, expected)
211+
212+
@pytest.mark.parametrize(
213+
"other",
214+
[
215+
np.arange(4, dtype="int64"),
216+
np.arange(4, dtype="float64"),
217+
date_range("2017-01-01", periods=4),
218+
date_range("2017-01-01", periods=4, tz="US/Eastern"),
219+
timedelta_range("0 days", periods=4),
220+
period_range("2017-01-01", periods=4, freq="D"),
221+
Categorical(list("abab")),
222+
Categorical(date_range("2017-01-01", periods=4)),
223+
pd.array(list("abcd")),
224+
pd.array(["foo", 3.14, None, object()]),
225+
],
226+
ids=lambda x: str(x.dtype),
227+
)
228+
def test_compare_list_like_other(self, op, array, other):
229+
result = op(array, other)
230+
expected = self.elementwise_comparison(op, array, other)
231+
tm.assert_numpy_array_equal(result, expected)
232+
233+
@pytest.mark.parametrize("length", [1, 3, 5])
234+
@pytest.mark.parametrize("other_constructor", [IntervalArray, list])
235+
def test_compare_length_mismatch_errors(self, op, other_constructor, length):
236+
array = IntervalArray.from_arrays(range(4), range(1, 5))
237+
other = other_constructor([Interval(0, 1)] * length)
238+
with pytest.raises(ValueError, match="Lengths must match to compare"):
239+
op(array, other)
240+
241+
@pytest.mark.parametrize(
242+
"constructor, expected_type, assert_func",
243+
[
244+
(IntervalIndex, np.array, tm.assert_numpy_array_equal),
245+
(Series, Series, tm.assert_series_equal),
246+
],
247+
)
248+
def test_index_series_compat(self, op, constructor, expected_type, assert_func):
249+
# IntervalIndex/Series that rely on IntervalArray for comparisons
250+
breaks = range(4)
251+
index = constructor(IntervalIndex.from_breaks(breaks))
252+
253+
# scalar comparisons
254+
other = index[0]
255+
result = op(index, other)
256+
expected = expected_type(self.elementwise_comparison(op, index, other))
257+
assert_func(result, expected)
258+
259+
other = breaks[0]
260+
result = op(index, other)
261+
expected = expected_type(self.elementwise_comparison(op, index, other))
262+
assert_func(result, expected)
263+
264+
# list-like comparisons
265+
other = IntervalArray.from_breaks(breaks)
266+
result = op(index, other)
267+
expected = expected_type(self.elementwise_comparison(op, index, other))
268+
assert_func(result, expected)
269+
270+
other = [index[0], breaks[0], "foo"]
271+
result = op(index, other)
272+
expected = expected_type(self.elementwise_comparison(op, index, other))
273+
assert_func(result, expected)

0 commit comments

Comments
 (0)