Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- ckpts/universal/global_step80/zero/21.mlp.dense_h_to_4h.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step80/zero/21.mlp.dense_h_to_4h.weight/fp32.pt +3 -0
- ckpts/universal/global_step80/zero/23.mlp.dense_h_to_4h_swiglu.weight/exp_avg.pt +3 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__init__.py +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_drop_duplicates.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_equals.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_indexing.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_is_monotonic.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_nat.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_sort_values.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_value_counts.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_drop_duplicates.py +89 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_equals.py +181 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_indexing.py +45 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_is_monotonic.py +46 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_nat.py +53 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_sort_values.py +315 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_value_counts.py +103 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/__init__.py +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/__pycache__/test_astype.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/__pycache__/test_constructors.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/__pycache__/test_equals.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/__pycache__/test_formats.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/__pycache__/test_indexing.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/__pycache__/test_interval.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/__pycache__/test_interval_range.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/__pycache__/test_interval_tree.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/__pycache__/test_join.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/__pycache__/test_pickle.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/__pycache__/test_setops.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/test_astype.py +248 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/test_constructors.py +535 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/test_equals.py +36 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/test_formats.py +119 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/test_indexing.py +671 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/test_interval.py +918 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/test_interval_range.py +369 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/test_interval_tree.py +209 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/test_join.py +44 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/test_pickle.py +13 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/test_setops.py +208 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__init__.py +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__pycache__/test_arithmetic.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__pycache__/test_constructors.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__pycache__/test_delete.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__pycache__/test_formats.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__pycache__/test_freq_attr.cpython-310.pyc +0 -0
ckpts/universal/global_step80/zero/21.mlp.dense_h_to_4h.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:df1b77280870d9b7bba19e899ce206b1aab298ad9c5587d18ce8ef3a147cc275
|
3 |
+
size 33555612
|
ckpts/universal/global_step80/zero/21.mlp.dense_h_to_4h.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9facb6e406700a98ab943cf0e5ff2648a4c9f689b7a5a12d8d44ff1845923d60
|
3 |
+
size 33555533
|
ckpts/universal/global_step80/zero/23.mlp.dense_h_to_4h_swiglu.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:058f5d77767bb21097ab58f233368378e9e0c2e8ad08160d2535d2b75e164020
|
3 |
+
size 33555612
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__init__.py
ADDED
File without changes
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (202 Bytes). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_drop_duplicates.cpython-310.pyc
ADDED
Binary file (2.96 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_equals.cpython-310.pyc
ADDED
Binary file (6.07 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_indexing.cpython-310.pyc
ADDED
Binary file (1.4 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_is_monotonic.cpython-310.pyc
ADDED
Binary file (1.02 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_nat.cpython-310.pyc
ADDED
Binary file (1.95 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_sort_values.cpython-310.pyc
ADDED
Binary file (7.62 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_value_counts.cpython-310.pyc
ADDED
Binary file (3.29 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_drop_duplicates.py
ADDED
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas import (
|
5 |
+
PeriodIndex,
|
6 |
+
Series,
|
7 |
+
date_range,
|
8 |
+
period_range,
|
9 |
+
timedelta_range,
|
10 |
+
)
|
11 |
+
import pandas._testing as tm
|
12 |
+
|
13 |
+
|
14 |
+
class DropDuplicates:
|
15 |
+
def test_drop_duplicates_metadata(self, idx):
|
16 |
+
# GH#10115
|
17 |
+
result = idx.drop_duplicates()
|
18 |
+
tm.assert_index_equal(idx, result)
|
19 |
+
assert idx.freq == result.freq
|
20 |
+
|
21 |
+
idx_dup = idx.append(idx)
|
22 |
+
result = idx_dup.drop_duplicates()
|
23 |
+
|
24 |
+
expected = idx
|
25 |
+
if not isinstance(idx, PeriodIndex):
|
26 |
+
# freq is reset except for PeriodIndex
|
27 |
+
assert idx_dup.freq is None
|
28 |
+
assert result.freq is None
|
29 |
+
expected = idx._with_freq(None)
|
30 |
+
else:
|
31 |
+
assert result.freq == expected.freq
|
32 |
+
|
33 |
+
tm.assert_index_equal(result, expected)
|
34 |
+
|
35 |
+
@pytest.mark.parametrize(
|
36 |
+
"keep, expected, index",
|
37 |
+
[
|
38 |
+
(
|
39 |
+
"first",
|
40 |
+
np.concatenate(([False] * 10, [True] * 5)),
|
41 |
+
np.arange(0, 10, dtype=np.int64),
|
42 |
+
),
|
43 |
+
(
|
44 |
+
"last",
|
45 |
+
np.concatenate(([True] * 5, [False] * 10)),
|
46 |
+
np.arange(5, 15, dtype=np.int64),
|
47 |
+
),
|
48 |
+
(
|
49 |
+
False,
|
50 |
+
np.concatenate(([True] * 5, [False] * 5, [True] * 5)),
|
51 |
+
np.arange(5, 10, dtype=np.int64),
|
52 |
+
),
|
53 |
+
],
|
54 |
+
)
|
55 |
+
def test_drop_duplicates(self, keep, expected, index, idx):
|
56 |
+
# to check Index/Series compat
|
57 |
+
idx = idx.append(idx[:5])
|
58 |
+
|
59 |
+
tm.assert_numpy_array_equal(idx.duplicated(keep=keep), expected)
|
60 |
+
expected = idx[~expected]
|
61 |
+
|
62 |
+
result = idx.drop_duplicates(keep=keep)
|
63 |
+
tm.assert_index_equal(result, expected)
|
64 |
+
|
65 |
+
result = Series(idx).drop_duplicates(keep=keep)
|
66 |
+
expected = Series(expected, index=index)
|
67 |
+
tm.assert_series_equal(result, expected)
|
68 |
+
|
69 |
+
|
70 |
+
class TestDropDuplicatesPeriodIndex(DropDuplicates):
|
71 |
+
@pytest.fixture(params=["D", "3D", "h", "2h", "min", "2min", "s", "3s"])
|
72 |
+
def freq(self, request):
|
73 |
+
return request.param
|
74 |
+
|
75 |
+
@pytest.fixture
|
76 |
+
def idx(self, freq):
|
77 |
+
return period_range("2011-01-01", periods=10, freq=freq, name="idx")
|
78 |
+
|
79 |
+
|
80 |
+
class TestDropDuplicatesDatetimeIndex(DropDuplicates):
|
81 |
+
@pytest.fixture
|
82 |
+
def idx(self, freq_sample):
|
83 |
+
return date_range("2011-01-01", freq=freq_sample, periods=10, name="idx")
|
84 |
+
|
85 |
+
|
86 |
+
class TestDropDuplicatesTimedeltaIndex(DropDuplicates):
|
87 |
+
@pytest.fixture
|
88 |
+
def idx(self, freq_sample):
|
89 |
+
return timedelta_range("1 day", periods=10, freq=freq_sample, name="idx")
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_equals.py
ADDED
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Tests shared for DatetimeIndex/TimedeltaIndex/PeriodIndex
|
3 |
+
"""
|
4 |
+
from datetime import (
|
5 |
+
datetime,
|
6 |
+
timedelta,
|
7 |
+
)
|
8 |
+
|
9 |
+
import numpy as np
|
10 |
+
import pytest
|
11 |
+
|
12 |
+
import pandas as pd
|
13 |
+
from pandas import (
|
14 |
+
CategoricalIndex,
|
15 |
+
DatetimeIndex,
|
16 |
+
Index,
|
17 |
+
PeriodIndex,
|
18 |
+
TimedeltaIndex,
|
19 |
+
date_range,
|
20 |
+
period_range,
|
21 |
+
timedelta_range,
|
22 |
+
)
|
23 |
+
import pandas._testing as tm
|
24 |
+
|
25 |
+
|
26 |
+
class EqualsTests:
|
27 |
+
def test_not_equals_numeric(self, index):
|
28 |
+
assert not index.equals(Index(index.asi8))
|
29 |
+
assert not index.equals(Index(index.asi8.astype("u8")))
|
30 |
+
assert not index.equals(Index(index.asi8).astype("f8"))
|
31 |
+
|
32 |
+
def test_equals(self, index):
|
33 |
+
assert index.equals(index)
|
34 |
+
assert index.equals(index.astype(object))
|
35 |
+
assert index.equals(CategoricalIndex(index))
|
36 |
+
assert index.equals(CategoricalIndex(index.astype(object)))
|
37 |
+
|
38 |
+
def test_not_equals_non_arraylike(self, index):
|
39 |
+
assert not index.equals(list(index))
|
40 |
+
|
41 |
+
def test_not_equals_strings(self, index):
|
42 |
+
other = Index([str(x) for x in index], dtype=object)
|
43 |
+
assert not index.equals(other)
|
44 |
+
assert not index.equals(CategoricalIndex(other))
|
45 |
+
|
46 |
+
def test_not_equals_misc_strs(self, index):
|
47 |
+
other = Index(list("abc"))
|
48 |
+
assert not index.equals(other)
|
49 |
+
|
50 |
+
|
51 |
+
class TestPeriodIndexEquals(EqualsTests):
|
52 |
+
@pytest.fixture
|
53 |
+
def index(self):
|
54 |
+
return period_range("2013-01-01", periods=5, freq="D")
|
55 |
+
|
56 |
+
# TODO: de-duplicate with other test_equals2 methods
|
57 |
+
@pytest.mark.parametrize("freq", ["D", "M"])
|
58 |
+
def test_equals2(self, freq):
|
59 |
+
# GH#13107
|
60 |
+
idx = PeriodIndex(["2011-01-01", "2011-01-02", "NaT"], freq=freq)
|
61 |
+
assert idx.equals(idx)
|
62 |
+
assert idx.equals(idx.copy())
|
63 |
+
assert idx.equals(idx.astype(object))
|
64 |
+
assert idx.astype(object).equals(idx)
|
65 |
+
assert idx.astype(object).equals(idx.astype(object))
|
66 |
+
assert not idx.equals(list(idx))
|
67 |
+
assert not idx.equals(pd.Series(idx))
|
68 |
+
|
69 |
+
idx2 = PeriodIndex(["2011-01-01", "2011-01-02", "NaT"], freq="h")
|
70 |
+
assert not idx.equals(idx2)
|
71 |
+
assert not idx.equals(idx2.copy())
|
72 |
+
assert not idx.equals(idx2.astype(object))
|
73 |
+
assert not idx.astype(object).equals(idx2)
|
74 |
+
assert not idx.equals(list(idx2))
|
75 |
+
assert not idx.equals(pd.Series(idx2))
|
76 |
+
|
77 |
+
# same internal, different tz
|
78 |
+
idx3 = PeriodIndex._simple_new(
|
79 |
+
idx._values._simple_new(idx._values.asi8, dtype=pd.PeriodDtype("h"))
|
80 |
+
)
|
81 |
+
tm.assert_numpy_array_equal(idx.asi8, idx3.asi8)
|
82 |
+
assert not idx.equals(idx3)
|
83 |
+
assert not idx.equals(idx3.copy())
|
84 |
+
assert not idx.equals(idx3.astype(object))
|
85 |
+
assert not idx.astype(object).equals(idx3)
|
86 |
+
assert not idx.equals(list(idx3))
|
87 |
+
assert not idx.equals(pd.Series(idx3))
|
88 |
+
|
89 |
+
|
90 |
+
class TestDatetimeIndexEquals(EqualsTests):
|
91 |
+
@pytest.fixture
|
92 |
+
def index(self):
|
93 |
+
return date_range("2013-01-01", periods=5)
|
94 |
+
|
95 |
+
def test_equals2(self):
|
96 |
+
# GH#13107
|
97 |
+
idx = DatetimeIndex(["2011-01-01", "2011-01-02", "NaT"])
|
98 |
+
assert idx.equals(idx)
|
99 |
+
assert idx.equals(idx.copy())
|
100 |
+
assert idx.equals(idx.astype(object))
|
101 |
+
assert idx.astype(object).equals(idx)
|
102 |
+
assert idx.astype(object).equals(idx.astype(object))
|
103 |
+
assert not idx.equals(list(idx))
|
104 |
+
assert not idx.equals(pd.Series(idx))
|
105 |
+
|
106 |
+
idx2 = DatetimeIndex(["2011-01-01", "2011-01-02", "NaT"], tz="US/Pacific")
|
107 |
+
assert not idx.equals(idx2)
|
108 |
+
assert not idx.equals(idx2.copy())
|
109 |
+
assert not idx.equals(idx2.astype(object))
|
110 |
+
assert not idx.astype(object).equals(idx2)
|
111 |
+
assert not idx.equals(list(idx2))
|
112 |
+
assert not idx.equals(pd.Series(idx2))
|
113 |
+
|
114 |
+
# same internal, different tz
|
115 |
+
idx3 = DatetimeIndex(idx.asi8, tz="US/Pacific")
|
116 |
+
tm.assert_numpy_array_equal(idx.asi8, idx3.asi8)
|
117 |
+
assert not idx.equals(idx3)
|
118 |
+
assert not idx.equals(idx3.copy())
|
119 |
+
assert not idx.equals(idx3.astype(object))
|
120 |
+
assert not idx.astype(object).equals(idx3)
|
121 |
+
assert not idx.equals(list(idx3))
|
122 |
+
assert not idx.equals(pd.Series(idx3))
|
123 |
+
|
124 |
+
# check that we do not raise when comparing with OutOfBounds objects
|
125 |
+
oob = Index([datetime(2500, 1, 1)] * 3, dtype=object)
|
126 |
+
assert not idx.equals(oob)
|
127 |
+
assert not idx2.equals(oob)
|
128 |
+
assert not idx3.equals(oob)
|
129 |
+
|
130 |
+
# check that we do not raise when comparing with OutOfBounds dt64
|
131 |
+
oob2 = oob.map(np.datetime64)
|
132 |
+
assert not idx.equals(oob2)
|
133 |
+
assert not idx2.equals(oob2)
|
134 |
+
assert not idx3.equals(oob2)
|
135 |
+
|
136 |
+
@pytest.mark.parametrize("freq", ["B", "C"])
|
137 |
+
def test_not_equals_bday(self, freq):
|
138 |
+
rng = date_range("2009-01-01", "2010-01-01", freq=freq)
|
139 |
+
assert not rng.equals(list(rng))
|
140 |
+
|
141 |
+
|
142 |
+
class TestTimedeltaIndexEquals(EqualsTests):
|
143 |
+
@pytest.fixture
|
144 |
+
def index(self):
|
145 |
+
return timedelta_range("1 day", periods=10)
|
146 |
+
|
147 |
+
def test_equals2(self):
|
148 |
+
# GH#13107
|
149 |
+
idx = TimedeltaIndex(["1 days", "2 days", "NaT"])
|
150 |
+
assert idx.equals(idx)
|
151 |
+
assert idx.equals(idx.copy())
|
152 |
+
assert idx.equals(idx.astype(object))
|
153 |
+
assert idx.astype(object).equals(idx)
|
154 |
+
assert idx.astype(object).equals(idx.astype(object))
|
155 |
+
assert not idx.equals(list(idx))
|
156 |
+
assert not idx.equals(pd.Series(idx))
|
157 |
+
|
158 |
+
idx2 = TimedeltaIndex(["2 days", "1 days", "NaT"])
|
159 |
+
assert not idx.equals(idx2)
|
160 |
+
assert not idx.equals(idx2.copy())
|
161 |
+
assert not idx.equals(idx2.astype(object))
|
162 |
+
assert not idx.astype(object).equals(idx2)
|
163 |
+
assert not idx.astype(object).equals(idx2.astype(object))
|
164 |
+
assert not idx.equals(list(idx2))
|
165 |
+
assert not idx.equals(pd.Series(idx2))
|
166 |
+
|
167 |
+
# Check that we dont raise OverflowError on comparisons outside the
|
168 |
+
# implementation range GH#28532
|
169 |
+
oob = Index([timedelta(days=10**6)] * 3, dtype=object)
|
170 |
+
assert not idx.equals(oob)
|
171 |
+
assert not idx2.equals(oob)
|
172 |
+
|
173 |
+
oob2 = Index([np.timedelta64(x) for x in oob], dtype=object)
|
174 |
+
assert (oob == oob2).all()
|
175 |
+
assert not idx.equals(oob2)
|
176 |
+
assert not idx2.equals(oob2)
|
177 |
+
|
178 |
+
oob3 = oob.map(np.timedelta64)
|
179 |
+
assert (oob3 == oob).all()
|
180 |
+
assert not idx.equals(oob3)
|
181 |
+
assert not idx2.equals(oob3)
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_indexing.py
ADDED
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
import pandas as pd
|
5 |
+
from pandas import (
|
6 |
+
DatetimeIndex,
|
7 |
+
Index,
|
8 |
+
)
|
9 |
+
import pandas._testing as tm
|
10 |
+
|
11 |
+
dtlike_dtypes = [
|
12 |
+
np.dtype("timedelta64[ns]"),
|
13 |
+
np.dtype("datetime64[ns]"),
|
14 |
+
pd.DatetimeTZDtype("ns", "Asia/Tokyo"),
|
15 |
+
pd.PeriodDtype("ns"),
|
16 |
+
]
|
17 |
+
|
18 |
+
|
19 |
+
@pytest.mark.parametrize("ldtype", dtlike_dtypes)
|
20 |
+
@pytest.mark.parametrize("rdtype", dtlike_dtypes)
|
21 |
+
def test_get_indexer_non_unique_wrong_dtype(ldtype, rdtype):
|
22 |
+
vals = np.tile(3600 * 10**9 * np.arange(3), 2)
|
23 |
+
|
24 |
+
def construct(dtype):
|
25 |
+
if dtype is dtlike_dtypes[-1]:
|
26 |
+
# PeriodArray will try to cast ints to strings
|
27 |
+
return DatetimeIndex(vals).astype(dtype)
|
28 |
+
return Index(vals, dtype=dtype)
|
29 |
+
|
30 |
+
left = construct(ldtype)
|
31 |
+
right = construct(rdtype)
|
32 |
+
|
33 |
+
result = left.get_indexer_non_unique(right)
|
34 |
+
|
35 |
+
if ldtype is rdtype:
|
36 |
+
ex1 = np.array([0, 3, 1, 4, 2, 5] * 2, dtype=np.intp)
|
37 |
+
ex2 = np.array([], dtype=np.intp)
|
38 |
+
tm.assert_numpy_array_equal(result[0], ex1)
|
39 |
+
tm.assert_numpy_array_equal(result[1], ex2)
|
40 |
+
|
41 |
+
else:
|
42 |
+
no_matches = np.array([-1] * 6, dtype=np.intp)
|
43 |
+
missing = np.arange(6, dtype=np.intp)
|
44 |
+
tm.assert_numpy_array_equal(result[0], no_matches)
|
45 |
+
tm.assert_numpy_array_equal(result[1], missing)
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_is_monotonic.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from pandas import (
|
2 |
+
Index,
|
3 |
+
NaT,
|
4 |
+
date_range,
|
5 |
+
)
|
6 |
+
|
7 |
+
|
8 |
+
def test_is_monotonic_with_nat():
|
9 |
+
# GH#31437
|
10 |
+
# PeriodIndex.is_monotonic_increasing should behave analogously to DatetimeIndex,
|
11 |
+
# in particular never be monotonic when we have NaT
|
12 |
+
dti = date_range("2016-01-01", periods=3)
|
13 |
+
pi = dti.to_period("D")
|
14 |
+
tdi = Index(dti.view("timedelta64[ns]"))
|
15 |
+
|
16 |
+
for obj in [pi, pi._engine, dti, dti._engine, tdi, tdi._engine]:
|
17 |
+
if isinstance(obj, Index):
|
18 |
+
# i.e. not Engines
|
19 |
+
assert obj.is_monotonic_increasing
|
20 |
+
assert obj.is_monotonic_increasing
|
21 |
+
assert not obj.is_monotonic_decreasing
|
22 |
+
assert obj.is_unique
|
23 |
+
|
24 |
+
dti1 = dti.insert(0, NaT)
|
25 |
+
pi1 = dti1.to_period("D")
|
26 |
+
tdi1 = Index(dti1.view("timedelta64[ns]"))
|
27 |
+
|
28 |
+
for obj in [pi1, pi1._engine, dti1, dti1._engine, tdi1, tdi1._engine]:
|
29 |
+
if isinstance(obj, Index):
|
30 |
+
# i.e. not Engines
|
31 |
+
assert not obj.is_monotonic_increasing
|
32 |
+
assert not obj.is_monotonic_increasing
|
33 |
+
assert not obj.is_monotonic_decreasing
|
34 |
+
assert obj.is_unique
|
35 |
+
|
36 |
+
dti2 = dti.insert(3, NaT)
|
37 |
+
pi2 = dti2.to_period("h")
|
38 |
+
tdi2 = Index(dti2.view("timedelta64[ns]"))
|
39 |
+
|
40 |
+
for obj in [pi2, pi2._engine, dti2, dti2._engine, tdi2, tdi2._engine]:
|
41 |
+
if isinstance(obj, Index):
|
42 |
+
# i.e. not Engines
|
43 |
+
assert not obj.is_monotonic_increasing
|
44 |
+
assert not obj.is_monotonic_increasing
|
45 |
+
assert not obj.is_monotonic_decreasing
|
46 |
+
assert obj.is_unique
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_nat.py
ADDED
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas import (
|
5 |
+
DatetimeIndex,
|
6 |
+
NaT,
|
7 |
+
PeriodIndex,
|
8 |
+
TimedeltaIndex,
|
9 |
+
)
|
10 |
+
import pandas._testing as tm
|
11 |
+
|
12 |
+
|
13 |
+
class NATests:
|
14 |
+
def test_nat(self, index_without_na):
|
15 |
+
empty_index = index_without_na[:0]
|
16 |
+
|
17 |
+
index_with_na = index_without_na.copy(deep=True)
|
18 |
+
index_with_na._data[1] = NaT
|
19 |
+
|
20 |
+
assert empty_index._na_value is NaT
|
21 |
+
assert index_with_na._na_value is NaT
|
22 |
+
assert index_without_na._na_value is NaT
|
23 |
+
|
24 |
+
idx = index_without_na
|
25 |
+
assert idx._can_hold_na
|
26 |
+
|
27 |
+
tm.assert_numpy_array_equal(idx._isnan, np.array([False, False]))
|
28 |
+
assert idx.hasnans is False
|
29 |
+
|
30 |
+
idx = index_with_na
|
31 |
+
assert idx._can_hold_na
|
32 |
+
|
33 |
+
tm.assert_numpy_array_equal(idx._isnan, np.array([False, True]))
|
34 |
+
assert idx.hasnans is True
|
35 |
+
|
36 |
+
|
37 |
+
class TestDatetimeIndexNA(NATests):
|
38 |
+
@pytest.fixture
|
39 |
+
def index_without_na(self, tz_naive_fixture):
|
40 |
+
tz = tz_naive_fixture
|
41 |
+
return DatetimeIndex(["2011-01-01", "2011-01-02"], tz=tz)
|
42 |
+
|
43 |
+
|
44 |
+
class TestTimedeltaIndexNA(NATests):
|
45 |
+
@pytest.fixture
|
46 |
+
def index_without_na(self):
|
47 |
+
return TimedeltaIndex(["1 days", "2 days"])
|
48 |
+
|
49 |
+
|
50 |
+
class TestPeriodIndexNA(NATests):
|
51 |
+
@pytest.fixture
|
52 |
+
def index_without_na(self):
|
53 |
+
return PeriodIndex(["2011-01-01", "2011-01-02"], freq="D")
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_sort_values.py
ADDED
@@ -0,0 +1,315 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas import (
|
5 |
+
DatetimeIndex,
|
6 |
+
Index,
|
7 |
+
NaT,
|
8 |
+
PeriodIndex,
|
9 |
+
TimedeltaIndex,
|
10 |
+
timedelta_range,
|
11 |
+
)
|
12 |
+
import pandas._testing as tm
|
13 |
+
|
14 |
+
|
15 |
+
def check_freq_ascending(ordered, orig, ascending):
|
16 |
+
"""
|
17 |
+
Check the expected freq on a PeriodIndex/DatetimeIndex/TimedeltaIndex
|
18 |
+
when the original index is generated (or generate-able) with
|
19 |
+
period_range/date_range/timedelta_range.
|
20 |
+
"""
|
21 |
+
if isinstance(ordered, PeriodIndex):
|
22 |
+
assert ordered.freq == orig.freq
|
23 |
+
elif isinstance(ordered, (DatetimeIndex, TimedeltaIndex)):
|
24 |
+
if ascending:
|
25 |
+
assert ordered.freq.n == orig.freq.n
|
26 |
+
else:
|
27 |
+
assert ordered.freq.n == -1 * orig.freq.n
|
28 |
+
|
29 |
+
|
30 |
+
def check_freq_nonmonotonic(ordered, orig):
|
31 |
+
"""
|
32 |
+
Check the expected freq on a PeriodIndex/DatetimeIndex/TimedeltaIndex
|
33 |
+
when the original index is _not_ generated (or generate-able) with
|
34 |
+
period_range/date_range//timedelta_range.
|
35 |
+
"""
|
36 |
+
if isinstance(ordered, PeriodIndex):
|
37 |
+
assert ordered.freq == orig.freq
|
38 |
+
elif isinstance(ordered, (DatetimeIndex, TimedeltaIndex)):
|
39 |
+
assert ordered.freq is None
|
40 |
+
|
41 |
+
|
42 |
+
class TestSortValues:
|
43 |
+
@pytest.fixture(params=[DatetimeIndex, TimedeltaIndex, PeriodIndex])
|
44 |
+
def non_monotonic_idx(self, request):
|
45 |
+
if request.param is DatetimeIndex:
|
46 |
+
return DatetimeIndex(["2000-01-04", "2000-01-01", "2000-01-02"])
|
47 |
+
elif request.param is PeriodIndex:
|
48 |
+
dti = DatetimeIndex(["2000-01-04", "2000-01-01", "2000-01-02"])
|
49 |
+
return dti.to_period("D")
|
50 |
+
else:
|
51 |
+
return TimedeltaIndex(
|
52 |
+
["1 day 00:00:05", "1 day 00:00:01", "1 day 00:00:02"]
|
53 |
+
)
|
54 |
+
|
55 |
+
def test_argmin_argmax(self, non_monotonic_idx):
|
56 |
+
assert non_monotonic_idx.argmin() == 1
|
57 |
+
assert non_monotonic_idx.argmax() == 0
|
58 |
+
|
59 |
+
def test_sort_values(self, non_monotonic_idx):
|
60 |
+
idx = non_monotonic_idx
|
61 |
+
ordered = idx.sort_values()
|
62 |
+
assert ordered.is_monotonic_increasing
|
63 |
+
ordered = idx.sort_values(ascending=False)
|
64 |
+
assert ordered[::-1].is_monotonic_increasing
|
65 |
+
|
66 |
+
ordered, dexer = idx.sort_values(return_indexer=True)
|
67 |
+
assert ordered.is_monotonic_increasing
|
68 |
+
tm.assert_numpy_array_equal(dexer, np.array([1, 2, 0], dtype=np.intp))
|
69 |
+
|
70 |
+
ordered, dexer = idx.sort_values(return_indexer=True, ascending=False)
|
71 |
+
assert ordered[::-1].is_monotonic_increasing
|
72 |
+
tm.assert_numpy_array_equal(dexer, np.array([0, 2, 1], dtype=np.intp))
|
73 |
+
|
74 |
+
def check_sort_values_with_freq(self, idx):
|
75 |
+
ordered = idx.sort_values()
|
76 |
+
tm.assert_index_equal(ordered, idx)
|
77 |
+
check_freq_ascending(ordered, idx, True)
|
78 |
+
|
79 |
+
ordered = idx.sort_values(ascending=False)
|
80 |
+
expected = idx[::-1]
|
81 |
+
tm.assert_index_equal(ordered, expected)
|
82 |
+
check_freq_ascending(ordered, idx, False)
|
83 |
+
|
84 |
+
ordered, indexer = idx.sort_values(return_indexer=True)
|
85 |
+
tm.assert_index_equal(ordered, idx)
|
86 |
+
tm.assert_numpy_array_equal(indexer, np.array([0, 1, 2], dtype=np.intp))
|
87 |
+
check_freq_ascending(ordered, idx, True)
|
88 |
+
|
89 |
+
ordered, indexer = idx.sort_values(return_indexer=True, ascending=False)
|
90 |
+
expected = idx[::-1]
|
91 |
+
tm.assert_index_equal(ordered, expected)
|
92 |
+
tm.assert_numpy_array_equal(indexer, np.array([2, 1, 0], dtype=np.intp))
|
93 |
+
check_freq_ascending(ordered, idx, False)
|
94 |
+
|
95 |
+
@pytest.mark.parametrize("freq", ["D", "h"])
|
96 |
+
def test_sort_values_with_freq_timedeltaindex(self, freq):
|
97 |
+
# GH#10295
|
98 |
+
idx = timedelta_range(start=f"1{freq}", periods=3, freq=freq).rename("idx")
|
99 |
+
|
100 |
+
self.check_sort_values_with_freq(idx)
|
101 |
+
|
102 |
+
@pytest.mark.parametrize(
|
103 |
+
"idx",
|
104 |
+
[
|
105 |
+
DatetimeIndex(
|
106 |
+
["2011-01-01", "2011-01-02", "2011-01-03"], freq="D", name="idx"
|
107 |
+
),
|
108 |
+
DatetimeIndex(
|
109 |
+
["2011-01-01 09:00", "2011-01-01 10:00", "2011-01-01 11:00"],
|
110 |
+
freq="h",
|
111 |
+
name="tzidx",
|
112 |
+
tz="Asia/Tokyo",
|
113 |
+
),
|
114 |
+
],
|
115 |
+
)
|
116 |
+
def test_sort_values_with_freq_datetimeindex(self, idx):
|
117 |
+
self.check_sort_values_with_freq(idx)
|
118 |
+
|
119 |
+
@pytest.mark.parametrize("freq", ["D", "2D", "4D"])
|
120 |
+
def test_sort_values_with_freq_periodindex(self, freq):
|
121 |
+
# here with_freq refers to being period_range-like
|
122 |
+
idx = PeriodIndex(
|
123 |
+
["2011-01-01", "2011-01-02", "2011-01-03"], freq=freq, name="idx"
|
124 |
+
)
|
125 |
+
self.check_sort_values_with_freq(idx)
|
126 |
+
|
127 |
+
@pytest.mark.parametrize(
|
128 |
+
"idx",
|
129 |
+
[
|
130 |
+
PeriodIndex(["2011", "2012", "2013"], name="pidx", freq="Y"),
|
131 |
+
Index([2011, 2012, 2013], name="idx"), # for compatibility check
|
132 |
+
],
|
133 |
+
)
|
134 |
+
def test_sort_values_with_freq_periodindex2(self, idx):
|
135 |
+
# here with_freq indicates this is period_range-like
|
136 |
+
self.check_sort_values_with_freq(idx)
|
137 |
+
|
138 |
+
def check_sort_values_without_freq(self, idx, expected):
|
139 |
+
ordered = idx.sort_values(na_position="first")
|
140 |
+
tm.assert_index_equal(ordered, expected)
|
141 |
+
check_freq_nonmonotonic(ordered, idx)
|
142 |
+
|
143 |
+
if not idx.isna().any():
|
144 |
+
ordered = idx.sort_values()
|
145 |
+
tm.assert_index_equal(ordered, expected)
|
146 |
+
check_freq_nonmonotonic(ordered, idx)
|
147 |
+
|
148 |
+
ordered = idx.sort_values(ascending=False)
|
149 |
+
tm.assert_index_equal(ordered, expected[::-1])
|
150 |
+
check_freq_nonmonotonic(ordered, idx)
|
151 |
+
|
152 |
+
ordered, indexer = idx.sort_values(return_indexer=True, na_position="first")
|
153 |
+
tm.assert_index_equal(ordered, expected)
|
154 |
+
|
155 |
+
exp = np.array([0, 4, 3, 1, 2], dtype=np.intp)
|
156 |
+
tm.assert_numpy_array_equal(indexer, exp)
|
157 |
+
check_freq_nonmonotonic(ordered, idx)
|
158 |
+
|
159 |
+
if not idx.isna().any():
|
160 |
+
ordered, indexer = idx.sort_values(return_indexer=True)
|
161 |
+
tm.assert_index_equal(ordered, expected)
|
162 |
+
|
163 |
+
exp = np.array([0, 4, 3, 1, 2], dtype=np.intp)
|
164 |
+
tm.assert_numpy_array_equal(indexer, exp)
|
165 |
+
check_freq_nonmonotonic(ordered, idx)
|
166 |
+
|
167 |
+
ordered, indexer = idx.sort_values(return_indexer=True, ascending=False)
|
168 |
+
tm.assert_index_equal(ordered, expected[::-1])
|
169 |
+
|
170 |
+
exp = np.array([2, 1, 3, 0, 4], dtype=np.intp)
|
171 |
+
tm.assert_numpy_array_equal(indexer, exp)
|
172 |
+
check_freq_nonmonotonic(ordered, idx)
|
173 |
+
|
174 |
+
def test_sort_values_without_freq_timedeltaindex(self):
|
175 |
+
# GH#10295
|
176 |
+
|
177 |
+
idx = TimedeltaIndex(
|
178 |
+
["1 hour", "3 hour", "5 hour", "2 hour ", "1 hour"], name="idx1"
|
179 |
+
)
|
180 |
+
expected = TimedeltaIndex(
|
181 |
+
["1 hour", "1 hour", "2 hour", "3 hour", "5 hour"], name="idx1"
|
182 |
+
)
|
183 |
+
self.check_sort_values_without_freq(idx, expected)
|
184 |
+
|
185 |
+
@pytest.mark.parametrize(
|
186 |
+
"index_dates,expected_dates",
|
187 |
+
[
|
188 |
+
(
|
189 |
+
["2011-01-01", "2011-01-03", "2011-01-05", "2011-01-02", "2011-01-01"],
|
190 |
+
["2011-01-01", "2011-01-01", "2011-01-02", "2011-01-03", "2011-01-05"],
|
191 |
+
),
|
192 |
+
(
|
193 |
+
["2011-01-01", "2011-01-03", "2011-01-05", "2011-01-02", "2011-01-01"],
|
194 |
+
["2011-01-01", "2011-01-01", "2011-01-02", "2011-01-03", "2011-01-05"],
|
195 |
+
),
|
196 |
+
(
|
197 |
+
[NaT, "2011-01-03", "2011-01-05", "2011-01-02", NaT],
|
198 |
+
[NaT, NaT, "2011-01-02", "2011-01-03", "2011-01-05"],
|
199 |
+
),
|
200 |
+
],
|
201 |
+
)
|
202 |
+
def test_sort_values_without_freq_datetimeindex(
|
203 |
+
self, index_dates, expected_dates, tz_naive_fixture
|
204 |
+
):
|
205 |
+
tz = tz_naive_fixture
|
206 |
+
|
207 |
+
# without freq
|
208 |
+
idx = DatetimeIndex(index_dates, tz=tz, name="idx")
|
209 |
+
expected = DatetimeIndex(expected_dates, tz=tz, name="idx")
|
210 |
+
|
211 |
+
self.check_sort_values_without_freq(idx, expected)
|
212 |
+
|
213 |
+
@pytest.mark.parametrize(
|
214 |
+
"idx,expected",
|
215 |
+
[
|
216 |
+
(
|
217 |
+
PeriodIndex(
|
218 |
+
[
|
219 |
+
"2011-01-01",
|
220 |
+
"2011-01-03",
|
221 |
+
"2011-01-05",
|
222 |
+
"2011-01-02",
|
223 |
+
"2011-01-01",
|
224 |
+
],
|
225 |
+
freq="D",
|
226 |
+
name="idx1",
|
227 |
+
),
|
228 |
+
PeriodIndex(
|
229 |
+
[
|
230 |
+
"2011-01-01",
|
231 |
+
"2011-01-01",
|
232 |
+
"2011-01-02",
|
233 |
+
"2011-01-03",
|
234 |
+
"2011-01-05",
|
235 |
+
],
|
236 |
+
freq="D",
|
237 |
+
name="idx1",
|
238 |
+
),
|
239 |
+
),
|
240 |
+
(
|
241 |
+
PeriodIndex(
|
242 |
+
[
|
243 |
+
"2011-01-01",
|
244 |
+
"2011-01-03",
|
245 |
+
"2011-01-05",
|
246 |
+
"2011-01-02",
|
247 |
+
"2011-01-01",
|
248 |
+
],
|
249 |
+
freq="D",
|
250 |
+
name="idx2",
|
251 |
+
),
|
252 |
+
PeriodIndex(
|
253 |
+
[
|
254 |
+
"2011-01-01",
|
255 |
+
"2011-01-01",
|
256 |
+
"2011-01-02",
|
257 |
+
"2011-01-03",
|
258 |
+
"2011-01-05",
|
259 |
+
],
|
260 |
+
freq="D",
|
261 |
+
name="idx2",
|
262 |
+
),
|
263 |
+
),
|
264 |
+
(
|
265 |
+
PeriodIndex(
|
266 |
+
[NaT, "2011-01-03", "2011-01-05", "2011-01-02", NaT],
|
267 |
+
freq="D",
|
268 |
+
name="idx3",
|
269 |
+
),
|
270 |
+
PeriodIndex(
|
271 |
+
[NaT, NaT, "2011-01-02", "2011-01-03", "2011-01-05"],
|
272 |
+
freq="D",
|
273 |
+
name="idx3",
|
274 |
+
),
|
275 |
+
),
|
276 |
+
(
|
277 |
+
PeriodIndex(
|
278 |
+
["2011", "2013", "2015", "2012", "2011"], name="pidx", freq="Y"
|
279 |
+
),
|
280 |
+
PeriodIndex(
|
281 |
+
["2011", "2011", "2012", "2013", "2015"], name="pidx", freq="Y"
|
282 |
+
),
|
283 |
+
),
|
284 |
+
(
|
285 |
+
# For compatibility check
|
286 |
+
Index([2011, 2013, 2015, 2012, 2011], name="idx"),
|
287 |
+
Index([2011, 2011, 2012, 2013, 2015], name="idx"),
|
288 |
+
),
|
289 |
+
],
|
290 |
+
)
|
291 |
+
def test_sort_values_without_freq_periodindex(self, idx, expected):
|
292 |
+
# here without_freq means not generateable by period_range
|
293 |
+
self.check_sort_values_without_freq(idx, expected)
|
294 |
+
|
295 |
+
def test_sort_values_without_freq_periodindex_nat(self):
|
296 |
+
# doesn't quite fit into check_sort_values_without_freq
|
297 |
+
idx = PeriodIndex(["2011", "2013", "NaT", "2011"], name="pidx", freq="D")
|
298 |
+
expected = PeriodIndex(["NaT", "2011", "2011", "2013"], name="pidx", freq="D")
|
299 |
+
|
300 |
+
ordered = idx.sort_values(na_position="first")
|
301 |
+
tm.assert_index_equal(ordered, expected)
|
302 |
+
check_freq_nonmonotonic(ordered, idx)
|
303 |
+
|
304 |
+
ordered = idx.sort_values(ascending=False)
|
305 |
+
tm.assert_index_equal(ordered, expected[::-1])
|
306 |
+
check_freq_nonmonotonic(ordered, idx)
|
307 |
+
|
308 |
+
|
309 |
+
def test_order_stability_compat():
|
310 |
+
# GH#35922. sort_values is stable both for normal and datetime-like Index
|
311 |
+
pidx = PeriodIndex(["2011", "2013", "2015", "2012", "2011"], name="pidx", freq="Y")
|
312 |
+
iidx = Index([2011, 2013, 2015, 2012, 2011], name="idx")
|
313 |
+
ordered1, indexer1 = pidx.sort_values(return_indexer=True, ascending=False)
|
314 |
+
ordered2, indexer2 = iidx.sort_values(return_indexer=True, ascending=False)
|
315 |
+
tm.assert_numpy_array_equal(indexer1, indexer2)
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_value_counts.py
ADDED
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
|
3 |
+
from pandas import (
|
4 |
+
DatetimeIndex,
|
5 |
+
NaT,
|
6 |
+
PeriodIndex,
|
7 |
+
Series,
|
8 |
+
TimedeltaIndex,
|
9 |
+
date_range,
|
10 |
+
period_range,
|
11 |
+
timedelta_range,
|
12 |
+
)
|
13 |
+
import pandas._testing as tm
|
14 |
+
|
15 |
+
|
16 |
+
class TestValueCounts:
|
17 |
+
# GH#7735
|
18 |
+
|
19 |
+
def test_value_counts_unique_datetimeindex(self, tz_naive_fixture):
|
20 |
+
tz = tz_naive_fixture
|
21 |
+
orig = date_range("2011-01-01 09:00", freq="h", periods=10, tz=tz)
|
22 |
+
self._check_value_counts_with_repeats(orig)
|
23 |
+
|
24 |
+
def test_value_counts_unique_timedeltaindex(self):
|
25 |
+
orig = timedelta_range("1 days 09:00:00", freq="h", periods=10)
|
26 |
+
self._check_value_counts_with_repeats(orig)
|
27 |
+
|
28 |
+
def test_value_counts_unique_periodindex(self):
|
29 |
+
orig = period_range("2011-01-01 09:00", freq="h", periods=10)
|
30 |
+
self._check_value_counts_with_repeats(orig)
|
31 |
+
|
32 |
+
def _check_value_counts_with_repeats(self, orig):
|
33 |
+
# create repeated values, 'n'th element is repeated by n+1 times
|
34 |
+
idx = type(orig)(
|
35 |
+
np.repeat(orig._values, range(1, len(orig) + 1)), dtype=orig.dtype
|
36 |
+
)
|
37 |
+
|
38 |
+
exp_idx = orig[::-1]
|
39 |
+
if not isinstance(exp_idx, PeriodIndex):
|
40 |
+
exp_idx = exp_idx._with_freq(None)
|
41 |
+
expected = Series(range(10, 0, -1), index=exp_idx, dtype="int64", name="count")
|
42 |
+
|
43 |
+
for obj in [idx, Series(idx)]:
|
44 |
+
tm.assert_series_equal(obj.value_counts(), expected)
|
45 |
+
|
46 |
+
tm.assert_index_equal(idx.unique(), orig)
|
47 |
+
|
48 |
+
def test_value_counts_unique_datetimeindex2(self, tz_naive_fixture):
|
49 |
+
tz = tz_naive_fixture
|
50 |
+
idx = DatetimeIndex(
|
51 |
+
[
|
52 |
+
"2013-01-01 09:00",
|
53 |
+
"2013-01-01 09:00",
|
54 |
+
"2013-01-01 09:00",
|
55 |
+
"2013-01-01 08:00",
|
56 |
+
"2013-01-01 08:00",
|
57 |
+
NaT,
|
58 |
+
],
|
59 |
+
tz=tz,
|
60 |
+
)
|
61 |
+
self._check_value_counts_dropna(idx)
|
62 |
+
|
63 |
+
def test_value_counts_unique_timedeltaindex2(self):
|
64 |
+
idx = TimedeltaIndex(
|
65 |
+
[
|
66 |
+
"1 days 09:00:00",
|
67 |
+
"1 days 09:00:00",
|
68 |
+
"1 days 09:00:00",
|
69 |
+
"1 days 08:00:00",
|
70 |
+
"1 days 08:00:00",
|
71 |
+
NaT,
|
72 |
+
]
|
73 |
+
)
|
74 |
+
self._check_value_counts_dropna(idx)
|
75 |
+
|
76 |
+
def test_value_counts_unique_periodindex2(self):
|
77 |
+
idx = PeriodIndex(
|
78 |
+
[
|
79 |
+
"2013-01-01 09:00",
|
80 |
+
"2013-01-01 09:00",
|
81 |
+
"2013-01-01 09:00",
|
82 |
+
"2013-01-01 08:00",
|
83 |
+
"2013-01-01 08:00",
|
84 |
+
NaT,
|
85 |
+
],
|
86 |
+
freq="h",
|
87 |
+
)
|
88 |
+
self._check_value_counts_dropna(idx)
|
89 |
+
|
90 |
+
def _check_value_counts_dropna(self, idx):
|
91 |
+
exp_idx = idx[[2, 3]]
|
92 |
+
expected = Series([3, 2], index=exp_idx, name="count")
|
93 |
+
|
94 |
+
for obj in [idx, Series(idx)]:
|
95 |
+
tm.assert_series_equal(obj.value_counts(), expected)
|
96 |
+
|
97 |
+
exp_idx = idx[[2, 3, -1]]
|
98 |
+
expected = Series([3, 2, 1], index=exp_idx, name="count")
|
99 |
+
|
100 |
+
for obj in [idx, Series(idx)]:
|
101 |
+
tm.assert_series_equal(obj.value_counts(dropna=False), expected)
|
102 |
+
|
103 |
+
tm.assert_index_equal(idx.unique(), exp_idx)
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/__init__.py
ADDED
File without changes
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (197 Bytes). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/__pycache__/test_astype.cpython-310.pyc
ADDED
Binary file (8.48 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/__pycache__/test_constructors.cpython-310.pyc
ADDED
Binary file (17.9 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/__pycache__/test_equals.cpython-310.pyc
ADDED
Binary file (1.18 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/__pycache__/test_formats.cpython-310.pyc
ADDED
Binary file (3.51 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/__pycache__/test_indexing.cpython-310.pyc
ADDED
Binary file (20.7 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/__pycache__/test_interval.cpython-310.pyc
ADDED
Binary file (24 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/__pycache__/test_interval_range.cpython-310.pyc
ADDED
Binary file (9.16 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/__pycache__/test_interval_tree.cpython-310.pyc
ADDED
Binary file (7.34 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/__pycache__/test_join.cpython-310.pyc
ADDED
Binary file (1.39 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/__pycache__/test_pickle.cpython-310.pyc
ADDED
Binary file (853 Bytes). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/__pycache__/test_setops.cpython-310.pyc
ADDED
Binary file (5.27 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/test_astype.py
ADDED
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
import pytest
|
5 |
+
|
6 |
+
from pandas.core.dtypes.dtypes import (
|
7 |
+
CategoricalDtype,
|
8 |
+
IntervalDtype,
|
9 |
+
)
|
10 |
+
|
11 |
+
from pandas import (
|
12 |
+
CategoricalIndex,
|
13 |
+
Index,
|
14 |
+
IntervalIndex,
|
15 |
+
NaT,
|
16 |
+
Timedelta,
|
17 |
+
Timestamp,
|
18 |
+
interval_range,
|
19 |
+
)
|
20 |
+
import pandas._testing as tm
|
21 |
+
|
22 |
+
|
23 |
+
class AstypeTests:
|
24 |
+
"""Tests common to IntervalIndex with any subtype"""
|
25 |
+
|
26 |
+
def test_astype_idempotent(self, index):
|
27 |
+
result = index.astype("interval")
|
28 |
+
tm.assert_index_equal(result, index)
|
29 |
+
|
30 |
+
result = index.astype(index.dtype)
|
31 |
+
tm.assert_index_equal(result, index)
|
32 |
+
|
33 |
+
def test_astype_object(self, index):
|
34 |
+
result = index.astype(object)
|
35 |
+
expected = Index(index.values, dtype="object")
|
36 |
+
tm.assert_index_equal(result, expected)
|
37 |
+
assert not result.equals(index)
|
38 |
+
|
39 |
+
def test_astype_category(self, index):
|
40 |
+
result = index.astype("category")
|
41 |
+
expected = CategoricalIndex(index.values)
|
42 |
+
tm.assert_index_equal(result, expected)
|
43 |
+
|
44 |
+
result = index.astype(CategoricalDtype())
|
45 |
+
tm.assert_index_equal(result, expected)
|
46 |
+
|
47 |
+
# non-default params
|
48 |
+
categories = index.dropna().unique().values[:-1]
|
49 |
+
dtype = CategoricalDtype(categories=categories, ordered=True)
|
50 |
+
result = index.astype(dtype)
|
51 |
+
expected = CategoricalIndex(index.values, categories=categories, ordered=True)
|
52 |
+
tm.assert_index_equal(result, expected)
|
53 |
+
|
54 |
+
@pytest.mark.parametrize(
|
55 |
+
"dtype",
|
56 |
+
[
|
57 |
+
"int64",
|
58 |
+
"uint64",
|
59 |
+
"float64",
|
60 |
+
"complex128",
|
61 |
+
"period[M]",
|
62 |
+
"timedelta64",
|
63 |
+
"timedelta64[ns]",
|
64 |
+
"datetime64",
|
65 |
+
"datetime64[ns]",
|
66 |
+
"datetime64[ns, US/Eastern]",
|
67 |
+
],
|
68 |
+
)
|
69 |
+
def test_astype_cannot_cast(self, index, dtype):
|
70 |
+
msg = "Cannot cast IntervalIndex to dtype"
|
71 |
+
with pytest.raises(TypeError, match=msg):
|
72 |
+
index.astype(dtype)
|
73 |
+
|
74 |
+
def test_astype_invalid_dtype(self, index):
|
75 |
+
msg = "data type [\"']fake_dtype[\"'] not understood"
|
76 |
+
with pytest.raises(TypeError, match=msg):
|
77 |
+
index.astype("fake_dtype")
|
78 |
+
|
79 |
+
|
80 |
+
class TestIntSubtype(AstypeTests):
|
81 |
+
"""Tests specific to IntervalIndex with integer-like subtype"""
|
82 |
+
|
83 |
+
indexes = [
|
84 |
+
IntervalIndex.from_breaks(np.arange(-10, 11, dtype="int64")),
|
85 |
+
IntervalIndex.from_breaks(np.arange(100, dtype="uint64"), closed="left"),
|
86 |
+
]
|
87 |
+
|
88 |
+
@pytest.fixture(params=indexes)
|
89 |
+
def index(self, request):
|
90 |
+
return request.param
|
91 |
+
|
92 |
+
@pytest.mark.parametrize(
|
93 |
+
"subtype", ["float64", "datetime64[ns]", "timedelta64[ns]"]
|
94 |
+
)
|
95 |
+
def test_subtype_conversion(self, index, subtype):
|
96 |
+
dtype = IntervalDtype(subtype, index.closed)
|
97 |
+
result = index.astype(dtype)
|
98 |
+
expected = IntervalIndex.from_arrays(
|
99 |
+
index.left.astype(subtype), index.right.astype(subtype), closed=index.closed
|
100 |
+
)
|
101 |
+
tm.assert_index_equal(result, expected)
|
102 |
+
|
103 |
+
@pytest.mark.parametrize(
|
104 |
+
"subtype_start, subtype_end", [("int64", "uint64"), ("uint64", "int64")]
|
105 |
+
)
|
106 |
+
def test_subtype_integer(self, subtype_start, subtype_end):
|
107 |
+
index = IntervalIndex.from_breaks(np.arange(100, dtype=subtype_start))
|
108 |
+
dtype = IntervalDtype(subtype_end, index.closed)
|
109 |
+
result = index.astype(dtype)
|
110 |
+
expected = IntervalIndex.from_arrays(
|
111 |
+
index.left.astype(subtype_end),
|
112 |
+
index.right.astype(subtype_end),
|
113 |
+
closed=index.closed,
|
114 |
+
)
|
115 |
+
tm.assert_index_equal(result, expected)
|
116 |
+
|
117 |
+
@pytest.mark.xfail(reason="GH#15832")
|
118 |
+
def test_subtype_integer_errors(self):
|
119 |
+
# int64 -> uint64 fails with negative values
|
120 |
+
index = interval_range(-10, 10)
|
121 |
+
dtype = IntervalDtype("uint64", "right")
|
122 |
+
|
123 |
+
# Until we decide what the exception message _should_ be, we
|
124 |
+
# assert something that it should _not_ be.
|
125 |
+
# We should _not_ be getting a message suggesting that the -10
|
126 |
+
# has been wrapped around to a large-positive integer
|
127 |
+
msg = "^(?!(left side of interval must be <= right side))"
|
128 |
+
with pytest.raises(ValueError, match=msg):
|
129 |
+
index.astype(dtype)
|
130 |
+
|
131 |
+
|
132 |
+
class TestFloatSubtype(AstypeTests):
|
133 |
+
"""Tests specific to IntervalIndex with float subtype"""
|
134 |
+
|
135 |
+
indexes = [
|
136 |
+
interval_range(-10.0, 10.0, closed="neither"),
|
137 |
+
IntervalIndex.from_arrays(
|
138 |
+
[-1.5, np.nan, 0.0, 0.0, 1.5], [-0.5, np.nan, 1.0, 1.0, 3.0], closed="both"
|
139 |
+
),
|
140 |
+
]
|
141 |
+
|
142 |
+
@pytest.fixture(params=indexes)
|
143 |
+
def index(self, request):
|
144 |
+
return request.param
|
145 |
+
|
146 |
+
@pytest.mark.parametrize("subtype", ["int64", "uint64"])
|
147 |
+
def test_subtype_integer(self, subtype):
|
148 |
+
index = interval_range(0.0, 10.0)
|
149 |
+
dtype = IntervalDtype(subtype, "right")
|
150 |
+
result = index.astype(dtype)
|
151 |
+
expected = IntervalIndex.from_arrays(
|
152 |
+
index.left.astype(subtype), index.right.astype(subtype), closed=index.closed
|
153 |
+
)
|
154 |
+
tm.assert_index_equal(result, expected)
|
155 |
+
|
156 |
+
# raises with NA
|
157 |
+
msg = r"Cannot convert non-finite values \(NA or inf\) to integer"
|
158 |
+
with pytest.raises(ValueError, match=msg):
|
159 |
+
index.insert(0, np.nan).astype(dtype)
|
160 |
+
|
161 |
+
@pytest.mark.parametrize("subtype", ["int64", "uint64"])
|
162 |
+
def test_subtype_integer_with_non_integer_borders(self, subtype):
|
163 |
+
index = interval_range(0.0, 3.0, freq=0.25)
|
164 |
+
dtype = IntervalDtype(subtype, "right")
|
165 |
+
result = index.astype(dtype)
|
166 |
+
expected = IntervalIndex.from_arrays(
|
167 |
+
index.left.astype(subtype), index.right.astype(subtype), closed=index.closed
|
168 |
+
)
|
169 |
+
tm.assert_index_equal(result, expected)
|
170 |
+
|
171 |
+
def test_subtype_integer_errors(self):
|
172 |
+
# float64 -> uint64 fails with negative values
|
173 |
+
index = interval_range(-10.0, 10.0)
|
174 |
+
dtype = IntervalDtype("uint64", "right")
|
175 |
+
msg = re.escape(
|
176 |
+
"Cannot convert interval[float64, right] to interval[uint64, right]; "
|
177 |
+
"subtypes are incompatible"
|
178 |
+
)
|
179 |
+
with pytest.raises(TypeError, match=msg):
|
180 |
+
index.astype(dtype)
|
181 |
+
|
182 |
+
@pytest.mark.parametrize("subtype", ["datetime64[ns]", "timedelta64[ns]"])
|
183 |
+
def test_subtype_datetimelike(self, index, subtype):
|
184 |
+
dtype = IntervalDtype(subtype, "right")
|
185 |
+
msg = "Cannot convert .* to .*; subtypes are incompatible"
|
186 |
+
with pytest.raises(TypeError, match=msg):
|
187 |
+
index.astype(dtype)
|
188 |
+
|
189 |
+
|
190 |
+
class TestDatetimelikeSubtype(AstypeTests):
|
191 |
+
"""Tests specific to IntervalIndex with datetime-like subtype"""
|
192 |
+
|
193 |
+
indexes = [
|
194 |
+
interval_range(Timestamp("2018-01-01"), periods=10, closed="neither"),
|
195 |
+
interval_range(Timestamp("2018-01-01"), periods=10).insert(2, NaT),
|
196 |
+
interval_range(Timestamp("2018-01-01", tz="US/Eastern"), periods=10),
|
197 |
+
interval_range(Timedelta("0 days"), periods=10, closed="both"),
|
198 |
+
interval_range(Timedelta("0 days"), periods=10).insert(2, NaT),
|
199 |
+
]
|
200 |
+
|
201 |
+
@pytest.fixture(params=indexes)
|
202 |
+
def index(self, request):
|
203 |
+
return request.param
|
204 |
+
|
205 |
+
@pytest.mark.parametrize("subtype", ["int64", "uint64"])
|
206 |
+
def test_subtype_integer(self, index, subtype):
|
207 |
+
dtype = IntervalDtype(subtype, "right")
|
208 |
+
|
209 |
+
if subtype != "int64":
|
210 |
+
msg = (
|
211 |
+
r"Cannot convert interval\[(timedelta64|datetime64)\[ns.*\], .*\] "
|
212 |
+
r"to interval\[uint64, .*\]"
|
213 |
+
)
|
214 |
+
with pytest.raises(TypeError, match=msg):
|
215 |
+
index.astype(dtype)
|
216 |
+
return
|
217 |
+
|
218 |
+
result = index.astype(dtype)
|
219 |
+
new_left = index.left.astype(subtype)
|
220 |
+
new_right = index.right.astype(subtype)
|
221 |
+
|
222 |
+
expected = IntervalIndex.from_arrays(new_left, new_right, closed=index.closed)
|
223 |
+
tm.assert_index_equal(result, expected)
|
224 |
+
|
225 |
+
def test_subtype_float(self, index):
|
226 |
+
dtype = IntervalDtype("float64", "right")
|
227 |
+
msg = "Cannot convert .* to .*; subtypes are incompatible"
|
228 |
+
with pytest.raises(TypeError, match=msg):
|
229 |
+
index.astype(dtype)
|
230 |
+
|
231 |
+
def test_subtype_datetimelike(self):
|
232 |
+
# datetime -> timedelta raises
|
233 |
+
dtype = IntervalDtype("timedelta64[ns]", "right")
|
234 |
+
msg = "Cannot convert .* to .*; subtypes are incompatible"
|
235 |
+
|
236 |
+
index = interval_range(Timestamp("2018-01-01"), periods=10)
|
237 |
+
with pytest.raises(TypeError, match=msg):
|
238 |
+
index.astype(dtype)
|
239 |
+
|
240 |
+
index = interval_range(Timestamp("2018-01-01", tz="CET"), periods=10)
|
241 |
+
with pytest.raises(TypeError, match=msg):
|
242 |
+
index.astype(dtype)
|
243 |
+
|
244 |
+
# timedelta -> datetime raises
|
245 |
+
dtype = IntervalDtype("datetime64[ns]", "right")
|
246 |
+
index = interval_range(Timedelta("0 days"), periods=10)
|
247 |
+
with pytest.raises(TypeError, match=msg):
|
248 |
+
index.astype(dtype)
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/test_constructors.py
ADDED
@@ -0,0 +1,535 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from functools import partial
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
import pytest
|
5 |
+
|
6 |
+
import pandas.util._test_decorators as td
|
7 |
+
|
8 |
+
from pandas.core.dtypes.common import is_unsigned_integer_dtype
|
9 |
+
from pandas.core.dtypes.dtypes import IntervalDtype
|
10 |
+
|
11 |
+
from pandas import (
|
12 |
+
Categorical,
|
13 |
+
CategoricalDtype,
|
14 |
+
CategoricalIndex,
|
15 |
+
Index,
|
16 |
+
Interval,
|
17 |
+
IntervalIndex,
|
18 |
+
date_range,
|
19 |
+
notna,
|
20 |
+
period_range,
|
21 |
+
timedelta_range,
|
22 |
+
)
|
23 |
+
import pandas._testing as tm
|
24 |
+
from pandas.core.arrays import IntervalArray
|
25 |
+
import pandas.core.common as com
|
26 |
+
|
27 |
+
|
28 |
+
@pytest.fixture(params=[None, "foo"])
|
29 |
+
def name(request):
|
30 |
+
return request.param
|
31 |
+
|
32 |
+
|
33 |
+
class ConstructorTests:
|
34 |
+
"""
|
35 |
+
Common tests for all variations of IntervalIndex construction. Input data
|
36 |
+
to be supplied in breaks format, then converted by the subclass method
|
37 |
+
get_kwargs_from_breaks to the expected format.
|
38 |
+
"""
|
39 |
+
|
40 |
+
@pytest.fixture(
|
41 |
+
params=[
|
42 |
+
([3, 14, 15, 92, 653], np.int64),
|
43 |
+
(np.arange(10, dtype="int64"), np.int64),
|
44 |
+
(Index(np.arange(-10, 11, dtype=np.int64)), np.int64),
|
45 |
+
(Index(np.arange(10, 31, dtype=np.uint64)), np.uint64),
|
46 |
+
(Index(np.arange(20, 30, 0.5), dtype=np.float64), np.float64),
|
47 |
+
(date_range("20180101", periods=10), "<M8[ns]"),
|
48 |
+
(
|
49 |
+
date_range("20180101", periods=10, tz="US/Eastern"),
|
50 |
+
"datetime64[ns, US/Eastern]",
|
51 |
+
),
|
52 |
+
(timedelta_range("1 day", periods=10), "<m8[ns]"),
|
53 |
+
]
|
54 |
+
)
|
55 |
+
def breaks_and_expected_subtype(self, request):
|
56 |
+
return request.param
|
57 |
+
|
58 |
+
def test_constructor(self, constructor, breaks_and_expected_subtype, closed, name):
|
59 |
+
breaks, expected_subtype = breaks_and_expected_subtype
|
60 |
+
|
61 |
+
result_kwargs = self.get_kwargs_from_breaks(breaks, closed)
|
62 |
+
|
63 |
+
result = constructor(closed=closed, name=name, **result_kwargs)
|
64 |
+
|
65 |
+
assert result.closed == closed
|
66 |
+
assert result.name == name
|
67 |
+
assert result.dtype.subtype == expected_subtype
|
68 |
+
tm.assert_index_equal(result.left, Index(breaks[:-1], dtype=expected_subtype))
|
69 |
+
tm.assert_index_equal(result.right, Index(breaks[1:], dtype=expected_subtype))
|
70 |
+
|
71 |
+
@pytest.mark.parametrize(
|
72 |
+
"breaks, subtype",
|
73 |
+
[
|
74 |
+
(Index([0, 1, 2, 3, 4], dtype=np.int64), "float64"),
|
75 |
+
(Index([0, 1, 2, 3, 4], dtype=np.int64), "datetime64[ns]"),
|
76 |
+
(Index([0, 1, 2, 3, 4], dtype=np.int64), "timedelta64[ns]"),
|
77 |
+
(Index([0, 1, 2, 3, 4], dtype=np.float64), "int64"),
|
78 |
+
(date_range("2017-01-01", periods=5), "int64"),
|
79 |
+
(timedelta_range("1 day", periods=5), "int64"),
|
80 |
+
],
|
81 |
+
)
|
82 |
+
def test_constructor_dtype(self, constructor, breaks, subtype):
|
83 |
+
# GH 19262: conversion via dtype parameter
|
84 |
+
expected_kwargs = self.get_kwargs_from_breaks(breaks.astype(subtype))
|
85 |
+
expected = constructor(**expected_kwargs)
|
86 |
+
|
87 |
+
result_kwargs = self.get_kwargs_from_breaks(breaks)
|
88 |
+
iv_dtype = IntervalDtype(subtype, "right")
|
89 |
+
for dtype in (iv_dtype, str(iv_dtype)):
|
90 |
+
result = constructor(dtype=dtype, **result_kwargs)
|
91 |
+
tm.assert_index_equal(result, expected)
|
92 |
+
|
93 |
+
@pytest.mark.parametrize(
|
94 |
+
"breaks",
|
95 |
+
[
|
96 |
+
Index([0, 1, 2, 3, 4], dtype=np.int64),
|
97 |
+
Index([0, 1, 2, 3, 4], dtype=np.uint64),
|
98 |
+
Index([0, 1, 2, 3, 4], dtype=np.float64),
|
99 |
+
date_range("2017-01-01", periods=5),
|
100 |
+
timedelta_range("1 day", periods=5),
|
101 |
+
],
|
102 |
+
)
|
103 |
+
def test_constructor_pass_closed(self, constructor, breaks):
|
104 |
+
# not passing closed to IntervalDtype, but to IntervalArray constructor
|
105 |
+
iv_dtype = IntervalDtype(breaks.dtype)
|
106 |
+
|
107 |
+
result_kwargs = self.get_kwargs_from_breaks(breaks)
|
108 |
+
|
109 |
+
for dtype in (iv_dtype, str(iv_dtype)):
|
110 |
+
with tm.assert_produces_warning(None):
|
111 |
+
result = constructor(dtype=dtype, closed="left", **result_kwargs)
|
112 |
+
assert result.dtype.closed == "left"
|
113 |
+
|
114 |
+
@pytest.mark.parametrize("breaks", [[np.nan] * 2, [np.nan] * 4, [np.nan] * 50])
|
115 |
+
def test_constructor_nan(self, constructor, breaks, closed):
|
116 |
+
# GH 18421
|
117 |
+
result_kwargs = self.get_kwargs_from_breaks(breaks)
|
118 |
+
result = constructor(closed=closed, **result_kwargs)
|
119 |
+
|
120 |
+
expected_subtype = np.float64
|
121 |
+
expected_values = np.array(breaks[:-1], dtype=object)
|
122 |
+
|
123 |
+
assert result.closed == closed
|
124 |
+
assert result.dtype.subtype == expected_subtype
|
125 |
+
tm.assert_numpy_array_equal(np.array(result), expected_values)
|
126 |
+
|
127 |
+
@pytest.mark.parametrize(
|
128 |
+
"breaks",
|
129 |
+
[
|
130 |
+
[],
|
131 |
+
np.array([], dtype="int64"),
|
132 |
+
np.array([], dtype="uint64"),
|
133 |
+
np.array([], dtype="float64"),
|
134 |
+
np.array([], dtype="datetime64[ns]"),
|
135 |
+
np.array([], dtype="timedelta64[ns]"),
|
136 |
+
],
|
137 |
+
)
|
138 |
+
def test_constructor_empty(self, constructor, breaks, closed):
|
139 |
+
# GH 18421
|
140 |
+
result_kwargs = self.get_kwargs_from_breaks(breaks)
|
141 |
+
result = constructor(closed=closed, **result_kwargs)
|
142 |
+
|
143 |
+
expected_values = np.array([], dtype=object)
|
144 |
+
expected_subtype = getattr(breaks, "dtype", np.int64)
|
145 |
+
|
146 |
+
assert result.empty
|
147 |
+
assert result.closed == closed
|
148 |
+
assert result.dtype.subtype == expected_subtype
|
149 |
+
tm.assert_numpy_array_equal(np.array(result), expected_values)
|
150 |
+
|
151 |
+
@pytest.mark.parametrize(
|
152 |
+
"breaks",
|
153 |
+
[
|
154 |
+
tuple("0123456789"),
|
155 |
+
list("abcdefghij"),
|
156 |
+
np.array(list("abcdefghij"), dtype=object),
|
157 |
+
np.array(list("abcdefghij"), dtype="<U1"),
|
158 |
+
],
|
159 |
+
)
|
160 |
+
def test_constructor_string(self, constructor, breaks):
|
161 |
+
# GH 19016
|
162 |
+
msg = (
|
163 |
+
"category, object, and string subtypes are not supported "
|
164 |
+
"for IntervalIndex"
|
165 |
+
)
|
166 |
+
with pytest.raises(TypeError, match=msg):
|
167 |
+
constructor(**self.get_kwargs_from_breaks(breaks))
|
168 |
+
|
169 |
+
@pytest.mark.parametrize("cat_constructor", [Categorical, CategoricalIndex])
|
170 |
+
def test_constructor_categorical_valid(self, constructor, cat_constructor):
|
171 |
+
# GH 21243/21253
|
172 |
+
|
173 |
+
breaks = np.arange(10, dtype="int64")
|
174 |
+
expected = IntervalIndex.from_breaks(breaks)
|
175 |
+
|
176 |
+
cat_breaks = cat_constructor(breaks)
|
177 |
+
result_kwargs = self.get_kwargs_from_breaks(cat_breaks)
|
178 |
+
result = constructor(**result_kwargs)
|
179 |
+
tm.assert_index_equal(result, expected)
|
180 |
+
|
181 |
+
def test_generic_errors(self, constructor):
|
182 |
+
# filler input data to be used when supplying invalid kwargs
|
183 |
+
filler = self.get_kwargs_from_breaks(range(10))
|
184 |
+
|
185 |
+
# invalid closed
|
186 |
+
msg = "closed must be one of 'right', 'left', 'both', 'neither'"
|
187 |
+
with pytest.raises(ValueError, match=msg):
|
188 |
+
constructor(closed="invalid", **filler)
|
189 |
+
|
190 |
+
# unsupported dtype
|
191 |
+
msg = "dtype must be an IntervalDtype, got int64"
|
192 |
+
with pytest.raises(TypeError, match=msg):
|
193 |
+
constructor(dtype="int64", **filler)
|
194 |
+
|
195 |
+
# invalid dtype
|
196 |
+
msg = "data type [\"']invalid[\"'] not understood"
|
197 |
+
with pytest.raises(TypeError, match=msg):
|
198 |
+
constructor(dtype="invalid", **filler)
|
199 |
+
|
200 |
+
# no point in nesting periods in an IntervalIndex
|
201 |
+
periods = period_range("2000-01-01", periods=10)
|
202 |
+
periods_kwargs = self.get_kwargs_from_breaks(periods)
|
203 |
+
msg = "Period dtypes are not supported, use a PeriodIndex instead"
|
204 |
+
with pytest.raises(ValueError, match=msg):
|
205 |
+
constructor(**periods_kwargs)
|
206 |
+
|
207 |
+
# decreasing values
|
208 |
+
decreasing_kwargs = self.get_kwargs_from_breaks(range(10, -1, -1))
|
209 |
+
msg = "left side of interval must be <= right side"
|
210 |
+
with pytest.raises(ValueError, match=msg):
|
211 |
+
constructor(**decreasing_kwargs)
|
212 |
+
|
213 |
+
|
214 |
+
class TestFromArrays(ConstructorTests):
|
215 |
+
"""Tests specific to IntervalIndex.from_arrays"""
|
216 |
+
|
217 |
+
@pytest.fixture
|
218 |
+
def constructor(self):
|
219 |
+
return IntervalIndex.from_arrays
|
220 |
+
|
221 |
+
def get_kwargs_from_breaks(self, breaks, closed="right"):
|
222 |
+
"""
|
223 |
+
converts intervals in breaks format to a dictionary of kwargs to
|
224 |
+
specific to the format expected by IntervalIndex.from_arrays
|
225 |
+
"""
|
226 |
+
return {"left": breaks[:-1], "right": breaks[1:]}
|
227 |
+
|
228 |
+
def test_constructor_errors(self):
|
229 |
+
# GH 19016: categorical data
|
230 |
+
data = Categorical(list("01234abcde"), ordered=True)
|
231 |
+
msg = (
|
232 |
+
"category, object, and string subtypes are not supported "
|
233 |
+
"for IntervalIndex"
|
234 |
+
)
|
235 |
+
with pytest.raises(TypeError, match=msg):
|
236 |
+
IntervalIndex.from_arrays(data[:-1], data[1:])
|
237 |
+
|
238 |
+
# unequal length
|
239 |
+
left = [0, 1, 2]
|
240 |
+
right = [2, 3]
|
241 |
+
msg = "left and right must have the same length"
|
242 |
+
with pytest.raises(ValueError, match=msg):
|
243 |
+
IntervalIndex.from_arrays(left, right)
|
244 |
+
|
245 |
+
@pytest.mark.parametrize(
|
246 |
+
"left_subtype, right_subtype", [(np.int64, np.float64), (np.float64, np.int64)]
|
247 |
+
)
|
248 |
+
def test_mixed_float_int(self, left_subtype, right_subtype):
|
249 |
+
"""mixed int/float left/right results in float for both sides"""
|
250 |
+
left = np.arange(9, dtype=left_subtype)
|
251 |
+
right = np.arange(1, 10, dtype=right_subtype)
|
252 |
+
result = IntervalIndex.from_arrays(left, right)
|
253 |
+
|
254 |
+
expected_left = Index(left, dtype=np.float64)
|
255 |
+
expected_right = Index(right, dtype=np.float64)
|
256 |
+
expected_subtype = np.float64
|
257 |
+
|
258 |
+
tm.assert_index_equal(result.left, expected_left)
|
259 |
+
tm.assert_index_equal(result.right, expected_right)
|
260 |
+
assert result.dtype.subtype == expected_subtype
|
261 |
+
|
262 |
+
@pytest.mark.parametrize("interval_cls", [IntervalArray, IntervalIndex])
|
263 |
+
def test_from_arrays_mismatched_datetimelike_resos(self, interval_cls):
|
264 |
+
# GH#55714
|
265 |
+
left = date_range("2016-01-01", periods=3, unit="s")
|
266 |
+
right = date_range("2017-01-01", periods=3, unit="ms")
|
267 |
+
result = interval_cls.from_arrays(left, right)
|
268 |
+
expected = interval_cls.from_arrays(left.as_unit("ms"), right)
|
269 |
+
tm.assert_equal(result, expected)
|
270 |
+
|
271 |
+
# td64
|
272 |
+
left2 = left - left[0]
|
273 |
+
right2 = right - left[0]
|
274 |
+
result2 = interval_cls.from_arrays(left2, right2)
|
275 |
+
expected2 = interval_cls.from_arrays(left2.as_unit("ms"), right2)
|
276 |
+
tm.assert_equal(result2, expected2)
|
277 |
+
|
278 |
+
# dt64tz
|
279 |
+
left3 = left.tz_localize("UTC")
|
280 |
+
right3 = right.tz_localize("UTC")
|
281 |
+
result3 = interval_cls.from_arrays(left3, right3)
|
282 |
+
expected3 = interval_cls.from_arrays(left3.as_unit("ms"), right3)
|
283 |
+
tm.assert_equal(result3, expected3)
|
284 |
+
|
285 |
+
|
286 |
+
class TestFromBreaks(ConstructorTests):
|
287 |
+
"""Tests specific to IntervalIndex.from_breaks"""
|
288 |
+
|
289 |
+
@pytest.fixture
|
290 |
+
def constructor(self):
|
291 |
+
return IntervalIndex.from_breaks
|
292 |
+
|
293 |
+
def get_kwargs_from_breaks(self, breaks, closed="right"):
|
294 |
+
"""
|
295 |
+
converts intervals in breaks format to a dictionary of kwargs to
|
296 |
+
specific to the format expected by IntervalIndex.from_breaks
|
297 |
+
"""
|
298 |
+
return {"breaks": breaks}
|
299 |
+
|
300 |
+
def test_constructor_errors(self):
|
301 |
+
# GH 19016: categorical data
|
302 |
+
data = Categorical(list("01234abcde"), ordered=True)
|
303 |
+
msg = (
|
304 |
+
"category, object, and string subtypes are not supported "
|
305 |
+
"for IntervalIndex"
|
306 |
+
)
|
307 |
+
with pytest.raises(TypeError, match=msg):
|
308 |
+
IntervalIndex.from_breaks(data)
|
309 |
+
|
310 |
+
def test_length_one(self):
|
311 |
+
"""breaks of length one produce an empty IntervalIndex"""
|
312 |
+
breaks = [0]
|
313 |
+
result = IntervalIndex.from_breaks(breaks)
|
314 |
+
expected = IntervalIndex.from_breaks([])
|
315 |
+
tm.assert_index_equal(result, expected)
|
316 |
+
|
317 |
+
def test_left_right_dont_share_data(self):
|
318 |
+
# GH#36310
|
319 |
+
breaks = np.arange(5)
|
320 |
+
result = IntervalIndex.from_breaks(breaks)._data
|
321 |
+
assert result._left.base is None or result._left.base is not result._right.base
|
322 |
+
|
323 |
+
|
324 |
+
class TestFromTuples(ConstructorTests):
|
325 |
+
"""Tests specific to IntervalIndex.from_tuples"""
|
326 |
+
|
327 |
+
@pytest.fixture
|
328 |
+
def constructor(self):
|
329 |
+
return IntervalIndex.from_tuples
|
330 |
+
|
331 |
+
def get_kwargs_from_breaks(self, breaks, closed="right"):
|
332 |
+
"""
|
333 |
+
converts intervals in breaks format to a dictionary of kwargs to
|
334 |
+
specific to the format expected by IntervalIndex.from_tuples
|
335 |
+
"""
|
336 |
+
if is_unsigned_integer_dtype(breaks):
|
337 |
+
pytest.skip(f"{breaks.dtype} not relevant IntervalIndex.from_tuples tests")
|
338 |
+
|
339 |
+
if len(breaks) == 0:
|
340 |
+
return {"data": breaks}
|
341 |
+
|
342 |
+
tuples = list(zip(breaks[:-1], breaks[1:]))
|
343 |
+
if isinstance(breaks, (list, tuple)):
|
344 |
+
return {"data": tuples}
|
345 |
+
elif isinstance(getattr(breaks, "dtype", None), CategoricalDtype):
|
346 |
+
return {"data": breaks._constructor(tuples)}
|
347 |
+
return {"data": com.asarray_tuplesafe(tuples)}
|
348 |
+
|
349 |
+
def test_constructor_errors(self):
|
350 |
+
# non-tuple
|
351 |
+
tuples = [(0, 1), 2, (3, 4)]
|
352 |
+
msg = "IntervalIndex.from_tuples received an invalid item, 2"
|
353 |
+
with pytest.raises(TypeError, match=msg.format(t=tuples)):
|
354 |
+
IntervalIndex.from_tuples(tuples)
|
355 |
+
|
356 |
+
# too few/many items
|
357 |
+
tuples = [(0, 1), (2,), (3, 4)]
|
358 |
+
msg = "IntervalIndex.from_tuples requires tuples of length 2, got {t}"
|
359 |
+
with pytest.raises(ValueError, match=msg.format(t=tuples)):
|
360 |
+
IntervalIndex.from_tuples(tuples)
|
361 |
+
|
362 |
+
tuples = [(0, 1), (2, 3, 4), (5, 6)]
|
363 |
+
with pytest.raises(ValueError, match=msg.format(t=tuples)):
|
364 |
+
IntervalIndex.from_tuples(tuples)
|
365 |
+
|
366 |
+
def test_na_tuples(self):
|
367 |
+
# tuple (NA, NA) evaluates the same as NA as an element
|
368 |
+
na_tuple = [(0, 1), (np.nan, np.nan), (2, 3)]
|
369 |
+
idx_na_tuple = IntervalIndex.from_tuples(na_tuple)
|
370 |
+
idx_na_element = IntervalIndex.from_tuples([(0, 1), np.nan, (2, 3)])
|
371 |
+
tm.assert_index_equal(idx_na_tuple, idx_na_element)
|
372 |
+
|
373 |
+
|
374 |
+
class TestClassConstructors(ConstructorTests):
|
375 |
+
"""Tests specific to the IntervalIndex/Index constructors"""
|
376 |
+
|
377 |
+
@pytest.fixture(
|
378 |
+
params=[IntervalIndex, partial(Index, dtype="interval")],
|
379 |
+
ids=["IntervalIndex", "Index"],
|
380 |
+
)
|
381 |
+
def klass(self, request):
|
382 |
+
# We use a separate fixture here to include Index.__new__ with dtype kwarg
|
383 |
+
return request.param
|
384 |
+
|
385 |
+
@pytest.fixture
|
386 |
+
def constructor(self):
|
387 |
+
return IntervalIndex
|
388 |
+
|
389 |
+
def get_kwargs_from_breaks(self, breaks, closed="right"):
|
390 |
+
"""
|
391 |
+
converts intervals in breaks format to a dictionary of kwargs to
|
392 |
+
specific to the format expected by the IntervalIndex/Index constructors
|
393 |
+
"""
|
394 |
+
if is_unsigned_integer_dtype(breaks):
|
395 |
+
pytest.skip(f"{breaks.dtype} not relevant for class constructor tests")
|
396 |
+
|
397 |
+
if len(breaks) == 0:
|
398 |
+
return {"data": breaks}
|
399 |
+
|
400 |
+
ivs = [
|
401 |
+
Interval(left, right, closed) if notna(left) else left
|
402 |
+
for left, right in zip(breaks[:-1], breaks[1:])
|
403 |
+
]
|
404 |
+
|
405 |
+
if isinstance(breaks, list):
|
406 |
+
return {"data": ivs}
|
407 |
+
elif isinstance(getattr(breaks, "dtype", None), CategoricalDtype):
|
408 |
+
return {"data": breaks._constructor(ivs)}
|
409 |
+
return {"data": np.array(ivs, dtype=object)}
|
410 |
+
|
411 |
+
def test_generic_errors(self, constructor):
|
412 |
+
"""
|
413 |
+
override the base class implementation since errors are handled
|
414 |
+
differently; checks unnecessary since caught at the Interval level
|
415 |
+
"""
|
416 |
+
|
417 |
+
def test_constructor_string(self):
|
418 |
+
# GH23013
|
419 |
+
# When forming the interval from breaks,
|
420 |
+
# the interval of strings is already forbidden.
|
421 |
+
pass
|
422 |
+
|
423 |
+
def test_constructor_errors(self, klass):
|
424 |
+
# mismatched closed within intervals with no constructor override
|
425 |
+
ivs = [Interval(0, 1, closed="right"), Interval(2, 3, closed="left")]
|
426 |
+
msg = "intervals must all be closed on the same side"
|
427 |
+
with pytest.raises(ValueError, match=msg):
|
428 |
+
klass(ivs)
|
429 |
+
|
430 |
+
# scalar
|
431 |
+
msg = (
|
432 |
+
r"(IntervalIndex|Index)\(...\) must be called with a collection of "
|
433 |
+
"some kind, 5 was passed"
|
434 |
+
)
|
435 |
+
with pytest.raises(TypeError, match=msg):
|
436 |
+
klass(5)
|
437 |
+
|
438 |
+
# not an interval; dtype depends on 32bit/windows builds
|
439 |
+
msg = "type <class 'numpy.int(32|64)'> with value 0 is not an interval"
|
440 |
+
with pytest.raises(TypeError, match=msg):
|
441 |
+
klass([0, 1])
|
442 |
+
|
443 |
+
@pytest.mark.parametrize(
|
444 |
+
"data, closed",
|
445 |
+
[
|
446 |
+
([], "both"),
|
447 |
+
([np.nan, np.nan], "neither"),
|
448 |
+
(
|
449 |
+
[Interval(0, 3, closed="neither"), Interval(2, 5, closed="neither")],
|
450 |
+
"left",
|
451 |
+
),
|
452 |
+
(
|
453 |
+
[Interval(0, 3, closed="left"), Interval(2, 5, closed="right")],
|
454 |
+
"neither",
|
455 |
+
),
|
456 |
+
(IntervalIndex.from_breaks(range(5), closed="both"), "right"),
|
457 |
+
],
|
458 |
+
)
|
459 |
+
def test_override_inferred_closed(self, constructor, data, closed):
|
460 |
+
# GH 19370
|
461 |
+
if isinstance(data, IntervalIndex):
|
462 |
+
tuples = data.to_tuples()
|
463 |
+
else:
|
464 |
+
tuples = [(iv.left, iv.right) if notna(iv) else iv for iv in data]
|
465 |
+
expected = IntervalIndex.from_tuples(tuples, closed=closed)
|
466 |
+
result = constructor(data, closed=closed)
|
467 |
+
tm.assert_index_equal(result, expected)
|
468 |
+
|
469 |
+
@pytest.mark.parametrize(
|
470 |
+
"values_constructor", [list, np.array, IntervalIndex, IntervalArray]
|
471 |
+
)
|
472 |
+
def test_index_object_dtype(self, values_constructor):
|
473 |
+
# Index(intervals, dtype=object) is an Index (not an IntervalIndex)
|
474 |
+
intervals = [Interval(0, 1), Interval(1, 2), Interval(2, 3)]
|
475 |
+
values = values_constructor(intervals)
|
476 |
+
result = Index(values, dtype=object)
|
477 |
+
|
478 |
+
assert type(result) is Index
|
479 |
+
tm.assert_numpy_array_equal(result.values, np.array(values))
|
480 |
+
|
481 |
+
def test_index_mixed_closed(self):
|
482 |
+
# GH27172
|
483 |
+
intervals = [
|
484 |
+
Interval(0, 1, closed="left"),
|
485 |
+
Interval(1, 2, closed="right"),
|
486 |
+
Interval(2, 3, closed="neither"),
|
487 |
+
Interval(3, 4, closed="both"),
|
488 |
+
]
|
489 |
+
result = Index(intervals)
|
490 |
+
expected = Index(intervals, dtype=object)
|
491 |
+
tm.assert_index_equal(result, expected)
|
492 |
+
|
493 |
+
|
494 |
+
@pytest.mark.parametrize("timezone", ["UTC", "US/Pacific", "GMT"])
|
495 |
+
def test_interval_index_subtype(timezone, inclusive_endpoints_fixture):
|
496 |
+
# GH#46999
|
497 |
+
dates = date_range("2022", periods=3, tz=timezone)
|
498 |
+
dtype = f"interval[datetime64[ns, {timezone}], {inclusive_endpoints_fixture}]"
|
499 |
+
result = IntervalIndex.from_arrays(
|
500 |
+
["2022-01-01", "2022-01-02"],
|
501 |
+
["2022-01-02", "2022-01-03"],
|
502 |
+
closed=inclusive_endpoints_fixture,
|
503 |
+
dtype=dtype,
|
504 |
+
)
|
505 |
+
expected = IntervalIndex.from_arrays(
|
506 |
+
dates[:-1], dates[1:], closed=inclusive_endpoints_fixture
|
507 |
+
)
|
508 |
+
tm.assert_index_equal(result, expected)
|
509 |
+
|
510 |
+
|
511 |
+
def test_dtype_closed_mismatch():
|
512 |
+
# GH#38394 closed specified in both dtype and IntervalIndex constructor
|
513 |
+
|
514 |
+
dtype = IntervalDtype(np.int64, "left")
|
515 |
+
|
516 |
+
msg = "closed keyword does not match dtype.closed"
|
517 |
+
with pytest.raises(ValueError, match=msg):
|
518 |
+
IntervalIndex([], dtype=dtype, closed="neither")
|
519 |
+
|
520 |
+
with pytest.raises(ValueError, match=msg):
|
521 |
+
IntervalArray([], dtype=dtype, closed="neither")
|
522 |
+
|
523 |
+
|
524 |
+
@pytest.mark.parametrize(
|
525 |
+
"dtype",
|
526 |
+
["Float64", pytest.param("float64[pyarrow]", marks=td.skip_if_no("pyarrow"))],
|
527 |
+
)
|
528 |
+
def test_ea_dtype(dtype):
|
529 |
+
# GH#56765
|
530 |
+
bins = [(0.0, 0.4), (0.4, 0.6)]
|
531 |
+
interval_dtype = IntervalDtype(subtype=dtype, closed="left")
|
532 |
+
result = IntervalIndex.from_tuples(bins, closed="left", dtype=interval_dtype)
|
533 |
+
assert result.dtype == interval_dtype
|
534 |
+
expected = IntervalIndex.from_tuples(bins, closed="left").astype(interval_dtype)
|
535 |
+
tm.assert_index_equal(result, expected)
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/test_equals.py
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
|
3 |
+
from pandas import (
|
4 |
+
IntervalIndex,
|
5 |
+
date_range,
|
6 |
+
)
|
7 |
+
|
8 |
+
|
9 |
+
class TestEquals:
|
10 |
+
def test_equals(self, closed):
|
11 |
+
expected = IntervalIndex.from_breaks(np.arange(5), closed=closed)
|
12 |
+
assert expected.equals(expected)
|
13 |
+
assert expected.equals(expected.copy())
|
14 |
+
|
15 |
+
assert not expected.equals(expected.astype(object))
|
16 |
+
assert not expected.equals(np.array(expected))
|
17 |
+
assert not expected.equals(list(expected))
|
18 |
+
|
19 |
+
assert not expected.equals([1, 2])
|
20 |
+
assert not expected.equals(np.array([1, 2]))
|
21 |
+
assert not expected.equals(date_range("20130101", periods=2))
|
22 |
+
|
23 |
+
expected_name1 = IntervalIndex.from_breaks(
|
24 |
+
np.arange(5), closed=closed, name="foo"
|
25 |
+
)
|
26 |
+
expected_name2 = IntervalIndex.from_breaks(
|
27 |
+
np.arange(5), closed=closed, name="bar"
|
28 |
+
)
|
29 |
+
assert expected.equals(expected_name1)
|
30 |
+
assert expected_name1.equals(expected_name2)
|
31 |
+
|
32 |
+
for other_closed in {"left", "right", "both", "neither"} - {closed}:
|
33 |
+
expected_other_closed = IntervalIndex.from_breaks(
|
34 |
+
np.arange(5), closed=other_closed
|
35 |
+
)
|
36 |
+
assert not expected.equals(expected_other_closed)
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/test_formats.py
ADDED
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas._config import using_pyarrow_string_dtype
|
5 |
+
|
6 |
+
from pandas import (
|
7 |
+
DataFrame,
|
8 |
+
DatetimeIndex,
|
9 |
+
Index,
|
10 |
+
Interval,
|
11 |
+
IntervalIndex,
|
12 |
+
Series,
|
13 |
+
Timedelta,
|
14 |
+
Timestamp,
|
15 |
+
)
|
16 |
+
import pandas._testing as tm
|
17 |
+
|
18 |
+
|
19 |
+
class TestIntervalIndexRendering:
|
20 |
+
# TODO: this is a test for DataFrame/Series, not IntervalIndex
|
21 |
+
@pytest.mark.parametrize(
|
22 |
+
"constructor,expected",
|
23 |
+
[
|
24 |
+
(
|
25 |
+
Series,
|
26 |
+
(
|
27 |
+
"(0.0, 1.0] a\n"
|
28 |
+
"NaN b\n"
|
29 |
+
"(2.0, 3.0] c\n"
|
30 |
+
"dtype: object"
|
31 |
+
),
|
32 |
+
),
|
33 |
+
(DataFrame, (" 0\n(0.0, 1.0] a\nNaN b\n(2.0, 3.0] c")),
|
34 |
+
],
|
35 |
+
)
|
36 |
+
def test_repr_missing(self, constructor, expected, using_infer_string, request):
|
37 |
+
# GH 25984
|
38 |
+
if using_infer_string and constructor is Series:
|
39 |
+
request.applymarker(pytest.mark.xfail(reason="repr different"))
|
40 |
+
index = IntervalIndex.from_tuples([(0, 1), np.nan, (2, 3)])
|
41 |
+
obj = constructor(list("abc"), index=index)
|
42 |
+
result = repr(obj)
|
43 |
+
assert result == expected
|
44 |
+
|
45 |
+
@pytest.mark.xfail(using_pyarrow_string_dtype(), reason="repr different")
|
46 |
+
def test_repr_floats(self):
|
47 |
+
# GH 32553
|
48 |
+
|
49 |
+
markers = Series(
|
50 |
+
["foo", "bar"],
|
51 |
+
index=IntervalIndex(
|
52 |
+
[
|
53 |
+
Interval(left, right)
|
54 |
+
for left, right in zip(
|
55 |
+
Index([329.973, 345.137], dtype="float64"),
|
56 |
+
Index([345.137, 360.191], dtype="float64"),
|
57 |
+
)
|
58 |
+
]
|
59 |
+
),
|
60 |
+
)
|
61 |
+
result = str(markers)
|
62 |
+
expected = "(329.973, 345.137] foo\n(345.137, 360.191] bar\ndtype: object"
|
63 |
+
assert result == expected
|
64 |
+
|
65 |
+
@pytest.mark.parametrize(
|
66 |
+
"tuples, closed, expected_data",
|
67 |
+
[
|
68 |
+
([(0, 1), (1, 2), (2, 3)], "left", ["[0, 1)", "[1, 2)", "[2, 3)"]),
|
69 |
+
(
|
70 |
+
[(0.5, 1.0), np.nan, (2.0, 3.0)],
|
71 |
+
"right",
|
72 |
+
["(0.5, 1.0]", "NaN", "(2.0, 3.0]"],
|
73 |
+
),
|
74 |
+
(
|
75 |
+
[
|
76 |
+
(Timestamp("20180101"), Timestamp("20180102")),
|
77 |
+
np.nan,
|
78 |
+
((Timestamp("20180102"), Timestamp("20180103"))),
|
79 |
+
],
|
80 |
+
"both",
|
81 |
+
[
|
82 |
+
"[2018-01-01 00:00:00, 2018-01-02 00:00:00]",
|
83 |
+
"NaN",
|
84 |
+
"[2018-01-02 00:00:00, 2018-01-03 00:00:00]",
|
85 |
+
],
|
86 |
+
),
|
87 |
+
(
|
88 |
+
[
|
89 |
+
(Timedelta("0 days"), Timedelta("1 days")),
|
90 |
+
(Timedelta("1 days"), Timedelta("2 days")),
|
91 |
+
np.nan,
|
92 |
+
],
|
93 |
+
"neither",
|
94 |
+
[
|
95 |
+
"(0 days 00:00:00, 1 days 00:00:00)",
|
96 |
+
"(1 days 00:00:00, 2 days 00:00:00)",
|
97 |
+
"NaN",
|
98 |
+
],
|
99 |
+
),
|
100 |
+
],
|
101 |
+
)
|
102 |
+
def test_get_values_for_csv(self, tuples, closed, expected_data):
|
103 |
+
# GH 28210
|
104 |
+
index = IntervalIndex.from_tuples(tuples, closed=closed)
|
105 |
+
result = index._get_values_for_csv(na_rep="NaN")
|
106 |
+
expected = np.array(expected_data)
|
107 |
+
tm.assert_numpy_array_equal(result, expected)
|
108 |
+
|
109 |
+
def test_timestamp_with_timezone(self, unit):
|
110 |
+
# GH 55035
|
111 |
+
left = DatetimeIndex(["2020-01-01"], dtype=f"M8[{unit}, UTC]")
|
112 |
+
right = DatetimeIndex(["2020-01-02"], dtype=f"M8[{unit}, UTC]")
|
113 |
+
index = IntervalIndex.from_arrays(left, right)
|
114 |
+
result = repr(index)
|
115 |
+
expected = (
|
116 |
+
"IntervalIndex([(2020-01-01 00:00:00+00:00, 2020-01-02 00:00:00+00:00]], "
|
117 |
+
f"dtype='interval[datetime64[{unit}, UTC], right]')"
|
118 |
+
)
|
119 |
+
assert result == expected
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/test_indexing.py
ADDED
@@ -0,0 +1,671 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
import pytest
|
5 |
+
|
6 |
+
from pandas.errors import InvalidIndexError
|
7 |
+
|
8 |
+
from pandas import (
|
9 |
+
NA,
|
10 |
+
CategoricalIndex,
|
11 |
+
DatetimeIndex,
|
12 |
+
Index,
|
13 |
+
Interval,
|
14 |
+
IntervalIndex,
|
15 |
+
MultiIndex,
|
16 |
+
NaT,
|
17 |
+
Timedelta,
|
18 |
+
Timestamp,
|
19 |
+
array,
|
20 |
+
date_range,
|
21 |
+
interval_range,
|
22 |
+
isna,
|
23 |
+
period_range,
|
24 |
+
timedelta_range,
|
25 |
+
)
|
26 |
+
import pandas._testing as tm
|
27 |
+
|
28 |
+
|
29 |
+
class TestGetItem:
|
30 |
+
def test_getitem(self, closed):
|
31 |
+
idx = IntervalIndex.from_arrays((0, 1, np.nan), (1, 2, np.nan), closed=closed)
|
32 |
+
assert idx[0] == Interval(0.0, 1.0, closed=closed)
|
33 |
+
assert idx[1] == Interval(1.0, 2.0, closed=closed)
|
34 |
+
assert isna(idx[2])
|
35 |
+
|
36 |
+
result = idx[0:1]
|
37 |
+
expected = IntervalIndex.from_arrays((0.0,), (1.0,), closed=closed)
|
38 |
+
tm.assert_index_equal(result, expected)
|
39 |
+
|
40 |
+
result = idx[0:2]
|
41 |
+
expected = IntervalIndex.from_arrays((0.0, 1), (1.0, 2.0), closed=closed)
|
42 |
+
tm.assert_index_equal(result, expected)
|
43 |
+
|
44 |
+
result = idx[1:3]
|
45 |
+
expected = IntervalIndex.from_arrays(
|
46 |
+
(1.0, np.nan), (2.0, np.nan), closed=closed
|
47 |
+
)
|
48 |
+
tm.assert_index_equal(result, expected)
|
49 |
+
|
50 |
+
def test_getitem_2d_deprecated(self):
|
51 |
+
# GH#30588 multi-dim indexing is deprecated, but raising is also acceptable
|
52 |
+
idx = IntervalIndex.from_breaks(range(11), closed="right")
|
53 |
+
with pytest.raises(ValueError, match="multi-dimensional indexing not allowed"):
|
54 |
+
idx[:, None]
|
55 |
+
with pytest.raises(ValueError, match="multi-dimensional indexing not allowed"):
|
56 |
+
# GH#44051
|
57 |
+
idx[True]
|
58 |
+
with pytest.raises(ValueError, match="multi-dimensional indexing not allowed"):
|
59 |
+
# GH#44051
|
60 |
+
idx[False]
|
61 |
+
|
62 |
+
|
63 |
+
class TestWhere:
|
64 |
+
def test_where(self, listlike_box):
|
65 |
+
klass = listlike_box
|
66 |
+
|
67 |
+
idx = IntervalIndex.from_breaks(range(11), closed="right")
|
68 |
+
cond = [True] * len(idx)
|
69 |
+
expected = idx
|
70 |
+
result = expected.where(klass(cond))
|
71 |
+
tm.assert_index_equal(result, expected)
|
72 |
+
|
73 |
+
cond = [False] + [True] * len(idx[1:])
|
74 |
+
expected = IntervalIndex([np.nan] + idx[1:].tolist())
|
75 |
+
result = idx.where(klass(cond))
|
76 |
+
tm.assert_index_equal(result, expected)
|
77 |
+
|
78 |
+
|
79 |
+
class TestTake:
|
80 |
+
def test_take(self, closed):
|
81 |
+
index = IntervalIndex.from_breaks(range(11), closed=closed)
|
82 |
+
|
83 |
+
result = index.take(range(10))
|
84 |
+
tm.assert_index_equal(result, index)
|
85 |
+
|
86 |
+
result = index.take([0, 0, 1])
|
87 |
+
expected = IntervalIndex.from_arrays([0, 0, 1], [1, 1, 2], closed=closed)
|
88 |
+
tm.assert_index_equal(result, expected)
|
89 |
+
|
90 |
+
|
91 |
+
class TestGetLoc:
|
92 |
+
@pytest.mark.parametrize("side", ["right", "left", "both", "neither"])
|
93 |
+
def test_get_loc_interval(self, closed, side):
|
94 |
+
idx = IntervalIndex.from_tuples([(0, 1), (2, 3)], closed=closed)
|
95 |
+
|
96 |
+
for bound in [[0, 1], [1, 2], [2, 3], [3, 4], [0, 2], [2.5, 3], [-1, 4]]:
|
97 |
+
# if get_loc is supplied an interval, it should only search
|
98 |
+
# for exact matches, not overlaps or covers, else KeyError.
|
99 |
+
msg = re.escape(f"Interval({bound[0]}, {bound[1]}, closed='{side}')")
|
100 |
+
if closed == side:
|
101 |
+
if bound == [0, 1]:
|
102 |
+
assert idx.get_loc(Interval(0, 1, closed=side)) == 0
|
103 |
+
elif bound == [2, 3]:
|
104 |
+
assert idx.get_loc(Interval(2, 3, closed=side)) == 1
|
105 |
+
else:
|
106 |
+
with pytest.raises(KeyError, match=msg):
|
107 |
+
idx.get_loc(Interval(*bound, closed=side))
|
108 |
+
else:
|
109 |
+
with pytest.raises(KeyError, match=msg):
|
110 |
+
idx.get_loc(Interval(*bound, closed=side))
|
111 |
+
|
112 |
+
@pytest.mark.parametrize("scalar", [-0.5, 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5])
|
113 |
+
def test_get_loc_scalar(self, closed, scalar):
|
114 |
+
# correct = {side: {query: answer}}.
|
115 |
+
# If query is not in the dict, that query should raise a KeyError
|
116 |
+
correct = {
|
117 |
+
"right": {0.5: 0, 1: 0, 2.5: 1, 3: 1},
|
118 |
+
"left": {0: 0, 0.5: 0, 2: 1, 2.5: 1},
|
119 |
+
"both": {0: 0, 0.5: 0, 1: 0, 2: 1, 2.5: 1, 3: 1},
|
120 |
+
"neither": {0.5: 0, 2.5: 1},
|
121 |
+
}
|
122 |
+
|
123 |
+
idx = IntervalIndex.from_tuples([(0, 1), (2, 3)], closed=closed)
|
124 |
+
|
125 |
+
# if get_loc is supplied a scalar, it should return the index of
|
126 |
+
# the interval which contains the scalar, or KeyError.
|
127 |
+
if scalar in correct[closed].keys():
|
128 |
+
assert idx.get_loc(scalar) == correct[closed][scalar]
|
129 |
+
else:
|
130 |
+
with pytest.raises(KeyError, match=str(scalar)):
|
131 |
+
idx.get_loc(scalar)
|
132 |
+
|
133 |
+
@pytest.mark.parametrize("scalar", [-1, 0, 0.5, 3, 4.5, 5, 6])
|
134 |
+
def test_get_loc_length_one_scalar(self, scalar, closed):
|
135 |
+
# GH 20921
|
136 |
+
index = IntervalIndex.from_tuples([(0, 5)], closed=closed)
|
137 |
+
if scalar in index[0]:
|
138 |
+
result = index.get_loc(scalar)
|
139 |
+
assert result == 0
|
140 |
+
else:
|
141 |
+
with pytest.raises(KeyError, match=str(scalar)):
|
142 |
+
index.get_loc(scalar)
|
143 |
+
|
144 |
+
@pytest.mark.parametrize("other_closed", ["left", "right", "both", "neither"])
|
145 |
+
@pytest.mark.parametrize("left, right", [(0, 5), (-1, 4), (-1, 6), (6, 7)])
|
146 |
+
def test_get_loc_length_one_interval(self, left, right, closed, other_closed):
|
147 |
+
# GH 20921
|
148 |
+
index = IntervalIndex.from_tuples([(0, 5)], closed=closed)
|
149 |
+
interval = Interval(left, right, closed=other_closed)
|
150 |
+
if interval == index[0]:
|
151 |
+
result = index.get_loc(interval)
|
152 |
+
assert result == 0
|
153 |
+
else:
|
154 |
+
with pytest.raises(
|
155 |
+
KeyError,
|
156 |
+
match=re.escape(f"Interval({left}, {right}, closed='{other_closed}')"),
|
157 |
+
):
|
158 |
+
index.get_loc(interval)
|
159 |
+
|
160 |
+
# Make consistent with test_interval_new.py (see #16316, #16386)
|
161 |
+
@pytest.mark.parametrize(
|
162 |
+
"breaks",
|
163 |
+
[
|
164 |
+
date_range("20180101", periods=4),
|
165 |
+
date_range("20180101", periods=4, tz="US/Eastern"),
|
166 |
+
timedelta_range("0 days", periods=4),
|
167 |
+
],
|
168 |
+
ids=lambda x: str(x.dtype),
|
169 |
+
)
|
170 |
+
def test_get_loc_datetimelike_nonoverlapping(self, breaks):
|
171 |
+
# GH 20636
|
172 |
+
# nonoverlapping = IntervalIndex method and no i8 conversion
|
173 |
+
index = IntervalIndex.from_breaks(breaks)
|
174 |
+
|
175 |
+
value = index[0].mid
|
176 |
+
result = index.get_loc(value)
|
177 |
+
expected = 0
|
178 |
+
assert result == expected
|
179 |
+
|
180 |
+
interval = Interval(index[0].left, index[0].right)
|
181 |
+
result = index.get_loc(interval)
|
182 |
+
expected = 0
|
183 |
+
assert result == expected
|
184 |
+
|
185 |
+
@pytest.mark.parametrize(
|
186 |
+
"arrays",
|
187 |
+
[
|
188 |
+
(date_range("20180101", periods=4), date_range("20180103", periods=4)),
|
189 |
+
(
|
190 |
+
date_range("20180101", periods=4, tz="US/Eastern"),
|
191 |
+
date_range("20180103", periods=4, tz="US/Eastern"),
|
192 |
+
),
|
193 |
+
(
|
194 |
+
timedelta_range("0 days", periods=4),
|
195 |
+
timedelta_range("2 days", periods=4),
|
196 |
+
),
|
197 |
+
],
|
198 |
+
ids=lambda x: str(x[0].dtype),
|
199 |
+
)
|
200 |
+
def test_get_loc_datetimelike_overlapping(self, arrays):
|
201 |
+
# GH 20636
|
202 |
+
index = IntervalIndex.from_arrays(*arrays)
|
203 |
+
|
204 |
+
value = index[0].mid + Timedelta("12 hours")
|
205 |
+
result = index.get_loc(value)
|
206 |
+
expected = slice(0, 2, None)
|
207 |
+
assert result == expected
|
208 |
+
|
209 |
+
interval = Interval(index[0].left, index[0].right)
|
210 |
+
result = index.get_loc(interval)
|
211 |
+
expected = 0
|
212 |
+
assert result == expected
|
213 |
+
|
214 |
+
@pytest.mark.parametrize(
|
215 |
+
"values",
|
216 |
+
[
|
217 |
+
date_range("2018-01-04", periods=4, freq="-1D"),
|
218 |
+
date_range("2018-01-04", periods=4, freq="-1D", tz="US/Eastern"),
|
219 |
+
timedelta_range("3 days", periods=4, freq="-1D"),
|
220 |
+
np.arange(3.0, -1.0, -1.0),
|
221 |
+
np.arange(3, -1, -1),
|
222 |
+
],
|
223 |
+
ids=lambda x: str(x.dtype),
|
224 |
+
)
|
225 |
+
def test_get_loc_decreasing(self, values):
|
226 |
+
# GH 25860
|
227 |
+
index = IntervalIndex.from_arrays(values[1:], values[:-1])
|
228 |
+
result = index.get_loc(index[0])
|
229 |
+
expected = 0
|
230 |
+
assert result == expected
|
231 |
+
|
232 |
+
@pytest.mark.parametrize("key", [[5], (2, 3)])
|
233 |
+
def test_get_loc_non_scalar_errors(self, key):
|
234 |
+
# GH 31117
|
235 |
+
idx = IntervalIndex.from_tuples([(1, 3), (2, 4), (3, 5), (7, 10), (3, 10)])
|
236 |
+
|
237 |
+
msg = str(key)
|
238 |
+
with pytest.raises(InvalidIndexError, match=msg):
|
239 |
+
idx.get_loc(key)
|
240 |
+
|
241 |
+
def test_get_indexer_with_nans(self):
|
242 |
+
# GH#41831
|
243 |
+
index = IntervalIndex([np.nan, Interval(1, 2), np.nan])
|
244 |
+
|
245 |
+
expected = np.array([True, False, True])
|
246 |
+
for key in [None, np.nan, NA]:
|
247 |
+
assert key in index
|
248 |
+
result = index.get_loc(key)
|
249 |
+
tm.assert_numpy_array_equal(result, expected)
|
250 |
+
|
251 |
+
for key in [NaT, np.timedelta64("NaT", "ns"), np.datetime64("NaT", "ns")]:
|
252 |
+
with pytest.raises(KeyError, match=str(key)):
|
253 |
+
index.get_loc(key)
|
254 |
+
|
255 |
+
|
256 |
+
class TestGetIndexer:
|
257 |
+
@pytest.mark.parametrize(
|
258 |
+
"query, expected",
|
259 |
+
[
|
260 |
+
([Interval(2, 4, closed="right")], [1]),
|
261 |
+
([Interval(2, 4, closed="left")], [-1]),
|
262 |
+
([Interval(2, 4, closed="both")], [-1]),
|
263 |
+
([Interval(2, 4, closed="neither")], [-1]),
|
264 |
+
([Interval(1, 4, closed="right")], [-1]),
|
265 |
+
([Interval(0, 4, closed="right")], [-1]),
|
266 |
+
([Interval(0.5, 1.5, closed="right")], [-1]),
|
267 |
+
([Interval(2, 4, closed="right"), Interval(0, 1, closed="right")], [1, -1]),
|
268 |
+
([Interval(2, 4, closed="right"), Interval(2, 4, closed="right")], [1, 1]),
|
269 |
+
([Interval(5, 7, closed="right"), Interval(2, 4, closed="right")], [2, 1]),
|
270 |
+
([Interval(2, 4, closed="right"), Interval(2, 4, closed="left")], [1, -1]),
|
271 |
+
],
|
272 |
+
)
|
273 |
+
def test_get_indexer_with_interval(self, query, expected):
|
274 |
+
tuples = [(0, 2), (2, 4), (5, 7)]
|
275 |
+
index = IntervalIndex.from_tuples(tuples, closed="right")
|
276 |
+
|
277 |
+
result = index.get_indexer(query)
|
278 |
+
expected = np.array(expected, dtype="intp")
|
279 |
+
tm.assert_numpy_array_equal(result, expected)
|
280 |
+
|
281 |
+
@pytest.mark.parametrize(
|
282 |
+
"query, expected",
|
283 |
+
[
|
284 |
+
([-0.5], [-1]),
|
285 |
+
([0], [-1]),
|
286 |
+
([0.5], [0]),
|
287 |
+
([1], [0]),
|
288 |
+
([1.5], [1]),
|
289 |
+
([2], [1]),
|
290 |
+
([2.5], [-1]),
|
291 |
+
([3], [-1]),
|
292 |
+
([3.5], [2]),
|
293 |
+
([4], [2]),
|
294 |
+
([4.5], [-1]),
|
295 |
+
([1, 2], [0, 1]),
|
296 |
+
([1, 2, 3], [0, 1, -1]),
|
297 |
+
([1, 2, 3, 4], [0, 1, -1, 2]),
|
298 |
+
([1, 2, 3, 4, 2], [0, 1, -1, 2, 1]),
|
299 |
+
],
|
300 |
+
)
|
301 |
+
def test_get_indexer_with_int_and_float(self, query, expected):
|
302 |
+
tuples = [(0, 1), (1, 2), (3, 4)]
|
303 |
+
index = IntervalIndex.from_tuples(tuples, closed="right")
|
304 |
+
|
305 |
+
result = index.get_indexer(query)
|
306 |
+
expected = np.array(expected, dtype="intp")
|
307 |
+
tm.assert_numpy_array_equal(result, expected)
|
308 |
+
|
309 |
+
@pytest.mark.parametrize("item", [[3], np.arange(0.5, 5, 0.5)])
|
310 |
+
def test_get_indexer_length_one(self, item, closed):
|
311 |
+
# GH 17284
|
312 |
+
index = IntervalIndex.from_tuples([(0, 5)], closed=closed)
|
313 |
+
result = index.get_indexer(item)
|
314 |
+
expected = np.array([0] * len(item), dtype="intp")
|
315 |
+
tm.assert_numpy_array_equal(result, expected)
|
316 |
+
|
317 |
+
@pytest.mark.parametrize("size", [1, 5])
|
318 |
+
def test_get_indexer_length_one_interval(self, size, closed):
|
319 |
+
# GH 17284
|
320 |
+
index = IntervalIndex.from_tuples([(0, 5)], closed=closed)
|
321 |
+
result = index.get_indexer([Interval(0, 5, closed)] * size)
|
322 |
+
expected = np.array([0] * size, dtype="intp")
|
323 |
+
tm.assert_numpy_array_equal(result, expected)
|
324 |
+
|
325 |
+
@pytest.mark.parametrize(
|
326 |
+
"target",
|
327 |
+
[
|
328 |
+
IntervalIndex.from_tuples([(7, 8), (1, 2), (3, 4), (0, 1)]),
|
329 |
+
IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4), np.nan]),
|
330 |
+
IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4)], closed="both"),
|
331 |
+
[-1, 0, 0.5, 1, 2, 2.5, np.nan],
|
332 |
+
["foo", "foo", "bar", "baz"],
|
333 |
+
],
|
334 |
+
)
|
335 |
+
def test_get_indexer_categorical(self, target, ordered):
|
336 |
+
# GH 30063: categorical and non-categorical results should be consistent
|
337 |
+
index = IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4)])
|
338 |
+
categorical_target = CategoricalIndex(target, ordered=ordered)
|
339 |
+
|
340 |
+
result = index.get_indexer(categorical_target)
|
341 |
+
expected = index.get_indexer(target)
|
342 |
+
tm.assert_numpy_array_equal(result, expected)
|
343 |
+
|
344 |
+
def test_get_indexer_categorical_with_nans(self):
|
345 |
+
# GH#41934 nans in both index and in target
|
346 |
+
ii = IntervalIndex.from_breaks(range(5))
|
347 |
+
ii2 = ii.append(IntervalIndex([np.nan]))
|
348 |
+
ci2 = CategoricalIndex(ii2)
|
349 |
+
|
350 |
+
result = ii2.get_indexer(ci2)
|
351 |
+
expected = np.arange(5, dtype=np.intp)
|
352 |
+
tm.assert_numpy_array_equal(result, expected)
|
353 |
+
|
354 |
+
# not-all-matches
|
355 |
+
result = ii2[1:].get_indexer(ci2[::-1])
|
356 |
+
expected = np.array([3, 2, 1, 0, -1], dtype=np.intp)
|
357 |
+
tm.assert_numpy_array_equal(result, expected)
|
358 |
+
|
359 |
+
# non-unique target, non-unique nans
|
360 |
+
result = ii2.get_indexer(ci2.append(ci2))
|
361 |
+
expected = np.array([0, 1, 2, 3, 4, 0, 1, 2, 3, 4], dtype=np.intp)
|
362 |
+
tm.assert_numpy_array_equal(result, expected)
|
363 |
+
|
364 |
+
def test_get_indexer_datetime(self):
|
365 |
+
ii = IntervalIndex.from_breaks(date_range("2018-01-01", periods=4))
|
366 |
+
# TODO: with mismatched resolution get_indexer currently raises;
|
367 |
+
# this should probably coerce?
|
368 |
+
target = DatetimeIndex(["2018-01-02"], dtype="M8[ns]")
|
369 |
+
result = ii.get_indexer(target)
|
370 |
+
expected = np.array([0], dtype=np.intp)
|
371 |
+
tm.assert_numpy_array_equal(result, expected)
|
372 |
+
|
373 |
+
result = ii.get_indexer(target.astype(str))
|
374 |
+
tm.assert_numpy_array_equal(result, expected)
|
375 |
+
|
376 |
+
# https://github.com/pandas-dev/pandas/issues/47772
|
377 |
+
result = ii.get_indexer(target.asi8)
|
378 |
+
expected = np.array([-1], dtype=np.intp)
|
379 |
+
tm.assert_numpy_array_equal(result, expected)
|
380 |
+
|
381 |
+
@pytest.mark.parametrize(
|
382 |
+
"tuples, closed",
|
383 |
+
[
|
384 |
+
([(0, 2), (1, 3), (3, 4)], "neither"),
|
385 |
+
([(0, 5), (1, 4), (6, 7)], "left"),
|
386 |
+
([(0, 1), (0, 1), (1, 2)], "right"),
|
387 |
+
([(0, 1), (2, 3), (3, 4)], "both"),
|
388 |
+
],
|
389 |
+
)
|
390 |
+
def test_get_indexer_errors(self, tuples, closed):
|
391 |
+
# IntervalIndex needs non-overlapping for uniqueness when querying
|
392 |
+
index = IntervalIndex.from_tuples(tuples, closed=closed)
|
393 |
+
|
394 |
+
msg = (
|
395 |
+
"cannot handle overlapping indices; use "
|
396 |
+
"IntervalIndex.get_indexer_non_unique"
|
397 |
+
)
|
398 |
+
with pytest.raises(InvalidIndexError, match=msg):
|
399 |
+
index.get_indexer([0, 2])
|
400 |
+
|
401 |
+
@pytest.mark.parametrize(
|
402 |
+
"query, expected",
|
403 |
+
[
|
404 |
+
([-0.5], ([-1], [0])),
|
405 |
+
([0], ([0], [])),
|
406 |
+
([0.5], ([0], [])),
|
407 |
+
([1], ([0, 1], [])),
|
408 |
+
([1.5], ([0, 1], [])),
|
409 |
+
([2], ([0, 1, 2], [])),
|
410 |
+
([2.5], ([1, 2], [])),
|
411 |
+
([3], ([2], [])),
|
412 |
+
([3.5], ([2], [])),
|
413 |
+
([4], ([-1], [0])),
|
414 |
+
([4.5], ([-1], [0])),
|
415 |
+
([1, 2], ([0, 1, 0, 1, 2], [])),
|
416 |
+
([1, 2, 3], ([0, 1, 0, 1, 2, 2], [])),
|
417 |
+
([1, 2, 3, 4], ([0, 1, 0, 1, 2, 2, -1], [3])),
|
418 |
+
([1, 2, 3, 4, 2], ([0, 1, 0, 1, 2, 2, -1, 0, 1, 2], [3])),
|
419 |
+
],
|
420 |
+
)
|
421 |
+
def test_get_indexer_non_unique_with_int_and_float(self, query, expected):
|
422 |
+
tuples = [(0, 2.5), (1, 3), (2, 4)]
|
423 |
+
index = IntervalIndex.from_tuples(tuples, closed="left")
|
424 |
+
|
425 |
+
result_indexer, result_missing = index.get_indexer_non_unique(query)
|
426 |
+
expected_indexer = np.array(expected[0], dtype="intp")
|
427 |
+
expected_missing = np.array(expected[1], dtype="intp")
|
428 |
+
|
429 |
+
tm.assert_numpy_array_equal(result_indexer, expected_indexer)
|
430 |
+
tm.assert_numpy_array_equal(result_missing, expected_missing)
|
431 |
+
|
432 |
+
# TODO we may also want to test get_indexer for the case when
|
433 |
+
# the intervals are duplicated, decreasing, non-monotonic, etc..
|
434 |
+
|
435 |
+
def test_get_indexer_non_monotonic(self):
|
436 |
+
# GH 16410
|
437 |
+
idx1 = IntervalIndex.from_tuples([(2, 3), (4, 5), (0, 1)])
|
438 |
+
idx2 = IntervalIndex.from_tuples([(0, 1), (2, 3), (6, 7), (8, 9)])
|
439 |
+
result = idx1.get_indexer(idx2)
|
440 |
+
expected = np.array([2, 0, -1, -1], dtype=np.intp)
|
441 |
+
tm.assert_numpy_array_equal(result, expected)
|
442 |
+
|
443 |
+
result = idx1.get_indexer(idx1[1:])
|
444 |
+
expected = np.array([1, 2], dtype=np.intp)
|
445 |
+
tm.assert_numpy_array_equal(result, expected)
|
446 |
+
|
447 |
+
def test_get_indexer_with_nans(self):
|
448 |
+
# GH#41831
|
449 |
+
index = IntervalIndex([np.nan, np.nan])
|
450 |
+
other = IntervalIndex([np.nan])
|
451 |
+
|
452 |
+
assert not index._index_as_unique
|
453 |
+
|
454 |
+
result = index.get_indexer_for(other)
|
455 |
+
expected = np.array([0, 1], dtype=np.intp)
|
456 |
+
tm.assert_numpy_array_equal(result, expected)
|
457 |
+
|
458 |
+
def test_get_index_non_unique_non_monotonic(self):
|
459 |
+
# GH#44084 (root cause)
|
460 |
+
index = IntervalIndex.from_tuples(
|
461 |
+
[(0.0, 1.0), (1.0, 2.0), (0.0, 1.0), (1.0, 2.0)]
|
462 |
+
)
|
463 |
+
|
464 |
+
result, _ = index.get_indexer_non_unique([Interval(1.0, 2.0)])
|
465 |
+
expected = np.array([1, 3], dtype=np.intp)
|
466 |
+
tm.assert_numpy_array_equal(result, expected)
|
467 |
+
|
468 |
+
def test_get_indexer_multiindex_with_intervals(self):
|
469 |
+
# GH#44084 (MultiIndex case as reported)
|
470 |
+
interval_index = IntervalIndex.from_tuples(
|
471 |
+
[(2.0, 3.0), (0.0, 1.0), (1.0, 2.0)], name="interval"
|
472 |
+
)
|
473 |
+
foo_index = Index([1, 2, 3], name="foo")
|
474 |
+
|
475 |
+
multi_index = MultiIndex.from_product([foo_index, interval_index])
|
476 |
+
|
477 |
+
result = multi_index.get_level_values("interval").get_indexer_for(
|
478 |
+
[Interval(0.0, 1.0)]
|
479 |
+
)
|
480 |
+
expected = np.array([1, 4, 7], dtype=np.intp)
|
481 |
+
tm.assert_numpy_array_equal(result, expected)
|
482 |
+
|
483 |
+
@pytest.mark.parametrize("box", [IntervalIndex, array, list])
|
484 |
+
def test_get_indexer_interval_index(self, box):
|
485 |
+
# GH#30178
|
486 |
+
rng = period_range("2022-07-01", freq="D", periods=3)
|
487 |
+
idx = box(interval_range(Timestamp("2022-07-01"), freq="3D", periods=3))
|
488 |
+
|
489 |
+
actual = rng.get_indexer(idx)
|
490 |
+
expected = np.array([-1, -1, -1], dtype=np.intp)
|
491 |
+
tm.assert_numpy_array_equal(actual, expected)
|
492 |
+
|
493 |
+
def test_get_indexer_read_only(self):
|
494 |
+
idx = interval_range(start=0, end=5)
|
495 |
+
arr = np.array([1, 2])
|
496 |
+
arr.flags.writeable = False
|
497 |
+
result = idx.get_indexer(arr)
|
498 |
+
expected = np.array([0, 1])
|
499 |
+
tm.assert_numpy_array_equal(result, expected, check_dtype=False)
|
500 |
+
|
501 |
+
result = idx.get_indexer_non_unique(arr)[0]
|
502 |
+
tm.assert_numpy_array_equal(result, expected, check_dtype=False)
|
503 |
+
|
504 |
+
|
505 |
+
class TestSliceLocs:
|
506 |
+
def test_slice_locs_with_interval(self):
|
507 |
+
# increasing monotonically
|
508 |
+
index = IntervalIndex.from_tuples([(0, 2), (1, 3), (2, 4)])
|
509 |
+
|
510 |
+
assert index.slice_locs(start=Interval(0, 2), end=Interval(2, 4)) == (0, 3)
|
511 |
+
assert index.slice_locs(start=Interval(0, 2)) == (0, 3)
|
512 |
+
assert index.slice_locs(end=Interval(2, 4)) == (0, 3)
|
513 |
+
assert index.slice_locs(end=Interval(0, 2)) == (0, 1)
|
514 |
+
assert index.slice_locs(start=Interval(2, 4), end=Interval(0, 2)) == (2, 1)
|
515 |
+
|
516 |
+
# decreasing monotonically
|
517 |
+
index = IntervalIndex.from_tuples([(2, 4), (1, 3), (0, 2)])
|
518 |
+
|
519 |
+
assert index.slice_locs(start=Interval(0, 2), end=Interval(2, 4)) == (2, 1)
|
520 |
+
assert index.slice_locs(start=Interval(0, 2)) == (2, 3)
|
521 |
+
assert index.slice_locs(end=Interval(2, 4)) == (0, 1)
|
522 |
+
assert index.slice_locs(end=Interval(0, 2)) == (0, 3)
|
523 |
+
assert index.slice_locs(start=Interval(2, 4), end=Interval(0, 2)) == (0, 3)
|
524 |
+
|
525 |
+
# sorted duplicates
|
526 |
+
index = IntervalIndex.from_tuples([(0, 2), (0, 2), (2, 4)])
|
527 |
+
|
528 |
+
assert index.slice_locs(start=Interval(0, 2), end=Interval(2, 4)) == (0, 3)
|
529 |
+
assert index.slice_locs(start=Interval(0, 2)) == (0, 3)
|
530 |
+
assert index.slice_locs(end=Interval(2, 4)) == (0, 3)
|
531 |
+
assert index.slice_locs(end=Interval(0, 2)) == (0, 2)
|
532 |
+
assert index.slice_locs(start=Interval(2, 4), end=Interval(0, 2)) == (2, 2)
|
533 |
+
|
534 |
+
# unsorted duplicates
|
535 |
+
index = IntervalIndex.from_tuples([(0, 2), (2, 4), (0, 2)])
|
536 |
+
|
537 |
+
with pytest.raises(
|
538 |
+
KeyError,
|
539 |
+
match=re.escape(
|
540 |
+
'"Cannot get left slice bound for non-unique label: '
|
541 |
+
"Interval(0, 2, closed='right')\""
|
542 |
+
),
|
543 |
+
):
|
544 |
+
index.slice_locs(start=Interval(0, 2), end=Interval(2, 4))
|
545 |
+
|
546 |
+
with pytest.raises(
|
547 |
+
KeyError,
|
548 |
+
match=re.escape(
|
549 |
+
'"Cannot get left slice bound for non-unique label: '
|
550 |
+
"Interval(0, 2, closed='right')\""
|
551 |
+
),
|
552 |
+
):
|
553 |
+
index.slice_locs(start=Interval(0, 2))
|
554 |
+
|
555 |
+
assert index.slice_locs(end=Interval(2, 4)) == (0, 2)
|
556 |
+
|
557 |
+
with pytest.raises(
|
558 |
+
KeyError,
|
559 |
+
match=re.escape(
|
560 |
+
'"Cannot get right slice bound for non-unique label: '
|
561 |
+
"Interval(0, 2, closed='right')\""
|
562 |
+
),
|
563 |
+
):
|
564 |
+
index.slice_locs(end=Interval(0, 2))
|
565 |
+
|
566 |
+
with pytest.raises(
|
567 |
+
KeyError,
|
568 |
+
match=re.escape(
|
569 |
+
'"Cannot get right slice bound for non-unique label: '
|
570 |
+
"Interval(0, 2, closed='right')\""
|
571 |
+
),
|
572 |
+
):
|
573 |
+
index.slice_locs(start=Interval(2, 4), end=Interval(0, 2))
|
574 |
+
|
575 |
+
# another unsorted duplicates
|
576 |
+
index = IntervalIndex.from_tuples([(0, 2), (0, 2), (2, 4), (1, 3)])
|
577 |
+
|
578 |
+
assert index.slice_locs(start=Interval(0, 2), end=Interval(2, 4)) == (0, 3)
|
579 |
+
assert index.slice_locs(start=Interval(0, 2)) == (0, 4)
|
580 |
+
assert index.slice_locs(end=Interval(2, 4)) == (0, 3)
|
581 |
+
assert index.slice_locs(end=Interval(0, 2)) == (0, 2)
|
582 |
+
assert index.slice_locs(start=Interval(2, 4), end=Interval(0, 2)) == (2, 2)
|
583 |
+
|
584 |
+
def test_slice_locs_with_ints_and_floats_succeeds(self):
|
585 |
+
# increasing non-overlapping
|
586 |
+
index = IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4)])
|
587 |
+
|
588 |
+
assert index.slice_locs(0, 1) == (0, 1)
|
589 |
+
assert index.slice_locs(0, 2) == (0, 2)
|
590 |
+
assert index.slice_locs(0, 3) == (0, 2)
|
591 |
+
assert index.slice_locs(3, 1) == (2, 1)
|
592 |
+
assert index.slice_locs(3, 4) == (2, 3)
|
593 |
+
assert index.slice_locs(0, 4) == (0, 3)
|
594 |
+
|
595 |
+
# decreasing non-overlapping
|
596 |
+
index = IntervalIndex.from_tuples([(3, 4), (1, 2), (0, 1)])
|
597 |
+
assert index.slice_locs(0, 1) == (3, 3)
|
598 |
+
assert index.slice_locs(0, 2) == (3, 2)
|
599 |
+
assert index.slice_locs(0, 3) == (3, 1)
|
600 |
+
assert index.slice_locs(3, 1) == (1, 3)
|
601 |
+
assert index.slice_locs(3, 4) == (1, 1)
|
602 |
+
assert index.slice_locs(0, 4) == (3, 1)
|
603 |
+
|
604 |
+
@pytest.mark.parametrize("query", [[0, 1], [0, 2], [0, 3], [0, 4]])
|
605 |
+
@pytest.mark.parametrize(
|
606 |
+
"tuples",
|
607 |
+
[
|
608 |
+
[(0, 2), (1, 3), (2, 4)],
|
609 |
+
[(2, 4), (1, 3), (0, 2)],
|
610 |
+
[(0, 2), (0, 2), (2, 4)],
|
611 |
+
[(0, 2), (2, 4), (0, 2)],
|
612 |
+
[(0, 2), (0, 2), (2, 4), (1, 3)],
|
613 |
+
],
|
614 |
+
)
|
615 |
+
def test_slice_locs_with_ints_and_floats_errors(self, tuples, query):
|
616 |
+
start, stop = query
|
617 |
+
index = IntervalIndex.from_tuples(tuples)
|
618 |
+
with pytest.raises(
|
619 |
+
KeyError,
|
620 |
+
match=(
|
621 |
+
"'can only get slices from an IntervalIndex if bounds are "
|
622 |
+
"non-overlapping and all monotonic increasing or decreasing'"
|
623 |
+
),
|
624 |
+
):
|
625 |
+
index.slice_locs(start, stop)
|
626 |
+
|
627 |
+
|
628 |
+
class TestPutmask:
|
629 |
+
@pytest.mark.parametrize("tz", ["US/Pacific", None])
|
630 |
+
def test_putmask_dt64(self, tz):
|
631 |
+
# GH#37968
|
632 |
+
dti = date_range("2016-01-01", periods=9, tz=tz)
|
633 |
+
idx = IntervalIndex.from_breaks(dti)
|
634 |
+
mask = np.zeros(idx.shape, dtype=bool)
|
635 |
+
mask[0:3] = True
|
636 |
+
|
637 |
+
result = idx.putmask(mask, idx[-1])
|
638 |
+
expected = IntervalIndex([idx[-1]] * 3 + list(idx[3:]))
|
639 |
+
tm.assert_index_equal(result, expected)
|
640 |
+
|
641 |
+
def test_putmask_td64(self):
|
642 |
+
# GH#37968
|
643 |
+
dti = date_range("2016-01-01", periods=9)
|
644 |
+
tdi = dti - dti[0]
|
645 |
+
idx = IntervalIndex.from_breaks(tdi)
|
646 |
+
mask = np.zeros(idx.shape, dtype=bool)
|
647 |
+
mask[0:3] = True
|
648 |
+
|
649 |
+
result = idx.putmask(mask, idx[-1])
|
650 |
+
expected = IntervalIndex([idx[-1]] * 3 + list(idx[3:]))
|
651 |
+
tm.assert_index_equal(result, expected)
|
652 |
+
|
653 |
+
|
654 |
+
class TestContains:
|
655 |
+
# .__contains__, not .contains
|
656 |
+
|
657 |
+
def test_contains_dunder(self):
|
658 |
+
index = IntervalIndex.from_arrays([0, 1], [1, 2], closed="right")
|
659 |
+
|
660 |
+
# __contains__ requires perfect matches to intervals.
|
661 |
+
assert 0 not in index
|
662 |
+
assert 1 not in index
|
663 |
+
assert 2 not in index
|
664 |
+
|
665 |
+
assert Interval(0, 1, closed="right") in index
|
666 |
+
assert Interval(0, 2, closed="right") not in index
|
667 |
+
assert Interval(0, 0.5, closed="right") not in index
|
668 |
+
assert Interval(3, 5, closed="right") not in index
|
669 |
+
assert Interval(-1, 0, closed="left") not in index
|
670 |
+
assert Interval(0, 1, closed="left") not in index
|
671 |
+
assert Interval(0, 1, closed="both") not in index
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/test_interval.py
ADDED
@@ -0,0 +1,918 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from itertools import permutations
|
2 |
+
import re
|
3 |
+
|
4 |
+
import numpy as np
|
5 |
+
import pytest
|
6 |
+
|
7 |
+
import pandas as pd
|
8 |
+
from pandas import (
|
9 |
+
Index,
|
10 |
+
Interval,
|
11 |
+
IntervalIndex,
|
12 |
+
Timedelta,
|
13 |
+
Timestamp,
|
14 |
+
date_range,
|
15 |
+
interval_range,
|
16 |
+
isna,
|
17 |
+
notna,
|
18 |
+
timedelta_range,
|
19 |
+
)
|
20 |
+
import pandas._testing as tm
|
21 |
+
import pandas.core.common as com
|
22 |
+
|
23 |
+
|
24 |
+
@pytest.fixture(params=[None, "foo"])
|
25 |
+
def name(request):
|
26 |
+
return request.param
|
27 |
+
|
28 |
+
|
29 |
+
class TestIntervalIndex:
|
30 |
+
index = IntervalIndex.from_arrays([0, 1], [1, 2])
|
31 |
+
|
32 |
+
def create_index(self, closed="right"):
|
33 |
+
return IntervalIndex.from_breaks(range(11), closed=closed)
|
34 |
+
|
35 |
+
def create_index_with_nan(self, closed="right"):
|
36 |
+
mask = [True, False] + [True] * 8
|
37 |
+
return IntervalIndex.from_arrays(
|
38 |
+
np.where(mask, np.arange(10), np.nan),
|
39 |
+
np.where(mask, np.arange(1, 11), np.nan),
|
40 |
+
closed=closed,
|
41 |
+
)
|
42 |
+
|
43 |
+
def test_properties(self, closed):
|
44 |
+
index = self.create_index(closed=closed)
|
45 |
+
assert len(index) == 10
|
46 |
+
assert index.size == 10
|
47 |
+
assert index.shape == (10,)
|
48 |
+
|
49 |
+
tm.assert_index_equal(index.left, Index(np.arange(10, dtype=np.int64)))
|
50 |
+
tm.assert_index_equal(index.right, Index(np.arange(1, 11, dtype=np.int64)))
|
51 |
+
tm.assert_index_equal(index.mid, Index(np.arange(0.5, 10.5, dtype=np.float64)))
|
52 |
+
|
53 |
+
assert index.closed == closed
|
54 |
+
|
55 |
+
ivs = [
|
56 |
+
Interval(left, right, closed)
|
57 |
+
for left, right in zip(range(10), range(1, 11))
|
58 |
+
]
|
59 |
+
expected = np.array(ivs, dtype=object)
|
60 |
+
tm.assert_numpy_array_equal(np.asarray(index), expected)
|
61 |
+
|
62 |
+
# with nans
|
63 |
+
index = self.create_index_with_nan(closed=closed)
|
64 |
+
assert len(index) == 10
|
65 |
+
assert index.size == 10
|
66 |
+
assert index.shape == (10,)
|
67 |
+
|
68 |
+
expected_left = Index([0, np.nan, 2, 3, 4, 5, 6, 7, 8, 9])
|
69 |
+
expected_right = expected_left + 1
|
70 |
+
expected_mid = expected_left + 0.5
|
71 |
+
tm.assert_index_equal(index.left, expected_left)
|
72 |
+
tm.assert_index_equal(index.right, expected_right)
|
73 |
+
tm.assert_index_equal(index.mid, expected_mid)
|
74 |
+
|
75 |
+
assert index.closed == closed
|
76 |
+
|
77 |
+
ivs = [
|
78 |
+
Interval(left, right, closed) if notna(left) else np.nan
|
79 |
+
for left, right in zip(expected_left, expected_right)
|
80 |
+
]
|
81 |
+
expected = np.array(ivs, dtype=object)
|
82 |
+
tm.assert_numpy_array_equal(np.asarray(index), expected)
|
83 |
+
|
84 |
+
@pytest.mark.parametrize(
|
85 |
+
"breaks",
|
86 |
+
[
|
87 |
+
[1, 1, 2, 5, 15, 53, 217, 1014, 5335, 31240, 201608],
|
88 |
+
[-np.inf, -100, -10, 0.5, 1, 1.5, 3.8, 101, 202, np.inf],
|
89 |
+
date_range("2017-01-01", "2017-01-04"),
|
90 |
+
pytest.param(
|
91 |
+
date_range("2017-01-01", "2017-01-04", unit="s"),
|
92 |
+
marks=pytest.mark.xfail(reason="mismatched result unit"),
|
93 |
+
),
|
94 |
+
pd.to_timedelta(["1ns", "2ms", "3s", "4min", "5h", "6D"]),
|
95 |
+
],
|
96 |
+
)
|
97 |
+
def test_length(self, closed, breaks):
|
98 |
+
# GH 18789
|
99 |
+
index = IntervalIndex.from_breaks(breaks, closed=closed)
|
100 |
+
result = index.length
|
101 |
+
expected = Index(iv.length for iv in index)
|
102 |
+
tm.assert_index_equal(result, expected)
|
103 |
+
|
104 |
+
# with NA
|
105 |
+
index = index.insert(1, np.nan)
|
106 |
+
result = index.length
|
107 |
+
expected = Index(iv.length if notna(iv) else iv for iv in index)
|
108 |
+
tm.assert_index_equal(result, expected)
|
109 |
+
|
110 |
+
def test_with_nans(self, closed):
|
111 |
+
index = self.create_index(closed=closed)
|
112 |
+
assert index.hasnans is False
|
113 |
+
|
114 |
+
result = index.isna()
|
115 |
+
expected = np.zeros(len(index), dtype=bool)
|
116 |
+
tm.assert_numpy_array_equal(result, expected)
|
117 |
+
|
118 |
+
result = index.notna()
|
119 |
+
expected = np.ones(len(index), dtype=bool)
|
120 |
+
tm.assert_numpy_array_equal(result, expected)
|
121 |
+
|
122 |
+
index = self.create_index_with_nan(closed=closed)
|
123 |
+
assert index.hasnans is True
|
124 |
+
|
125 |
+
result = index.isna()
|
126 |
+
expected = np.array([False, True] + [False] * (len(index) - 2))
|
127 |
+
tm.assert_numpy_array_equal(result, expected)
|
128 |
+
|
129 |
+
result = index.notna()
|
130 |
+
expected = np.array([True, False] + [True] * (len(index) - 2))
|
131 |
+
tm.assert_numpy_array_equal(result, expected)
|
132 |
+
|
133 |
+
def test_copy(self, closed):
|
134 |
+
expected = self.create_index(closed=closed)
|
135 |
+
|
136 |
+
result = expected.copy()
|
137 |
+
assert result.equals(expected)
|
138 |
+
|
139 |
+
result = expected.copy(deep=True)
|
140 |
+
assert result.equals(expected)
|
141 |
+
assert result.left is not expected.left
|
142 |
+
|
143 |
+
def test_ensure_copied_data(self, closed):
|
144 |
+
# exercise the copy flag in the constructor
|
145 |
+
|
146 |
+
# not copying
|
147 |
+
index = self.create_index(closed=closed)
|
148 |
+
result = IntervalIndex(index, copy=False)
|
149 |
+
tm.assert_numpy_array_equal(
|
150 |
+
index.left.values, result.left.values, check_same="same"
|
151 |
+
)
|
152 |
+
tm.assert_numpy_array_equal(
|
153 |
+
index.right.values, result.right.values, check_same="same"
|
154 |
+
)
|
155 |
+
|
156 |
+
# by-definition make a copy
|
157 |
+
result = IntervalIndex(np.array(index), copy=False)
|
158 |
+
tm.assert_numpy_array_equal(
|
159 |
+
index.left.values, result.left.values, check_same="copy"
|
160 |
+
)
|
161 |
+
tm.assert_numpy_array_equal(
|
162 |
+
index.right.values, result.right.values, check_same="copy"
|
163 |
+
)
|
164 |
+
|
165 |
+
def test_delete(self, closed):
|
166 |
+
breaks = np.arange(1, 11, dtype=np.int64)
|
167 |
+
expected = IntervalIndex.from_breaks(breaks, closed=closed)
|
168 |
+
result = self.create_index(closed=closed).delete(0)
|
169 |
+
tm.assert_index_equal(result, expected)
|
170 |
+
|
171 |
+
@pytest.mark.parametrize(
|
172 |
+
"data",
|
173 |
+
[
|
174 |
+
interval_range(0, periods=10, closed="neither"),
|
175 |
+
interval_range(1.7, periods=8, freq=2.5, closed="both"),
|
176 |
+
interval_range(Timestamp("20170101"), periods=12, closed="left"),
|
177 |
+
interval_range(Timedelta("1 day"), periods=6, closed="right"),
|
178 |
+
],
|
179 |
+
)
|
180 |
+
def test_insert(self, data):
|
181 |
+
item = data[0]
|
182 |
+
idx_item = IntervalIndex([item])
|
183 |
+
|
184 |
+
# start
|
185 |
+
expected = idx_item.append(data)
|
186 |
+
result = data.insert(0, item)
|
187 |
+
tm.assert_index_equal(result, expected)
|
188 |
+
|
189 |
+
# end
|
190 |
+
expected = data.append(idx_item)
|
191 |
+
result = data.insert(len(data), item)
|
192 |
+
tm.assert_index_equal(result, expected)
|
193 |
+
|
194 |
+
# mid
|
195 |
+
expected = data[:3].append(idx_item).append(data[3:])
|
196 |
+
result = data.insert(3, item)
|
197 |
+
tm.assert_index_equal(result, expected)
|
198 |
+
|
199 |
+
# invalid type
|
200 |
+
res = data.insert(1, "foo")
|
201 |
+
expected = data.astype(object).insert(1, "foo")
|
202 |
+
tm.assert_index_equal(res, expected)
|
203 |
+
|
204 |
+
msg = "can only insert Interval objects and NA into an IntervalArray"
|
205 |
+
with pytest.raises(TypeError, match=msg):
|
206 |
+
data._data.insert(1, "foo")
|
207 |
+
|
208 |
+
# invalid closed
|
209 |
+
msg = "'value.closed' is 'left', expected 'right'."
|
210 |
+
for closed in {"left", "right", "both", "neither"} - {item.closed}:
|
211 |
+
msg = f"'value.closed' is '{closed}', expected '{item.closed}'."
|
212 |
+
bad_item = Interval(item.left, item.right, closed=closed)
|
213 |
+
res = data.insert(1, bad_item)
|
214 |
+
expected = data.astype(object).insert(1, bad_item)
|
215 |
+
tm.assert_index_equal(res, expected)
|
216 |
+
with pytest.raises(ValueError, match=msg):
|
217 |
+
data._data.insert(1, bad_item)
|
218 |
+
|
219 |
+
# GH 18295 (test missing)
|
220 |
+
na_idx = IntervalIndex([np.nan], closed=data.closed)
|
221 |
+
for na in [np.nan, None, pd.NA]:
|
222 |
+
expected = data[:1].append(na_idx).append(data[1:])
|
223 |
+
result = data.insert(1, na)
|
224 |
+
tm.assert_index_equal(result, expected)
|
225 |
+
|
226 |
+
if data.left.dtype.kind not in ["m", "M"]:
|
227 |
+
# trying to insert pd.NaT into a numeric-dtyped Index should cast
|
228 |
+
expected = data.astype(object).insert(1, pd.NaT)
|
229 |
+
|
230 |
+
msg = "can only insert Interval objects and NA into an IntervalArray"
|
231 |
+
with pytest.raises(TypeError, match=msg):
|
232 |
+
data._data.insert(1, pd.NaT)
|
233 |
+
|
234 |
+
result = data.insert(1, pd.NaT)
|
235 |
+
tm.assert_index_equal(result, expected)
|
236 |
+
|
237 |
+
def test_is_unique_interval(self, closed):
|
238 |
+
"""
|
239 |
+
Interval specific tests for is_unique in addition to base class tests
|
240 |
+
"""
|
241 |
+
# unique overlapping - distinct endpoints
|
242 |
+
idx = IntervalIndex.from_tuples([(0, 1), (0.5, 1.5)], closed=closed)
|
243 |
+
assert idx.is_unique is True
|
244 |
+
|
245 |
+
# unique overlapping - shared endpoints
|
246 |
+
idx = IntervalIndex.from_tuples([(1, 2), (1, 3), (2, 3)], closed=closed)
|
247 |
+
assert idx.is_unique is True
|
248 |
+
|
249 |
+
# unique nested
|
250 |
+
idx = IntervalIndex.from_tuples([(-1, 1), (-2, 2)], closed=closed)
|
251 |
+
assert idx.is_unique is True
|
252 |
+
|
253 |
+
# unique NaN
|
254 |
+
idx = IntervalIndex.from_tuples([(np.nan, np.nan)], closed=closed)
|
255 |
+
assert idx.is_unique is True
|
256 |
+
|
257 |
+
# non-unique NaN
|
258 |
+
idx = IntervalIndex.from_tuples(
|
259 |
+
[(np.nan, np.nan), (np.nan, np.nan)], closed=closed
|
260 |
+
)
|
261 |
+
assert idx.is_unique is False
|
262 |
+
|
263 |
+
def test_monotonic(self, closed):
|
264 |
+
# increasing non-overlapping
|
265 |
+
idx = IntervalIndex.from_tuples([(0, 1), (2, 3), (4, 5)], closed=closed)
|
266 |
+
assert idx.is_monotonic_increasing is True
|
267 |
+
assert idx._is_strictly_monotonic_increasing is True
|
268 |
+
assert idx.is_monotonic_decreasing is False
|
269 |
+
assert idx._is_strictly_monotonic_decreasing is False
|
270 |
+
|
271 |
+
# decreasing non-overlapping
|
272 |
+
idx = IntervalIndex.from_tuples([(4, 5), (2, 3), (1, 2)], closed=closed)
|
273 |
+
assert idx.is_monotonic_increasing is False
|
274 |
+
assert idx._is_strictly_monotonic_increasing is False
|
275 |
+
assert idx.is_monotonic_decreasing is True
|
276 |
+
assert idx._is_strictly_monotonic_decreasing is True
|
277 |
+
|
278 |
+
# unordered non-overlapping
|
279 |
+
idx = IntervalIndex.from_tuples([(0, 1), (4, 5), (2, 3)], closed=closed)
|
280 |
+
assert idx.is_monotonic_increasing is False
|
281 |
+
assert idx._is_strictly_monotonic_increasing is False
|
282 |
+
assert idx.is_monotonic_decreasing is False
|
283 |
+
assert idx._is_strictly_monotonic_decreasing is False
|
284 |
+
|
285 |
+
# increasing overlapping
|
286 |
+
idx = IntervalIndex.from_tuples([(0, 2), (0.5, 2.5), (1, 3)], closed=closed)
|
287 |
+
assert idx.is_monotonic_increasing is True
|
288 |
+
assert idx._is_strictly_monotonic_increasing is True
|
289 |
+
assert idx.is_monotonic_decreasing is False
|
290 |
+
assert idx._is_strictly_monotonic_decreasing is False
|
291 |
+
|
292 |
+
# decreasing overlapping
|
293 |
+
idx = IntervalIndex.from_tuples([(1, 3), (0.5, 2.5), (0, 2)], closed=closed)
|
294 |
+
assert idx.is_monotonic_increasing is False
|
295 |
+
assert idx._is_strictly_monotonic_increasing is False
|
296 |
+
assert idx.is_monotonic_decreasing is True
|
297 |
+
assert idx._is_strictly_monotonic_decreasing is True
|
298 |
+
|
299 |
+
# unordered overlapping
|
300 |
+
idx = IntervalIndex.from_tuples([(0.5, 2.5), (0, 2), (1, 3)], closed=closed)
|
301 |
+
assert idx.is_monotonic_increasing is False
|
302 |
+
assert idx._is_strictly_monotonic_increasing is False
|
303 |
+
assert idx.is_monotonic_decreasing is False
|
304 |
+
assert idx._is_strictly_monotonic_decreasing is False
|
305 |
+
|
306 |
+
# increasing overlapping shared endpoints
|
307 |
+
idx = IntervalIndex.from_tuples([(1, 2), (1, 3), (2, 3)], closed=closed)
|
308 |
+
assert idx.is_monotonic_increasing is True
|
309 |
+
assert idx._is_strictly_monotonic_increasing is True
|
310 |
+
assert idx.is_monotonic_decreasing is False
|
311 |
+
assert idx._is_strictly_monotonic_decreasing is False
|
312 |
+
|
313 |
+
# decreasing overlapping shared endpoints
|
314 |
+
idx = IntervalIndex.from_tuples([(2, 3), (1, 3), (1, 2)], closed=closed)
|
315 |
+
assert idx.is_monotonic_increasing is False
|
316 |
+
assert idx._is_strictly_monotonic_increasing is False
|
317 |
+
assert idx.is_monotonic_decreasing is True
|
318 |
+
assert idx._is_strictly_monotonic_decreasing is True
|
319 |
+
|
320 |
+
# stationary
|
321 |
+
idx = IntervalIndex.from_tuples([(0, 1), (0, 1)], closed=closed)
|
322 |
+
assert idx.is_monotonic_increasing is True
|
323 |
+
assert idx._is_strictly_monotonic_increasing is False
|
324 |
+
assert idx.is_monotonic_decreasing is True
|
325 |
+
assert idx._is_strictly_monotonic_decreasing is False
|
326 |
+
|
327 |
+
# empty
|
328 |
+
idx = IntervalIndex([], closed=closed)
|
329 |
+
assert idx.is_monotonic_increasing is True
|
330 |
+
assert idx._is_strictly_monotonic_increasing is True
|
331 |
+
assert idx.is_monotonic_decreasing is True
|
332 |
+
assert idx._is_strictly_monotonic_decreasing is True
|
333 |
+
|
334 |
+
def test_is_monotonic_with_nans(self):
|
335 |
+
# GH#41831
|
336 |
+
index = IntervalIndex([np.nan, np.nan])
|
337 |
+
|
338 |
+
assert not index.is_monotonic_increasing
|
339 |
+
assert not index._is_strictly_monotonic_increasing
|
340 |
+
assert not index.is_monotonic_increasing
|
341 |
+
assert not index._is_strictly_monotonic_decreasing
|
342 |
+
assert not index.is_monotonic_decreasing
|
343 |
+
|
344 |
+
@pytest.mark.parametrize(
|
345 |
+
"breaks",
|
346 |
+
[
|
347 |
+
date_range("20180101", periods=4),
|
348 |
+
date_range("20180101", periods=4, tz="US/Eastern"),
|
349 |
+
timedelta_range("0 days", periods=4),
|
350 |
+
],
|
351 |
+
ids=lambda x: str(x.dtype),
|
352 |
+
)
|
353 |
+
def test_maybe_convert_i8(self, breaks):
|
354 |
+
# GH 20636
|
355 |
+
index = IntervalIndex.from_breaks(breaks)
|
356 |
+
|
357 |
+
# intervalindex
|
358 |
+
result = index._maybe_convert_i8(index)
|
359 |
+
expected = IntervalIndex.from_breaks(breaks.asi8)
|
360 |
+
tm.assert_index_equal(result, expected)
|
361 |
+
|
362 |
+
# interval
|
363 |
+
interval = Interval(breaks[0], breaks[1])
|
364 |
+
result = index._maybe_convert_i8(interval)
|
365 |
+
expected = Interval(breaks[0]._value, breaks[1]._value)
|
366 |
+
assert result == expected
|
367 |
+
|
368 |
+
# datetimelike index
|
369 |
+
result = index._maybe_convert_i8(breaks)
|
370 |
+
expected = Index(breaks.asi8)
|
371 |
+
tm.assert_index_equal(result, expected)
|
372 |
+
|
373 |
+
# datetimelike scalar
|
374 |
+
result = index._maybe_convert_i8(breaks[0])
|
375 |
+
expected = breaks[0]._value
|
376 |
+
assert result == expected
|
377 |
+
|
378 |
+
# list-like of datetimelike scalars
|
379 |
+
result = index._maybe_convert_i8(list(breaks))
|
380 |
+
expected = Index(breaks.asi8)
|
381 |
+
tm.assert_index_equal(result, expected)
|
382 |
+
|
383 |
+
@pytest.mark.parametrize(
|
384 |
+
"breaks",
|
385 |
+
[date_range("2018-01-01", periods=5), timedelta_range("0 days", periods=5)],
|
386 |
+
)
|
387 |
+
def test_maybe_convert_i8_nat(self, breaks):
|
388 |
+
# GH 20636
|
389 |
+
index = IntervalIndex.from_breaks(breaks)
|
390 |
+
|
391 |
+
to_convert = breaks._constructor([pd.NaT] * 3).as_unit("ns")
|
392 |
+
expected = Index([np.nan] * 3, dtype=np.float64)
|
393 |
+
result = index._maybe_convert_i8(to_convert)
|
394 |
+
tm.assert_index_equal(result, expected)
|
395 |
+
|
396 |
+
to_convert = to_convert.insert(0, breaks[0])
|
397 |
+
expected = expected.insert(0, float(breaks[0]._value))
|
398 |
+
result = index._maybe_convert_i8(to_convert)
|
399 |
+
tm.assert_index_equal(result, expected)
|
400 |
+
|
401 |
+
@pytest.mark.parametrize(
|
402 |
+
"make_key",
|
403 |
+
[lambda breaks: breaks, list],
|
404 |
+
ids=["lambda", "list"],
|
405 |
+
)
|
406 |
+
def test_maybe_convert_i8_numeric(self, make_key, any_real_numpy_dtype):
|
407 |
+
# GH 20636
|
408 |
+
breaks = np.arange(5, dtype=any_real_numpy_dtype)
|
409 |
+
index = IntervalIndex.from_breaks(breaks)
|
410 |
+
key = make_key(breaks)
|
411 |
+
|
412 |
+
result = index._maybe_convert_i8(key)
|
413 |
+
kind = breaks.dtype.kind
|
414 |
+
expected_dtype = {"i": np.int64, "u": np.uint64, "f": np.float64}[kind]
|
415 |
+
expected = Index(key, dtype=expected_dtype)
|
416 |
+
tm.assert_index_equal(result, expected)
|
417 |
+
|
418 |
+
@pytest.mark.parametrize(
|
419 |
+
"make_key",
|
420 |
+
[
|
421 |
+
IntervalIndex.from_breaks,
|
422 |
+
lambda breaks: Interval(breaks[0], breaks[1]),
|
423 |
+
lambda breaks: breaks[0],
|
424 |
+
],
|
425 |
+
ids=["IntervalIndex", "Interval", "scalar"],
|
426 |
+
)
|
427 |
+
def test_maybe_convert_i8_numeric_identical(self, make_key, any_real_numpy_dtype):
|
428 |
+
# GH 20636
|
429 |
+
breaks = np.arange(5, dtype=any_real_numpy_dtype)
|
430 |
+
index = IntervalIndex.from_breaks(breaks)
|
431 |
+
key = make_key(breaks)
|
432 |
+
|
433 |
+
# test if _maybe_convert_i8 won't change key if an Interval or IntervalIndex
|
434 |
+
result = index._maybe_convert_i8(key)
|
435 |
+
assert result is key
|
436 |
+
|
437 |
+
@pytest.mark.parametrize(
|
438 |
+
"breaks1, breaks2",
|
439 |
+
permutations(
|
440 |
+
[
|
441 |
+
date_range("20180101", periods=4),
|
442 |
+
date_range("20180101", periods=4, tz="US/Eastern"),
|
443 |
+
timedelta_range("0 days", periods=4),
|
444 |
+
],
|
445 |
+
2,
|
446 |
+
),
|
447 |
+
ids=lambda x: str(x.dtype),
|
448 |
+
)
|
449 |
+
@pytest.mark.parametrize(
|
450 |
+
"make_key",
|
451 |
+
[
|
452 |
+
IntervalIndex.from_breaks,
|
453 |
+
lambda breaks: Interval(breaks[0], breaks[1]),
|
454 |
+
lambda breaks: breaks,
|
455 |
+
lambda breaks: breaks[0],
|
456 |
+
list,
|
457 |
+
],
|
458 |
+
ids=["IntervalIndex", "Interval", "Index", "scalar", "list"],
|
459 |
+
)
|
460 |
+
def test_maybe_convert_i8_errors(self, breaks1, breaks2, make_key):
|
461 |
+
# GH 20636
|
462 |
+
index = IntervalIndex.from_breaks(breaks1)
|
463 |
+
key = make_key(breaks2)
|
464 |
+
|
465 |
+
msg = (
|
466 |
+
f"Cannot index an IntervalIndex of subtype {breaks1.dtype} with "
|
467 |
+
f"values of dtype {breaks2.dtype}"
|
468 |
+
)
|
469 |
+
msg = re.escape(msg)
|
470 |
+
with pytest.raises(ValueError, match=msg):
|
471 |
+
index._maybe_convert_i8(key)
|
472 |
+
|
473 |
+
def test_contains_method(self):
|
474 |
+
# can select values that are IN the range of a value
|
475 |
+
i = IntervalIndex.from_arrays([0, 1], [1, 2])
|
476 |
+
|
477 |
+
expected = np.array([False, False], dtype="bool")
|
478 |
+
actual = i.contains(0)
|
479 |
+
tm.assert_numpy_array_equal(actual, expected)
|
480 |
+
actual = i.contains(3)
|
481 |
+
tm.assert_numpy_array_equal(actual, expected)
|
482 |
+
|
483 |
+
expected = np.array([True, False], dtype="bool")
|
484 |
+
actual = i.contains(0.5)
|
485 |
+
tm.assert_numpy_array_equal(actual, expected)
|
486 |
+
actual = i.contains(1)
|
487 |
+
tm.assert_numpy_array_equal(actual, expected)
|
488 |
+
|
489 |
+
# __contains__ not implemented for "interval in interval", follow
|
490 |
+
# that for the contains method for now
|
491 |
+
with pytest.raises(
|
492 |
+
NotImplementedError, match="contains not implemented for two"
|
493 |
+
):
|
494 |
+
i.contains(Interval(0, 1))
|
495 |
+
|
496 |
+
def test_dropna(self, closed):
|
497 |
+
expected = IntervalIndex.from_tuples([(0.0, 1.0), (1.0, 2.0)], closed=closed)
|
498 |
+
|
499 |
+
ii = IntervalIndex.from_tuples([(0, 1), (1, 2), np.nan], closed=closed)
|
500 |
+
result = ii.dropna()
|
501 |
+
tm.assert_index_equal(result, expected)
|
502 |
+
|
503 |
+
ii = IntervalIndex.from_arrays([0, 1, np.nan], [1, 2, np.nan], closed=closed)
|
504 |
+
result = ii.dropna()
|
505 |
+
tm.assert_index_equal(result, expected)
|
506 |
+
|
507 |
+
def test_non_contiguous(self, closed):
|
508 |
+
index = IntervalIndex.from_tuples([(0, 1), (2, 3)], closed=closed)
|
509 |
+
target = [0.5, 1.5, 2.5]
|
510 |
+
actual = index.get_indexer(target)
|
511 |
+
expected = np.array([0, -1, 1], dtype="intp")
|
512 |
+
tm.assert_numpy_array_equal(actual, expected)
|
513 |
+
|
514 |
+
assert 1.5 not in index
|
515 |
+
|
516 |
+
def test_isin(self, closed):
|
517 |
+
index = self.create_index(closed=closed)
|
518 |
+
|
519 |
+
expected = np.array([True] + [False] * (len(index) - 1))
|
520 |
+
result = index.isin(index[:1])
|
521 |
+
tm.assert_numpy_array_equal(result, expected)
|
522 |
+
|
523 |
+
result = index.isin([index[0]])
|
524 |
+
tm.assert_numpy_array_equal(result, expected)
|
525 |
+
|
526 |
+
other = IntervalIndex.from_breaks(np.arange(-2, 10), closed=closed)
|
527 |
+
expected = np.array([True] * (len(index) - 1) + [False])
|
528 |
+
result = index.isin(other)
|
529 |
+
tm.assert_numpy_array_equal(result, expected)
|
530 |
+
|
531 |
+
result = index.isin(other.tolist())
|
532 |
+
tm.assert_numpy_array_equal(result, expected)
|
533 |
+
|
534 |
+
for other_closed in ["right", "left", "both", "neither"]:
|
535 |
+
other = self.create_index(closed=other_closed)
|
536 |
+
expected = np.repeat(closed == other_closed, len(index))
|
537 |
+
result = index.isin(other)
|
538 |
+
tm.assert_numpy_array_equal(result, expected)
|
539 |
+
|
540 |
+
result = index.isin(other.tolist())
|
541 |
+
tm.assert_numpy_array_equal(result, expected)
|
542 |
+
|
543 |
+
def test_comparison(self):
|
544 |
+
actual = Interval(0, 1) < self.index
|
545 |
+
expected = np.array([False, True])
|
546 |
+
tm.assert_numpy_array_equal(actual, expected)
|
547 |
+
|
548 |
+
actual = Interval(0.5, 1.5) < self.index
|
549 |
+
expected = np.array([False, True])
|
550 |
+
tm.assert_numpy_array_equal(actual, expected)
|
551 |
+
actual = self.index > Interval(0.5, 1.5)
|
552 |
+
tm.assert_numpy_array_equal(actual, expected)
|
553 |
+
|
554 |
+
actual = self.index == self.index
|
555 |
+
expected = np.array([True, True])
|
556 |
+
tm.assert_numpy_array_equal(actual, expected)
|
557 |
+
actual = self.index <= self.index
|
558 |
+
tm.assert_numpy_array_equal(actual, expected)
|
559 |
+
actual = self.index >= self.index
|
560 |
+
tm.assert_numpy_array_equal(actual, expected)
|
561 |
+
|
562 |
+
actual = self.index < self.index
|
563 |
+
expected = np.array([False, False])
|
564 |
+
tm.assert_numpy_array_equal(actual, expected)
|
565 |
+
actual = self.index > self.index
|
566 |
+
tm.assert_numpy_array_equal(actual, expected)
|
567 |
+
|
568 |
+
actual = self.index == IntervalIndex.from_breaks([0, 1, 2], "left")
|
569 |
+
tm.assert_numpy_array_equal(actual, expected)
|
570 |
+
|
571 |
+
actual = self.index == self.index.values
|
572 |
+
tm.assert_numpy_array_equal(actual, np.array([True, True]))
|
573 |
+
actual = self.index.values == self.index
|
574 |
+
tm.assert_numpy_array_equal(actual, np.array([True, True]))
|
575 |
+
actual = self.index <= self.index.values
|
576 |
+
tm.assert_numpy_array_equal(actual, np.array([True, True]))
|
577 |
+
actual = self.index != self.index.values
|
578 |
+
tm.assert_numpy_array_equal(actual, np.array([False, False]))
|
579 |
+
actual = self.index > self.index.values
|
580 |
+
tm.assert_numpy_array_equal(actual, np.array([False, False]))
|
581 |
+
actual = self.index.values > self.index
|
582 |
+
tm.assert_numpy_array_equal(actual, np.array([False, False]))
|
583 |
+
|
584 |
+
# invalid comparisons
|
585 |
+
actual = self.index == 0
|
586 |
+
tm.assert_numpy_array_equal(actual, np.array([False, False]))
|
587 |
+
actual = self.index == self.index.left
|
588 |
+
tm.assert_numpy_array_equal(actual, np.array([False, False]))
|
589 |
+
|
590 |
+
msg = "|".join(
|
591 |
+
[
|
592 |
+
"not supported between instances of 'int' and '.*.Interval'",
|
593 |
+
r"Invalid comparison between dtype=interval\[int64, right\] and ",
|
594 |
+
]
|
595 |
+
)
|
596 |
+
with pytest.raises(TypeError, match=msg):
|
597 |
+
self.index > 0
|
598 |
+
with pytest.raises(TypeError, match=msg):
|
599 |
+
self.index <= 0
|
600 |
+
with pytest.raises(TypeError, match=msg):
|
601 |
+
self.index > np.arange(2)
|
602 |
+
|
603 |
+
msg = "Lengths must match to compare"
|
604 |
+
with pytest.raises(ValueError, match=msg):
|
605 |
+
self.index > np.arange(3)
|
606 |
+
|
607 |
+
def test_missing_values(self, closed):
|
608 |
+
idx = Index(
|
609 |
+
[np.nan, Interval(0, 1, closed=closed), Interval(1, 2, closed=closed)]
|
610 |
+
)
|
611 |
+
idx2 = IntervalIndex.from_arrays([np.nan, 0, 1], [np.nan, 1, 2], closed=closed)
|
612 |
+
assert idx.equals(idx2)
|
613 |
+
|
614 |
+
msg = (
|
615 |
+
"missing values must be missing in the same location both left "
|
616 |
+
"and right sides"
|
617 |
+
)
|
618 |
+
with pytest.raises(ValueError, match=msg):
|
619 |
+
IntervalIndex.from_arrays(
|
620 |
+
[np.nan, 0, 1], np.array([0, 1, 2]), closed=closed
|
621 |
+
)
|
622 |
+
|
623 |
+
tm.assert_numpy_array_equal(isna(idx), np.array([True, False, False]))
|
624 |
+
|
625 |
+
def test_sort_values(self, closed):
|
626 |
+
index = self.create_index(closed=closed)
|
627 |
+
|
628 |
+
result = index.sort_values()
|
629 |
+
tm.assert_index_equal(result, index)
|
630 |
+
|
631 |
+
result = index.sort_values(ascending=False)
|
632 |
+
tm.assert_index_equal(result, index[::-1])
|
633 |
+
|
634 |
+
# with nan
|
635 |
+
index = IntervalIndex([Interval(1, 2), np.nan, Interval(0, 1)])
|
636 |
+
|
637 |
+
result = index.sort_values()
|
638 |
+
expected = IntervalIndex([Interval(0, 1), Interval(1, 2), np.nan])
|
639 |
+
tm.assert_index_equal(result, expected)
|
640 |
+
|
641 |
+
result = index.sort_values(ascending=False, na_position="first")
|
642 |
+
expected = IntervalIndex([np.nan, Interval(1, 2), Interval(0, 1)])
|
643 |
+
tm.assert_index_equal(result, expected)
|
644 |
+
|
645 |
+
@pytest.mark.parametrize("tz", [None, "US/Eastern"])
|
646 |
+
def test_datetime(self, tz):
|
647 |
+
start = Timestamp("2000-01-01", tz=tz)
|
648 |
+
dates = date_range(start=start, periods=10)
|
649 |
+
index = IntervalIndex.from_breaks(dates)
|
650 |
+
|
651 |
+
# test mid
|
652 |
+
start = Timestamp("2000-01-01T12:00", tz=tz)
|
653 |
+
expected = date_range(start=start, periods=9)
|
654 |
+
tm.assert_index_equal(index.mid, expected)
|
655 |
+
|
656 |
+
# __contains__ doesn't check individual points
|
657 |
+
assert Timestamp("2000-01-01", tz=tz) not in index
|
658 |
+
assert Timestamp("2000-01-01T12", tz=tz) not in index
|
659 |
+
assert Timestamp("2000-01-02", tz=tz) not in index
|
660 |
+
iv_true = Interval(
|
661 |
+
Timestamp("2000-01-02", tz=tz), Timestamp("2000-01-03", tz=tz)
|
662 |
+
)
|
663 |
+
iv_false = Interval(
|
664 |
+
Timestamp("1999-12-31", tz=tz), Timestamp("2000-01-01", tz=tz)
|
665 |
+
)
|
666 |
+
assert iv_true in index
|
667 |
+
assert iv_false not in index
|
668 |
+
|
669 |
+
# .contains does check individual points
|
670 |
+
assert not index.contains(Timestamp("2000-01-01", tz=tz)).any()
|
671 |
+
assert index.contains(Timestamp("2000-01-01T12", tz=tz)).any()
|
672 |
+
assert index.contains(Timestamp("2000-01-02", tz=tz)).any()
|
673 |
+
|
674 |
+
# test get_indexer
|
675 |
+
start = Timestamp("1999-12-31T12:00", tz=tz)
|
676 |
+
target = date_range(start=start, periods=7, freq="12h")
|
677 |
+
actual = index.get_indexer(target)
|
678 |
+
expected = np.array([-1, -1, 0, 0, 1, 1, 2], dtype="intp")
|
679 |
+
tm.assert_numpy_array_equal(actual, expected)
|
680 |
+
|
681 |
+
start = Timestamp("2000-01-08T18:00", tz=tz)
|
682 |
+
target = date_range(start=start, periods=7, freq="6h")
|
683 |
+
actual = index.get_indexer(target)
|
684 |
+
expected = np.array([7, 7, 8, 8, 8, 8, -1], dtype="intp")
|
685 |
+
tm.assert_numpy_array_equal(actual, expected)
|
686 |
+
|
687 |
+
def test_append(self, closed):
|
688 |
+
index1 = IntervalIndex.from_arrays([0, 1], [1, 2], closed=closed)
|
689 |
+
index2 = IntervalIndex.from_arrays([1, 2], [2, 3], closed=closed)
|
690 |
+
|
691 |
+
result = index1.append(index2)
|
692 |
+
expected = IntervalIndex.from_arrays([0, 1, 1, 2], [1, 2, 2, 3], closed=closed)
|
693 |
+
tm.assert_index_equal(result, expected)
|
694 |
+
|
695 |
+
result = index1.append([index1, index2])
|
696 |
+
expected = IntervalIndex.from_arrays(
|
697 |
+
[0, 1, 0, 1, 1, 2], [1, 2, 1, 2, 2, 3], closed=closed
|
698 |
+
)
|
699 |
+
tm.assert_index_equal(result, expected)
|
700 |
+
|
701 |
+
for other_closed in {"left", "right", "both", "neither"} - {closed}:
|
702 |
+
index_other_closed = IntervalIndex.from_arrays(
|
703 |
+
[0, 1], [1, 2], closed=other_closed
|
704 |
+
)
|
705 |
+
result = index1.append(index_other_closed)
|
706 |
+
expected = index1.astype(object).append(index_other_closed.astype(object))
|
707 |
+
tm.assert_index_equal(result, expected)
|
708 |
+
|
709 |
+
def test_is_non_overlapping_monotonic(self, closed):
|
710 |
+
# Should be True in all cases
|
711 |
+
tpls = [(0, 1), (2, 3), (4, 5), (6, 7)]
|
712 |
+
idx = IntervalIndex.from_tuples(tpls, closed=closed)
|
713 |
+
assert idx.is_non_overlapping_monotonic is True
|
714 |
+
|
715 |
+
idx = IntervalIndex.from_tuples(tpls[::-1], closed=closed)
|
716 |
+
assert idx.is_non_overlapping_monotonic is True
|
717 |
+
|
718 |
+
# Should be False in all cases (overlapping)
|
719 |
+
tpls = [(0, 2), (1, 3), (4, 5), (6, 7)]
|
720 |
+
idx = IntervalIndex.from_tuples(tpls, closed=closed)
|
721 |
+
assert idx.is_non_overlapping_monotonic is False
|
722 |
+
|
723 |
+
idx = IntervalIndex.from_tuples(tpls[::-1], closed=closed)
|
724 |
+
assert idx.is_non_overlapping_monotonic is False
|
725 |
+
|
726 |
+
# Should be False in all cases (non-monotonic)
|
727 |
+
tpls = [(0, 1), (2, 3), (6, 7), (4, 5)]
|
728 |
+
idx = IntervalIndex.from_tuples(tpls, closed=closed)
|
729 |
+
assert idx.is_non_overlapping_monotonic is False
|
730 |
+
|
731 |
+
idx = IntervalIndex.from_tuples(tpls[::-1], closed=closed)
|
732 |
+
assert idx.is_non_overlapping_monotonic is False
|
733 |
+
|
734 |
+
# Should be False for closed='both', otherwise True (GH16560)
|
735 |
+
if closed == "both":
|
736 |
+
idx = IntervalIndex.from_breaks(range(4), closed=closed)
|
737 |
+
assert idx.is_non_overlapping_monotonic is False
|
738 |
+
else:
|
739 |
+
idx = IntervalIndex.from_breaks(range(4), closed=closed)
|
740 |
+
assert idx.is_non_overlapping_monotonic is True
|
741 |
+
|
742 |
+
@pytest.mark.parametrize(
|
743 |
+
"start, shift, na_value",
|
744 |
+
[
|
745 |
+
(0, 1, np.nan),
|
746 |
+
(Timestamp("2018-01-01"), Timedelta("1 day"), pd.NaT),
|
747 |
+
(Timedelta("0 days"), Timedelta("1 day"), pd.NaT),
|
748 |
+
],
|
749 |
+
)
|
750 |
+
def test_is_overlapping(self, start, shift, na_value, closed):
|
751 |
+
# GH 23309
|
752 |
+
# see test_interval_tree.py for extensive tests; interface tests here
|
753 |
+
|
754 |
+
# non-overlapping
|
755 |
+
tuples = [(start + n * shift, start + (n + 1) * shift) for n in (0, 2, 4)]
|
756 |
+
index = IntervalIndex.from_tuples(tuples, closed=closed)
|
757 |
+
assert index.is_overlapping is False
|
758 |
+
|
759 |
+
# non-overlapping with NA
|
760 |
+
tuples = [(na_value, na_value)] + tuples + [(na_value, na_value)]
|
761 |
+
index = IntervalIndex.from_tuples(tuples, closed=closed)
|
762 |
+
assert index.is_overlapping is False
|
763 |
+
|
764 |
+
# overlapping
|
765 |
+
tuples = [(start + n * shift, start + (n + 2) * shift) for n in range(3)]
|
766 |
+
index = IntervalIndex.from_tuples(tuples, closed=closed)
|
767 |
+
assert index.is_overlapping is True
|
768 |
+
|
769 |
+
# overlapping with NA
|
770 |
+
tuples = [(na_value, na_value)] + tuples + [(na_value, na_value)]
|
771 |
+
index = IntervalIndex.from_tuples(tuples, closed=closed)
|
772 |
+
assert index.is_overlapping is True
|
773 |
+
|
774 |
+
# common endpoints
|
775 |
+
tuples = [(start + n * shift, start + (n + 1) * shift) for n in range(3)]
|
776 |
+
index = IntervalIndex.from_tuples(tuples, closed=closed)
|
777 |
+
result = index.is_overlapping
|
778 |
+
expected = closed == "both"
|
779 |
+
assert result is expected
|
780 |
+
|
781 |
+
# common endpoints with NA
|
782 |
+
tuples = [(na_value, na_value)] + tuples + [(na_value, na_value)]
|
783 |
+
index = IntervalIndex.from_tuples(tuples, closed=closed)
|
784 |
+
result = index.is_overlapping
|
785 |
+
assert result is expected
|
786 |
+
|
787 |
+
# intervals with duplicate left values
|
788 |
+
a = [10, 15, 20, 25, 30, 35, 40, 45, 45, 50, 55, 60, 65, 70, 75, 80, 85]
|
789 |
+
b = [15, 20, 25, 30, 35, 40, 45, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90]
|
790 |
+
index = IntervalIndex.from_arrays(a, b, closed="right")
|
791 |
+
result = index.is_overlapping
|
792 |
+
assert result is False
|
793 |
+
|
794 |
+
@pytest.mark.parametrize(
|
795 |
+
"tuples",
|
796 |
+
[
|
797 |
+
list(zip(range(10), range(1, 11))),
|
798 |
+
list(
|
799 |
+
zip(
|
800 |
+
date_range("20170101", periods=10),
|
801 |
+
date_range("20170101", periods=10),
|
802 |
+
)
|
803 |
+
),
|
804 |
+
list(
|
805 |
+
zip(
|
806 |
+
timedelta_range("0 days", periods=10),
|
807 |
+
timedelta_range("1 day", periods=10),
|
808 |
+
)
|
809 |
+
),
|
810 |
+
],
|
811 |
+
)
|
812 |
+
def test_to_tuples(self, tuples):
|
813 |
+
# GH 18756
|
814 |
+
idx = IntervalIndex.from_tuples(tuples)
|
815 |
+
result = idx.to_tuples()
|
816 |
+
expected = Index(com.asarray_tuplesafe(tuples))
|
817 |
+
tm.assert_index_equal(result, expected)
|
818 |
+
|
819 |
+
@pytest.mark.parametrize(
|
820 |
+
"tuples",
|
821 |
+
[
|
822 |
+
list(zip(range(10), range(1, 11))) + [np.nan],
|
823 |
+
list(
|
824 |
+
zip(
|
825 |
+
date_range("20170101", periods=10),
|
826 |
+
date_range("20170101", periods=10),
|
827 |
+
)
|
828 |
+
)
|
829 |
+
+ [np.nan],
|
830 |
+
list(
|
831 |
+
zip(
|
832 |
+
timedelta_range("0 days", periods=10),
|
833 |
+
timedelta_range("1 day", periods=10),
|
834 |
+
)
|
835 |
+
)
|
836 |
+
+ [np.nan],
|
837 |
+
],
|
838 |
+
)
|
839 |
+
@pytest.mark.parametrize("na_tuple", [True, False])
|
840 |
+
def test_to_tuples_na(self, tuples, na_tuple):
|
841 |
+
# GH 18756
|
842 |
+
idx = IntervalIndex.from_tuples(tuples)
|
843 |
+
result = idx.to_tuples(na_tuple=na_tuple)
|
844 |
+
|
845 |
+
# check the non-NA portion
|
846 |
+
expected_notna = Index(com.asarray_tuplesafe(tuples[:-1]))
|
847 |
+
result_notna = result[:-1]
|
848 |
+
tm.assert_index_equal(result_notna, expected_notna)
|
849 |
+
|
850 |
+
# check the NA portion
|
851 |
+
result_na = result[-1]
|
852 |
+
if na_tuple:
|
853 |
+
assert isinstance(result_na, tuple)
|
854 |
+
assert len(result_na) == 2
|
855 |
+
assert all(isna(x) for x in result_na)
|
856 |
+
else:
|
857 |
+
assert isna(result_na)
|
858 |
+
|
859 |
+
def test_nbytes(self):
|
860 |
+
# GH 19209
|
861 |
+
left = np.arange(0, 4, dtype="i8")
|
862 |
+
right = np.arange(1, 5, dtype="i8")
|
863 |
+
|
864 |
+
result = IntervalIndex.from_arrays(left, right).nbytes
|
865 |
+
expected = 64 # 4 * 8 * 2
|
866 |
+
assert result == expected
|
867 |
+
|
868 |
+
@pytest.mark.parametrize("new_closed", ["left", "right", "both", "neither"])
|
869 |
+
def test_set_closed(self, name, closed, new_closed):
|
870 |
+
# GH 21670
|
871 |
+
index = interval_range(0, 5, closed=closed, name=name)
|
872 |
+
result = index.set_closed(new_closed)
|
873 |
+
expected = interval_range(0, 5, closed=new_closed, name=name)
|
874 |
+
tm.assert_index_equal(result, expected)
|
875 |
+
|
876 |
+
@pytest.mark.parametrize("bad_closed", ["foo", 10, "LEFT", True, False])
|
877 |
+
def test_set_closed_errors(self, bad_closed):
|
878 |
+
# GH 21670
|
879 |
+
index = interval_range(0, 5)
|
880 |
+
msg = f"invalid option for 'closed': {bad_closed}"
|
881 |
+
with pytest.raises(ValueError, match=msg):
|
882 |
+
index.set_closed(bad_closed)
|
883 |
+
|
884 |
+
def test_is_all_dates(self):
|
885 |
+
# GH 23576
|
886 |
+
year_2017 = Interval(
|
887 |
+
Timestamp("2017-01-01 00:00:00"), Timestamp("2018-01-01 00:00:00")
|
888 |
+
)
|
889 |
+
year_2017_index = IntervalIndex([year_2017])
|
890 |
+
assert not year_2017_index._is_all_dates
|
891 |
+
|
892 |
+
|
893 |
+
def test_dir():
|
894 |
+
# GH#27571 dir(interval_index) should not raise
|
895 |
+
index = IntervalIndex.from_arrays([0, 1], [1, 2])
|
896 |
+
result = dir(index)
|
897 |
+
assert "str" not in result
|
898 |
+
|
899 |
+
|
900 |
+
def test_searchsorted_different_argument_classes(listlike_box):
|
901 |
+
# https://github.com/pandas-dev/pandas/issues/32762
|
902 |
+
values = IntervalIndex([Interval(0, 1), Interval(1, 2)])
|
903 |
+
result = values.searchsorted(listlike_box(values))
|
904 |
+
expected = np.array([0, 1], dtype=result.dtype)
|
905 |
+
tm.assert_numpy_array_equal(result, expected)
|
906 |
+
|
907 |
+
result = values._data.searchsorted(listlike_box(values))
|
908 |
+
tm.assert_numpy_array_equal(result, expected)
|
909 |
+
|
910 |
+
|
911 |
+
@pytest.mark.parametrize(
|
912 |
+
"arg", [[1, 2], ["a", "b"], [Timestamp("2020-01-01", tz="Europe/London")] * 2]
|
913 |
+
)
|
914 |
+
def test_searchsorted_invalid_argument(arg):
|
915 |
+
values = IntervalIndex([Interval(0, 1), Interval(1, 2)])
|
916 |
+
msg = "'<' not supported between instances of 'pandas._libs.interval.Interval' and "
|
917 |
+
with pytest.raises(TypeError, match=msg):
|
918 |
+
values.searchsorted(arg)
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/test_interval_range.py
ADDED
@@ -0,0 +1,369 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from datetime import timedelta
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
import pytest
|
5 |
+
|
6 |
+
from pandas.core.dtypes.common import is_integer
|
7 |
+
|
8 |
+
from pandas import (
|
9 |
+
DateOffset,
|
10 |
+
Interval,
|
11 |
+
IntervalIndex,
|
12 |
+
Timedelta,
|
13 |
+
Timestamp,
|
14 |
+
date_range,
|
15 |
+
interval_range,
|
16 |
+
timedelta_range,
|
17 |
+
)
|
18 |
+
import pandas._testing as tm
|
19 |
+
|
20 |
+
from pandas.tseries.offsets import Day
|
21 |
+
|
22 |
+
|
23 |
+
@pytest.fixture(params=[None, "foo"])
|
24 |
+
def name(request):
|
25 |
+
return request.param
|
26 |
+
|
27 |
+
|
28 |
+
class TestIntervalRange:
|
29 |
+
@pytest.mark.parametrize("freq, periods", [(1, 100), (2.5, 40), (5, 20), (25, 4)])
|
30 |
+
def test_constructor_numeric(self, closed, name, freq, periods):
|
31 |
+
start, end = 0, 100
|
32 |
+
breaks = np.arange(101, step=freq)
|
33 |
+
expected = IntervalIndex.from_breaks(breaks, name=name, closed=closed)
|
34 |
+
|
35 |
+
# defined from start/end/freq
|
36 |
+
result = interval_range(
|
37 |
+
start=start, end=end, freq=freq, name=name, closed=closed
|
38 |
+
)
|
39 |
+
tm.assert_index_equal(result, expected)
|
40 |
+
|
41 |
+
# defined from start/periods/freq
|
42 |
+
result = interval_range(
|
43 |
+
start=start, periods=periods, freq=freq, name=name, closed=closed
|
44 |
+
)
|
45 |
+
tm.assert_index_equal(result, expected)
|
46 |
+
|
47 |
+
# defined from end/periods/freq
|
48 |
+
result = interval_range(
|
49 |
+
end=end, periods=periods, freq=freq, name=name, closed=closed
|
50 |
+
)
|
51 |
+
tm.assert_index_equal(result, expected)
|
52 |
+
|
53 |
+
# GH 20976: linspace behavior defined from start/end/periods
|
54 |
+
result = interval_range(
|
55 |
+
start=start, end=end, periods=periods, name=name, closed=closed
|
56 |
+
)
|
57 |
+
tm.assert_index_equal(result, expected)
|
58 |
+
|
59 |
+
@pytest.mark.parametrize("tz", [None, "US/Eastern"])
|
60 |
+
@pytest.mark.parametrize(
|
61 |
+
"freq, periods", [("D", 364), ("2D", 182), ("22D18h", 16), ("ME", 11)]
|
62 |
+
)
|
63 |
+
def test_constructor_timestamp(self, closed, name, freq, periods, tz):
|
64 |
+
start, end = Timestamp("20180101", tz=tz), Timestamp("20181231", tz=tz)
|
65 |
+
breaks = date_range(start=start, end=end, freq=freq)
|
66 |
+
expected = IntervalIndex.from_breaks(breaks, name=name, closed=closed)
|
67 |
+
|
68 |
+
# defined from start/end/freq
|
69 |
+
result = interval_range(
|
70 |
+
start=start, end=end, freq=freq, name=name, closed=closed
|
71 |
+
)
|
72 |
+
tm.assert_index_equal(result, expected)
|
73 |
+
|
74 |
+
# defined from start/periods/freq
|
75 |
+
result = interval_range(
|
76 |
+
start=start, periods=periods, freq=freq, name=name, closed=closed
|
77 |
+
)
|
78 |
+
tm.assert_index_equal(result, expected)
|
79 |
+
|
80 |
+
# defined from end/periods/freq
|
81 |
+
result = interval_range(
|
82 |
+
end=end, periods=periods, freq=freq, name=name, closed=closed
|
83 |
+
)
|
84 |
+
tm.assert_index_equal(result, expected)
|
85 |
+
|
86 |
+
# GH 20976: linspace behavior defined from start/end/periods
|
87 |
+
if not breaks.freq.n == 1 and tz is None:
|
88 |
+
result = interval_range(
|
89 |
+
start=start, end=end, periods=periods, name=name, closed=closed
|
90 |
+
)
|
91 |
+
tm.assert_index_equal(result, expected)
|
92 |
+
|
93 |
+
@pytest.mark.parametrize(
|
94 |
+
"freq, periods", [("D", 100), ("2D12h", 40), ("5D", 20), ("25D", 4)]
|
95 |
+
)
|
96 |
+
def test_constructor_timedelta(self, closed, name, freq, periods):
|
97 |
+
start, end = Timedelta("0 days"), Timedelta("100 days")
|
98 |
+
breaks = timedelta_range(start=start, end=end, freq=freq)
|
99 |
+
expected = IntervalIndex.from_breaks(breaks, name=name, closed=closed)
|
100 |
+
|
101 |
+
# defined from start/end/freq
|
102 |
+
result = interval_range(
|
103 |
+
start=start, end=end, freq=freq, name=name, closed=closed
|
104 |
+
)
|
105 |
+
tm.assert_index_equal(result, expected)
|
106 |
+
|
107 |
+
# defined from start/periods/freq
|
108 |
+
result = interval_range(
|
109 |
+
start=start, periods=periods, freq=freq, name=name, closed=closed
|
110 |
+
)
|
111 |
+
tm.assert_index_equal(result, expected)
|
112 |
+
|
113 |
+
# defined from end/periods/freq
|
114 |
+
result = interval_range(
|
115 |
+
end=end, periods=periods, freq=freq, name=name, closed=closed
|
116 |
+
)
|
117 |
+
tm.assert_index_equal(result, expected)
|
118 |
+
|
119 |
+
# GH 20976: linspace behavior defined from start/end/periods
|
120 |
+
result = interval_range(
|
121 |
+
start=start, end=end, periods=periods, name=name, closed=closed
|
122 |
+
)
|
123 |
+
tm.assert_index_equal(result, expected)
|
124 |
+
|
125 |
+
@pytest.mark.parametrize(
|
126 |
+
"start, end, freq, expected_endpoint",
|
127 |
+
[
|
128 |
+
(0, 10, 3, 9),
|
129 |
+
(0, 10, 1.5, 9),
|
130 |
+
(0.5, 10, 3, 9.5),
|
131 |
+
(Timedelta("0D"), Timedelta("10D"), "2D4h", Timedelta("8D16h")),
|
132 |
+
(
|
133 |
+
Timestamp("2018-01-01"),
|
134 |
+
Timestamp("2018-02-09"),
|
135 |
+
"MS",
|
136 |
+
Timestamp("2018-02-01"),
|
137 |
+
),
|
138 |
+
(
|
139 |
+
Timestamp("2018-01-01", tz="US/Eastern"),
|
140 |
+
Timestamp("2018-01-20", tz="US/Eastern"),
|
141 |
+
"5D12h",
|
142 |
+
Timestamp("2018-01-17 12:00:00", tz="US/Eastern"),
|
143 |
+
),
|
144 |
+
],
|
145 |
+
)
|
146 |
+
def test_early_truncation(self, start, end, freq, expected_endpoint):
|
147 |
+
# index truncates early if freq causes end to be skipped
|
148 |
+
result = interval_range(start=start, end=end, freq=freq)
|
149 |
+
result_endpoint = result.right[-1]
|
150 |
+
assert result_endpoint == expected_endpoint
|
151 |
+
|
152 |
+
@pytest.mark.parametrize(
|
153 |
+
"start, end, freq",
|
154 |
+
[(0.5, None, None), (None, 4.5, None), (0.5, None, 1.5), (None, 6.5, 1.5)],
|
155 |
+
)
|
156 |
+
def test_no_invalid_float_truncation(self, start, end, freq):
|
157 |
+
# GH 21161
|
158 |
+
if freq is None:
|
159 |
+
breaks = [0.5, 1.5, 2.5, 3.5, 4.5]
|
160 |
+
else:
|
161 |
+
breaks = [0.5, 2.0, 3.5, 5.0, 6.5]
|
162 |
+
expected = IntervalIndex.from_breaks(breaks)
|
163 |
+
|
164 |
+
result = interval_range(start=start, end=end, periods=4, freq=freq)
|
165 |
+
tm.assert_index_equal(result, expected)
|
166 |
+
|
167 |
+
@pytest.mark.parametrize(
|
168 |
+
"start, mid, end",
|
169 |
+
[
|
170 |
+
(
|
171 |
+
Timestamp("2018-03-10", tz="US/Eastern"),
|
172 |
+
Timestamp("2018-03-10 23:30:00", tz="US/Eastern"),
|
173 |
+
Timestamp("2018-03-12", tz="US/Eastern"),
|
174 |
+
),
|
175 |
+
(
|
176 |
+
Timestamp("2018-11-03", tz="US/Eastern"),
|
177 |
+
Timestamp("2018-11-04 00:30:00", tz="US/Eastern"),
|
178 |
+
Timestamp("2018-11-05", tz="US/Eastern"),
|
179 |
+
),
|
180 |
+
],
|
181 |
+
)
|
182 |
+
def test_linspace_dst_transition(self, start, mid, end):
|
183 |
+
# GH 20976: linspace behavior defined from start/end/periods
|
184 |
+
# accounts for the hour gained/lost during DST transition
|
185 |
+
start = start.as_unit("ns")
|
186 |
+
mid = mid.as_unit("ns")
|
187 |
+
end = end.as_unit("ns")
|
188 |
+
result = interval_range(start=start, end=end, periods=2)
|
189 |
+
expected = IntervalIndex.from_breaks([start, mid, end])
|
190 |
+
tm.assert_index_equal(result, expected)
|
191 |
+
|
192 |
+
@pytest.mark.parametrize("freq", [2, 2.0])
|
193 |
+
@pytest.mark.parametrize("end", [10, 10.0])
|
194 |
+
@pytest.mark.parametrize("start", [0, 0.0])
|
195 |
+
def test_float_subtype(self, start, end, freq):
|
196 |
+
# Has float subtype if any of start/end/freq are float, even if all
|
197 |
+
# resulting endpoints can safely be upcast to integers
|
198 |
+
|
199 |
+
# defined from start/end/freq
|
200 |
+
index = interval_range(start=start, end=end, freq=freq)
|
201 |
+
result = index.dtype.subtype
|
202 |
+
expected = "int64" if is_integer(start + end + freq) else "float64"
|
203 |
+
assert result == expected
|
204 |
+
|
205 |
+
# defined from start/periods/freq
|
206 |
+
index = interval_range(start=start, periods=5, freq=freq)
|
207 |
+
result = index.dtype.subtype
|
208 |
+
expected = "int64" if is_integer(start + freq) else "float64"
|
209 |
+
assert result == expected
|
210 |
+
|
211 |
+
# defined from end/periods/freq
|
212 |
+
index = interval_range(end=end, periods=5, freq=freq)
|
213 |
+
result = index.dtype.subtype
|
214 |
+
expected = "int64" if is_integer(end + freq) else "float64"
|
215 |
+
assert result == expected
|
216 |
+
|
217 |
+
# GH 20976: linspace behavior defined from start/end/periods
|
218 |
+
index = interval_range(start=start, end=end, periods=5)
|
219 |
+
result = index.dtype.subtype
|
220 |
+
expected = "int64" if is_integer(start + end) else "float64"
|
221 |
+
assert result == expected
|
222 |
+
|
223 |
+
def test_interval_range_fractional_period(self):
|
224 |
+
# float value for periods
|
225 |
+
expected = interval_range(start=0, periods=10)
|
226 |
+
msg = "Non-integer 'periods' in pd.date_range, .* pd.interval_range"
|
227 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
228 |
+
result = interval_range(start=0, periods=10.5)
|
229 |
+
tm.assert_index_equal(result, expected)
|
230 |
+
|
231 |
+
def test_constructor_coverage(self):
|
232 |
+
# equivalent timestamp-like start/end
|
233 |
+
start, end = Timestamp("2017-01-01"), Timestamp("2017-01-15")
|
234 |
+
expected = interval_range(start=start, end=end)
|
235 |
+
|
236 |
+
result = interval_range(start=start.to_pydatetime(), end=end.to_pydatetime())
|
237 |
+
tm.assert_index_equal(result, expected)
|
238 |
+
|
239 |
+
result = interval_range(start=start.asm8, end=end.asm8)
|
240 |
+
tm.assert_index_equal(result, expected)
|
241 |
+
|
242 |
+
# equivalent freq with timestamp
|
243 |
+
equiv_freq = [
|
244 |
+
"D",
|
245 |
+
Day(),
|
246 |
+
Timedelta(days=1),
|
247 |
+
timedelta(days=1),
|
248 |
+
DateOffset(days=1),
|
249 |
+
]
|
250 |
+
for freq in equiv_freq:
|
251 |
+
result = interval_range(start=start, end=end, freq=freq)
|
252 |
+
tm.assert_index_equal(result, expected)
|
253 |
+
|
254 |
+
# equivalent timedelta-like start/end
|
255 |
+
start, end = Timedelta(days=1), Timedelta(days=10)
|
256 |
+
expected = interval_range(start=start, end=end)
|
257 |
+
|
258 |
+
result = interval_range(start=start.to_pytimedelta(), end=end.to_pytimedelta())
|
259 |
+
tm.assert_index_equal(result, expected)
|
260 |
+
|
261 |
+
result = interval_range(start=start.asm8, end=end.asm8)
|
262 |
+
tm.assert_index_equal(result, expected)
|
263 |
+
|
264 |
+
# equivalent freq with timedelta
|
265 |
+
equiv_freq = ["D", Day(), Timedelta(days=1), timedelta(days=1)]
|
266 |
+
for freq in equiv_freq:
|
267 |
+
result = interval_range(start=start, end=end, freq=freq)
|
268 |
+
tm.assert_index_equal(result, expected)
|
269 |
+
|
270 |
+
def test_errors(self):
|
271 |
+
# not enough params
|
272 |
+
msg = (
|
273 |
+
"Of the four parameters: start, end, periods, and freq, "
|
274 |
+
"exactly three must be specified"
|
275 |
+
)
|
276 |
+
|
277 |
+
with pytest.raises(ValueError, match=msg):
|
278 |
+
interval_range(start=0)
|
279 |
+
|
280 |
+
with pytest.raises(ValueError, match=msg):
|
281 |
+
interval_range(end=5)
|
282 |
+
|
283 |
+
with pytest.raises(ValueError, match=msg):
|
284 |
+
interval_range(periods=2)
|
285 |
+
|
286 |
+
with pytest.raises(ValueError, match=msg):
|
287 |
+
interval_range()
|
288 |
+
|
289 |
+
# too many params
|
290 |
+
with pytest.raises(ValueError, match=msg):
|
291 |
+
interval_range(start=0, end=5, periods=6, freq=1.5)
|
292 |
+
|
293 |
+
# mixed units
|
294 |
+
msg = "start, end, freq need to be type compatible"
|
295 |
+
with pytest.raises(TypeError, match=msg):
|
296 |
+
interval_range(start=0, end=Timestamp("20130101"), freq=2)
|
297 |
+
|
298 |
+
with pytest.raises(TypeError, match=msg):
|
299 |
+
interval_range(start=0, end=Timedelta("1 day"), freq=2)
|
300 |
+
|
301 |
+
with pytest.raises(TypeError, match=msg):
|
302 |
+
interval_range(start=0, end=10, freq="D")
|
303 |
+
|
304 |
+
with pytest.raises(TypeError, match=msg):
|
305 |
+
interval_range(start=Timestamp("20130101"), end=10, freq="D")
|
306 |
+
|
307 |
+
with pytest.raises(TypeError, match=msg):
|
308 |
+
interval_range(
|
309 |
+
start=Timestamp("20130101"), end=Timedelta("1 day"), freq="D"
|
310 |
+
)
|
311 |
+
|
312 |
+
with pytest.raises(TypeError, match=msg):
|
313 |
+
interval_range(
|
314 |
+
start=Timestamp("20130101"), end=Timestamp("20130110"), freq=2
|
315 |
+
)
|
316 |
+
|
317 |
+
with pytest.raises(TypeError, match=msg):
|
318 |
+
interval_range(start=Timedelta("1 day"), end=10, freq="D")
|
319 |
+
|
320 |
+
with pytest.raises(TypeError, match=msg):
|
321 |
+
interval_range(
|
322 |
+
start=Timedelta("1 day"), end=Timestamp("20130110"), freq="D"
|
323 |
+
)
|
324 |
+
|
325 |
+
with pytest.raises(TypeError, match=msg):
|
326 |
+
interval_range(start=Timedelta("1 day"), end=Timedelta("10 days"), freq=2)
|
327 |
+
|
328 |
+
# invalid periods
|
329 |
+
msg = "periods must be a number, got foo"
|
330 |
+
with pytest.raises(TypeError, match=msg):
|
331 |
+
interval_range(start=0, periods="foo")
|
332 |
+
|
333 |
+
# invalid start
|
334 |
+
msg = "start must be numeric or datetime-like, got foo"
|
335 |
+
with pytest.raises(ValueError, match=msg):
|
336 |
+
interval_range(start="foo", periods=10)
|
337 |
+
|
338 |
+
# invalid end
|
339 |
+
msg = r"end must be numeric or datetime-like, got \(0, 1\]"
|
340 |
+
with pytest.raises(ValueError, match=msg):
|
341 |
+
interval_range(end=Interval(0, 1), periods=10)
|
342 |
+
|
343 |
+
# invalid freq for datetime-like
|
344 |
+
msg = "freq must be numeric or convertible to DateOffset, got foo"
|
345 |
+
with pytest.raises(ValueError, match=msg):
|
346 |
+
interval_range(start=0, end=10, freq="foo")
|
347 |
+
|
348 |
+
with pytest.raises(ValueError, match=msg):
|
349 |
+
interval_range(start=Timestamp("20130101"), periods=10, freq="foo")
|
350 |
+
|
351 |
+
with pytest.raises(ValueError, match=msg):
|
352 |
+
interval_range(end=Timedelta("1 day"), periods=10, freq="foo")
|
353 |
+
|
354 |
+
# mixed tz
|
355 |
+
start = Timestamp("2017-01-01", tz="US/Eastern")
|
356 |
+
end = Timestamp("2017-01-07", tz="US/Pacific")
|
357 |
+
msg = "Start and end cannot both be tz-aware with different timezones"
|
358 |
+
with pytest.raises(TypeError, match=msg):
|
359 |
+
interval_range(start=start, end=end)
|
360 |
+
|
361 |
+
def test_float_freq(self):
|
362 |
+
# GH 54477
|
363 |
+
result = interval_range(0, 1, freq=0.1)
|
364 |
+
expected = IntervalIndex.from_breaks([0 + 0.1 * n for n in range(11)])
|
365 |
+
tm.assert_index_equal(result, expected)
|
366 |
+
|
367 |
+
result = interval_range(0, 1, freq=0.6)
|
368 |
+
expected = IntervalIndex.from_breaks([0, 0.6])
|
369 |
+
tm.assert_index_equal(result, expected)
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/test_interval_tree.py
ADDED
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from itertools import permutations
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
import pytest
|
5 |
+
|
6 |
+
from pandas._libs.interval import IntervalTree
|
7 |
+
from pandas.compat import IS64
|
8 |
+
|
9 |
+
import pandas._testing as tm
|
10 |
+
|
11 |
+
|
12 |
+
def skipif_32bit(param):
|
13 |
+
"""
|
14 |
+
Skip parameters in a parametrize on 32bit systems. Specifically used
|
15 |
+
here to skip leaf_size parameters related to GH 23440.
|
16 |
+
"""
|
17 |
+
marks = pytest.mark.skipif(not IS64, reason="GH 23440: int type mismatch on 32bit")
|
18 |
+
return pytest.param(param, marks=marks)
|
19 |
+
|
20 |
+
|
21 |
+
@pytest.fixture(params=["int64", "float64", "uint64"])
|
22 |
+
def dtype(request):
|
23 |
+
return request.param
|
24 |
+
|
25 |
+
|
26 |
+
@pytest.fixture(params=[skipif_32bit(1), skipif_32bit(2), 10])
|
27 |
+
def leaf_size(request):
|
28 |
+
"""
|
29 |
+
Fixture to specify IntervalTree leaf_size parameter; to be used with the
|
30 |
+
tree fixture.
|
31 |
+
"""
|
32 |
+
return request.param
|
33 |
+
|
34 |
+
|
35 |
+
@pytest.fixture(
|
36 |
+
params=[
|
37 |
+
np.arange(5, dtype="int64"),
|
38 |
+
np.arange(5, dtype="uint64"),
|
39 |
+
np.arange(5, dtype="float64"),
|
40 |
+
np.array([0, 1, 2, 3, 4, np.nan], dtype="float64"),
|
41 |
+
]
|
42 |
+
)
|
43 |
+
def tree(request, leaf_size):
|
44 |
+
left = request.param
|
45 |
+
return IntervalTree(left, left + 2, leaf_size=leaf_size)
|
46 |
+
|
47 |
+
|
48 |
+
class TestIntervalTree:
|
49 |
+
def test_get_indexer(self, tree):
|
50 |
+
result = tree.get_indexer(np.array([1.0, 5.5, 6.5]))
|
51 |
+
expected = np.array([0, 4, -1], dtype="intp")
|
52 |
+
tm.assert_numpy_array_equal(result, expected)
|
53 |
+
|
54 |
+
with pytest.raises(
|
55 |
+
KeyError, match="'indexer does not intersect a unique set of intervals'"
|
56 |
+
):
|
57 |
+
tree.get_indexer(np.array([3.0]))
|
58 |
+
|
59 |
+
@pytest.mark.parametrize(
|
60 |
+
"dtype, target_value, target_dtype",
|
61 |
+
[("int64", 2**63 + 1, "uint64"), ("uint64", -1, "int64")],
|
62 |
+
)
|
63 |
+
def test_get_indexer_overflow(self, dtype, target_value, target_dtype):
|
64 |
+
left, right = np.array([0, 1], dtype=dtype), np.array([1, 2], dtype=dtype)
|
65 |
+
tree = IntervalTree(left, right)
|
66 |
+
|
67 |
+
result = tree.get_indexer(np.array([target_value], dtype=target_dtype))
|
68 |
+
expected = np.array([-1], dtype="intp")
|
69 |
+
tm.assert_numpy_array_equal(result, expected)
|
70 |
+
|
71 |
+
def test_get_indexer_non_unique(self, tree):
|
72 |
+
indexer, missing = tree.get_indexer_non_unique(np.array([1.0, 2.0, 6.5]))
|
73 |
+
|
74 |
+
result = indexer[:1]
|
75 |
+
expected = np.array([0], dtype="intp")
|
76 |
+
tm.assert_numpy_array_equal(result, expected)
|
77 |
+
|
78 |
+
result = np.sort(indexer[1:3])
|
79 |
+
expected = np.array([0, 1], dtype="intp")
|
80 |
+
tm.assert_numpy_array_equal(result, expected)
|
81 |
+
|
82 |
+
result = np.sort(indexer[3:])
|
83 |
+
expected = np.array([-1], dtype="intp")
|
84 |
+
tm.assert_numpy_array_equal(result, expected)
|
85 |
+
|
86 |
+
result = missing
|
87 |
+
expected = np.array([2], dtype="intp")
|
88 |
+
tm.assert_numpy_array_equal(result, expected)
|
89 |
+
|
90 |
+
@pytest.mark.parametrize(
|
91 |
+
"dtype, target_value, target_dtype",
|
92 |
+
[("int64", 2**63 + 1, "uint64"), ("uint64", -1, "int64")],
|
93 |
+
)
|
94 |
+
def test_get_indexer_non_unique_overflow(self, dtype, target_value, target_dtype):
|
95 |
+
left, right = np.array([0, 2], dtype=dtype), np.array([1, 3], dtype=dtype)
|
96 |
+
tree = IntervalTree(left, right)
|
97 |
+
target = np.array([target_value], dtype=target_dtype)
|
98 |
+
|
99 |
+
result_indexer, result_missing = tree.get_indexer_non_unique(target)
|
100 |
+
expected_indexer = np.array([-1], dtype="intp")
|
101 |
+
tm.assert_numpy_array_equal(result_indexer, expected_indexer)
|
102 |
+
|
103 |
+
expected_missing = np.array([0], dtype="intp")
|
104 |
+
tm.assert_numpy_array_equal(result_missing, expected_missing)
|
105 |
+
|
106 |
+
def test_duplicates(self, dtype):
|
107 |
+
left = np.array([0, 0, 0], dtype=dtype)
|
108 |
+
tree = IntervalTree(left, left + 1)
|
109 |
+
|
110 |
+
with pytest.raises(
|
111 |
+
KeyError, match="'indexer does not intersect a unique set of intervals'"
|
112 |
+
):
|
113 |
+
tree.get_indexer(np.array([0.5]))
|
114 |
+
|
115 |
+
indexer, missing = tree.get_indexer_non_unique(np.array([0.5]))
|
116 |
+
result = np.sort(indexer)
|
117 |
+
expected = np.array([0, 1, 2], dtype="intp")
|
118 |
+
tm.assert_numpy_array_equal(result, expected)
|
119 |
+
|
120 |
+
result = missing
|
121 |
+
expected = np.array([], dtype="intp")
|
122 |
+
tm.assert_numpy_array_equal(result, expected)
|
123 |
+
|
124 |
+
@pytest.mark.parametrize(
|
125 |
+
"leaf_size", [skipif_32bit(1), skipif_32bit(10), skipif_32bit(100), 10000]
|
126 |
+
)
|
127 |
+
def test_get_indexer_closed(self, closed, leaf_size):
|
128 |
+
x = np.arange(1000, dtype="float64")
|
129 |
+
found = x.astype("intp")
|
130 |
+
not_found = (-1 * np.ones(1000)).astype("intp")
|
131 |
+
|
132 |
+
tree = IntervalTree(x, x + 0.5, closed=closed, leaf_size=leaf_size)
|
133 |
+
tm.assert_numpy_array_equal(found, tree.get_indexer(x + 0.25))
|
134 |
+
|
135 |
+
expected = found if tree.closed_left else not_found
|
136 |
+
tm.assert_numpy_array_equal(expected, tree.get_indexer(x + 0.0))
|
137 |
+
|
138 |
+
expected = found if tree.closed_right else not_found
|
139 |
+
tm.assert_numpy_array_equal(expected, tree.get_indexer(x + 0.5))
|
140 |
+
|
141 |
+
@pytest.mark.parametrize(
|
142 |
+
"left, right, expected",
|
143 |
+
[
|
144 |
+
(np.array([0, 1, 4], dtype="int64"), np.array([2, 3, 5]), True),
|
145 |
+
(np.array([0, 1, 2], dtype="int64"), np.array([5, 4, 3]), True),
|
146 |
+
(np.array([0, 1, np.nan]), np.array([5, 4, np.nan]), True),
|
147 |
+
(np.array([0, 2, 4], dtype="int64"), np.array([1, 3, 5]), False),
|
148 |
+
(np.array([0, 2, np.nan]), np.array([1, 3, np.nan]), False),
|
149 |
+
],
|
150 |
+
)
|
151 |
+
@pytest.mark.parametrize("order", (list(x) for x in permutations(range(3))))
|
152 |
+
def test_is_overlapping(self, closed, order, left, right, expected):
|
153 |
+
# GH 23309
|
154 |
+
tree = IntervalTree(left[order], right[order], closed=closed)
|
155 |
+
result = tree.is_overlapping
|
156 |
+
assert result is expected
|
157 |
+
|
158 |
+
@pytest.mark.parametrize("order", (list(x) for x in permutations(range(3))))
|
159 |
+
def test_is_overlapping_endpoints(self, closed, order):
|
160 |
+
"""shared endpoints are marked as overlapping"""
|
161 |
+
# GH 23309
|
162 |
+
left, right = np.arange(3, dtype="int64"), np.arange(1, 4)
|
163 |
+
tree = IntervalTree(left[order], right[order], closed=closed)
|
164 |
+
result = tree.is_overlapping
|
165 |
+
expected = closed == "both"
|
166 |
+
assert result is expected
|
167 |
+
|
168 |
+
@pytest.mark.parametrize(
|
169 |
+
"left, right",
|
170 |
+
[
|
171 |
+
(np.array([], dtype="int64"), np.array([], dtype="int64")),
|
172 |
+
(np.array([0], dtype="int64"), np.array([1], dtype="int64")),
|
173 |
+
(np.array([np.nan]), np.array([np.nan])),
|
174 |
+
(np.array([np.nan] * 3), np.array([np.nan] * 3)),
|
175 |
+
],
|
176 |
+
)
|
177 |
+
def test_is_overlapping_trivial(self, closed, left, right):
|
178 |
+
# GH 23309
|
179 |
+
tree = IntervalTree(left, right, closed=closed)
|
180 |
+
assert tree.is_overlapping is False
|
181 |
+
|
182 |
+
@pytest.mark.skipif(not IS64, reason="GH 23440")
|
183 |
+
def test_construction_overflow(self):
|
184 |
+
# GH 25485
|
185 |
+
left, right = np.arange(101, dtype="int64"), [np.iinfo(np.int64).max] * 101
|
186 |
+
tree = IntervalTree(left, right)
|
187 |
+
|
188 |
+
# pivot should be average of left/right medians
|
189 |
+
result = tree.root.pivot
|
190 |
+
expected = (50 + np.iinfo(np.int64).max) / 2
|
191 |
+
assert result == expected
|
192 |
+
|
193 |
+
@pytest.mark.xfail(not IS64, reason="GH 23440")
|
194 |
+
@pytest.mark.parametrize(
|
195 |
+
"left, right, expected",
|
196 |
+
[
|
197 |
+
([-np.inf, 1.0], [1.0, 2.0], 0.0),
|
198 |
+
([-np.inf, -2.0], [-2.0, -1.0], -2.0),
|
199 |
+
([-2.0, -1.0], [-1.0, np.inf], 0.0),
|
200 |
+
([1.0, 2.0], [2.0, np.inf], 2.0),
|
201 |
+
],
|
202 |
+
)
|
203 |
+
def test_inf_bound_infinite_recursion(self, left, right, expected):
|
204 |
+
# GH 46658
|
205 |
+
|
206 |
+
tree = IntervalTree(left * 101, right * 101)
|
207 |
+
|
208 |
+
result = tree.root.pivot
|
209 |
+
assert result == expected
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/test_join.py
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
from pandas import (
|
4 |
+
IntervalIndex,
|
5 |
+
MultiIndex,
|
6 |
+
RangeIndex,
|
7 |
+
)
|
8 |
+
import pandas._testing as tm
|
9 |
+
|
10 |
+
|
11 |
+
@pytest.fixture
|
12 |
+
def range_index():
|
13 |
+
return RangeIndex(3, name="range_index")
|
14 |
+
|
15 |
+
|
16 |
+
@pytest.fixture
|
17 |
+
def interval_index():
|
18 |
+
return IntervalIndex.from_tuples(
|
19 |
+
[(0.0, 1.0), (1.0, 2.0), (1.5, 2.5)], name="interval_index"
|
20 |
+
)
|
21 |
+
|
22 |
+
|
23 |
+
def test_join_overlapping_in_mi_to_same_intervalindex(range_index, interval_index):
|
24 |
+
# GH-45661
|
25 |
+
multi_index = MultiIndex.from_product([interval_index, range_index])
|
26 |
+
result = multi_index.join(interval_index)
|
27 |
+
|
28 |
+
tm.assert_index_equal(result, multi_index)
|
29 |
+
|
30 |
+
|
31 |
+
def test_join_overlapping_to_multiindex_with_same_interval(range_index, interval_index):
|
32 |
+
# GH-45661
|
33 |
+
multi_index = MultiIndex.from_product([interval_index, range_index])
|
34 |
+
result = interval_index.join(multi_index)
|
35 |
+
|
36 |
+
tm.assert_index_equal(result, multi_index)
|
37 |
+
|
38 |
+
|
39 |
+
def test_join_overlapping_interval_to_another_intervalindex(interval_index):
|
40 |
+
# GH-45661
|
41 |
+
flipped_interval_index = interval_index[::-1]
|
42 |
+
result = interval_index.join(flipped_interval_index)
|
43 |
+
|
44 |
+
tm.assert_index_equal(result, interval_index)
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/test_pickle.py
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
from pandas import IntervalIndex
|
4 |
+
import pandas._testing as tm
|
5 |
+
|
6 |
+
|
7 |
+
class TestPickle:
|
8 |
+
@pytest.mark.parametrize("closed", ["left", "right", "both"])
|
9 |
+
def test_pickle_round_trip_closed(self, closed):
|
10 |
+
# https://github.com/pandas-dev/pandas/issues/35658
|
11 |
+
idx = IntervalIndex.from_tuples([(1, 2), (2, 3)], closed=closed)
|
12 |
+
result = tm.round_trip_pickle(idx)
|
13 |
+
tm.assert_index_equal(result, idx)
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/interval/test_setops.py
ADDED
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas import (
|
5 |
+
Index,
|
6 |
+
IntervalIndex,
|
7 |
+
Timestamp,
|
8 |
+
interval_range,
|
9 |
+
)
|
10 |
+
import pandas._testing as tm
|
11 |
+
|
12 |
+
|
13 |
+
def monotonic_index(start, end, dtype="int64", closed="right"):
|
14 |
+
return IntervalIndex.from_breaks(np.arange(start, end, dtype=dtype), closed=closed)
|
15 |
+
|
16 |
+
|
17 |
+
def empty_index(dtype="int64", closed="right"):
|
18 |
+
return IntervalIndex(np.array([], dtype=dtype), closed=closed)
|
19 |
+
|
20 |
+
|
21 |
+
class TestIntervalIndex:
|
22 |
+
def test_union(self, closed, sort):
|
23 |
+
index = monotonic_index(0, 11, closed=closed)
|
24 |
+
other = monotonic_index(5, 13, closed=closed)
|
25 |
+
|
26 |
+
expected = monotonic_index(0, 13, closed=closed)
|
27 |
+
result = index[::-1].union(other, sort=sort)
|
28 |
+
if sort in (None, True):
|
29 |
+
tm.assert_index_equal(result, expected)
|
30 |
+
else:
|
31 |
+
tm.assert_index_equal(result.sort_values(), expected)
|
32 |
+
|
33 |
+
result = other[::-1].union(index, sort=sort)
|
34 |
+
if sort in (None, True):
|
35 |
+
tm.assert_index_equal(result, expected)
|
36 |
+
else:
|
37 |
+
tm.assert_index_equal(result.sort_values(), expected)
|
38 |
+
|
39 |
+
tm.assert_index_equal(index.union(index, sort=sort), index)
|
40 |
+
tm.assert_index_equal(index.union(index[:1], sort=sort), index)
|
41 |
+
|
42 |
+
def test_union_empty_result(self, closed, sort):
|
43 |
+
# GH 19101: empty result, same dtype
|
44 |
+
index = empty_index(dtype="int64", closed=closed)
|
45 |
+
result = index.union(index, sort=sort)
|
46 |
+
tm.assert_index_equal(result, index)
|
47 |
+
|
48 |
+
# GH 19101: empty result, different numeric dtypes -> common dtype is f8
|
49 |
+
other = empty_index(dtype="float64", closed=closed)
|
50 |
+
result = index.union(other, sort=sort)
|
51 |
+
expected = other
|
52 |
+
tm.assert_index_equal(result, expected)
|
53 |
+
|
54 |
+
other = index.union(index, sort=sort)
|
55 |
+
tm.assert_index_equal(result, expected)
|
56 |
+
|
57 |
+
other = empty_index(dtype="uint64", closed=closed)
|
58 |
+
result = index.union(other, sort=sort)
|
59 |
+
tm.assert_index_equal(result, expected)
|
60 |
+
|
61 |
+
result = other.union(index, sort=sort)
|
62 |
+
tm.assert_index_equal(result, expected)
|
63 |
+
|
64 |
+
def test_intersection(self, closed, sort):
|
65 |
+
index = monotonic_index(0, 11, closed=closed)
|
66 |
+
other = monotonic_index(5, 13, closed=closed)
|
67 |
+
|
68 |
+
expected = monotonic_index(5, 11, closed=closed)
|
69 |
+
result = index[::-1].intersection(other, sort=sort)
|
70 |
+
if sort in (None, True):
|
71 |
+
tm.assert_index_equal(result, expected)
|
72 |
+
else:
|
73 |
+
tm.assert_index_equal(result.sort_values(), expected)
|
74 |
+
|
75 |
+
result = other[::-1].intersection(index, sort=sort)
|
76 |
+
if sort in (None, True):
|
77 |
+
tm.assert_index_equal(result, expected)
|
78 |
+
else:
|
79 |
+
tm.assert_index_equal(result.sort_values(), expected)
|
80 |
+
|
81 |
+
tm.assert_index_equal(index.intersection(index, sort=sort), index)
|
82 |
+
|
83 |
+
# GH 26225: nested intervals
|
84 |
+
index = IntervalIndex.from_tuples([(1, 2), (1, 3), (1, 4), (0, 2)])
|
85 |
+
other = IntervalIndex.from_tuples([(1, 2), (1, 3)])
|
86 |
+
expected = IntervalIndex.from_tuples([(1, 2), (1, 3)])
|
87 |
+
result = index.intersection(other)
|
88 |
+
tm.assert_index_equal(result, expected)
|
89 |
+
|
90 |
+
# GH 26225
|
91 |
+
index = IntervalIndex.from_tuples([(0, 3), (0, 2)])
|
92 |
+
other = IntervalIndex.from_tuples([(0, 2), (1, 3)])
|
93 |
+
expected = IntervalIndex.from_tuples([(0, 2)])
|
94 |
+
result = index.intersection(other)
|
95 |
+
tm.assert_index_equal(result, expected)
|
96 |
+
|
97 |
+
# GH 26225: duplicate nan element
|
98 |
+
index = IntervalIndex([np.nan, np.nan])
|
99 |
+
other = IntervalIndex([np.nan])
|
100 |
+
expected = IntervalIndex([np.nan])
|
101 |
+
result = index.intersection(other)
|
102 |
+
tm.assert_index_equal(result, expected)
|
103 |
+
|
104 |
+
def test_intersection_empty_result(self, closed, sort):
|
105 |
+
index = monotonic_index(0, 11, closed=closed)
|
106 |
+
|
107 |
+
# GH 19101: empty result, same dtype
|
108 |
+
other = monotonic_index(300, 314, closed=closed)
|
109 |
+
expected = empty_index(dtype="int64", closed=closed)
|
110 |
+
result = index.intersection(other, sort=sort)
|
111 |
+
tm.assert_index_equal(result, expected)
|
112 |
+
|
113 |
+
# GH 19101: empty result, different numeric dtypes -> common dtype is float64
|
114 |
+
other = monotonic_index(300, 314, dtype="float64", closed=closed)
|
115 |
+
result = index.intersection(other, sort=sort)
|
116 |
+
expected = other[:0]
|
117 |
+
tm.assert_index_equal(result, expected)
|
118 |
+
|
119 |
+
other = monotonic_index(300, 314, dtype="uint64", closed=closed)
|
120 |
+
result = index.intersection(other, sort=sort)
|
121 |
+
tm.assert_index_equal(result, expected)
|
122 |
+
|
123 |
+
def test_intersection_duplicates(self):
|
124 |
+
# GH#38743
|
125 |
+
index = IntervalIndex.from_tuples([(1, 2), (1, 2), (2, 3), (3, 4)])
|
126 |
+
other = IntervalIndex.from_tuples([(1, 2), (2, 3)])
|
127 |
+
expected = IntervalIndex.from_tuples([(1, 2), (2, 3)])
|
128 |
+
result = index.intersection(other)
|
129 |
+
tm.assert_index_equal(result, expected)
|
130 |
+
|
131 |
+
def test_difference(self, closed, sort):
|
132 |
+
index = IntervalIndex.from_arrays([1, 0, 3, 2], [1, 2, 3, 4], closed=closed)
|
133 |
+
result = index.difference(index[:1], sort=sort)
|
134 |
+
expected = index[1:]
|
135 |
+
if sort is None:
|
136 |
+
expected = expected.sort_values()
|
137 |
+
tm.assert_index_equal(result, expected)
|
138 |
+
|
139 |
+
# GH 19101: empty result, same dtype
|
140 |
+
result = index.difference(index, sort=sort)
|
141 |
+
expected = empty_index(dtype="int64", closed=closed)
|
142 |
+
tm.assert_index_equal(result, expected)
|
143 |
+
|
144 |
+
# GH 19101: empty result, different dtypes
|
145 |
+
other = IntervalIndex.from_arrays(
|
146 |
+
index.left.astype("float64"), index.right, closed=closed
|
147 |
+
)
|
148 |
+
result = index.difference(other, sort=sort)
|
149 |
+
tm.assert_index_equal(result, expected)
|
150 |
+
|
151 |
+
def test_symmetric_difference(self, closed, sort):
|
152 |
+
index = monotonic_index(0, 11, closed=closed)
|
153 |
+
result = index[1:].symmetric_difference(index[:-1], sort=sort)
|
154 |
+
expected = IntervalIndex([index[0], index[-1]])
|
155 |
+
if sort in (None, True):
|
156 |
+
tm.assert_index_equal(result, expected)
|
157 |
+
else:
|
158 |
+
tm.assert_index_equal(result.sort_values(), expected)
|
159 |
+
|
160 |
+
# GH 19101: empty result, same dtype
|
161 |
+
result = index.symmetric_difference(index, sort=sort)
|
162 |
+
expected = empty_index(dtype="int64", closed=closed)
|
163 |
+
if sort in (None, True):
|
164 |
+
tm.assert_index_equal(result, expected)
|
165 |
+
else:
|
166 |
+
tm.assert_index_equal(result.sort_values(), expected)
|
167 |
+
|
168 |
+
# GH 19101: empty result, different dtypes
|
169 |
+
other = IntervalIndex.from_arrays(
|
170 |
+
index.left.astype("float64"), index.right, closed=closed
|
171 |
+
)
|
172 |
+
result = index.symmetric_difference(other, sort=sort)
|
173 |
+
expected = empty_index(dtype="float64", closed=closed)
|
174 |
+
tm.assert_index_equal(result, expected)
|
175 |
+
|
176 |
+
@pytest.mark.filterwarnings("ignore:'<' not supported between:RuntimeWarning")
|
177 |
+
@pytest.mark.parametrize(
|
178 |
+
"op_name", ["union", "intersection", "difference", "symmetric_difference"]
|
179 |
+
)
|
180 |
+
def test_set_incompatible_types(self, closed, op_name, sort):
|
181 |
+
index = monotonic_index(0, 11, closed=closed)
|
182 |
+
set_op = getattr(index, op_name)
|
183 |
+
|
184 |
+
# TODO: standardize return type of non-union setops type(self vs other)
|
185 |
+
# non-IntervalIndex
|
186 |
+
if op_name == "difference":
|
187 |
+
expected = index
|
188 |
+
else:
|
189 |
+
expected = getattr(index.astype("O"), op_name)(Index([1, 2, 3]))
|
190 |
+
result = set_op(Index([1, 2, 3]), sort=sort)
|
191 |
+
tm.assert_index_equal(result, expected)
|
192 |
+
|
193 |
+
# mixed closed -> cast to object
|
194 |
+
for other_closed in {"right", "left", "both", "neither"} - {closed}:
|
195 |
+
other = monotonic_index(0, 11, closed=other_closed)
|
196 |
+
expected = getattr(index.astype(object), op_name)(other, sort=sort)
|
197 |
+
if op_name == "difference":
|
198 |
+
expected = index
|
199 |
+
result = set_op(other, sort=sort)
|
200 |
+
tm.assert_index_equal(result, expected)
|
201 |
+
|
202 |
+
# GH 19016: incompatible dtypes -> cast to object
|
203 |
+
other = interval_range(Timestamp("20180101"), periods=9, closed=closed)
|
204 |
+
expected = getattr(index.astype(object), op_name)(other, sort=sort)
|
205 |
+
if op_name == "difference":
|
206 |
+
expected = index
|
207 |
+
result = set_op(other, sort=sort)
|
208 |
+
tm.assert_index_equal(result, expected)
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__init__.py
ADDED
File without changes
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (199 Bytes). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__pycache__/test_arithmetic.cpython-310.pyc
ADDED
Binary file (1.53 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__pycache__/test_constructors.cpython-310.pyc
ADDED
Binary file (10.3 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__pycache__/test_delete.cpython-310.pyc
ADDED
Binary file (2.14 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__pycache__/test_formats.cpython-310.pyc
ADDED
Binary file (3.42 kB). View file
|
|
venv/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__pycache__/test_freq_attr.cpython-310.pyc
ADDED
Binary file (2.23 kB). View file
|
|