Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/__pycache__/test_constructors.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/__pycache__/test_formats.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/__pycache__/test_indexing.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/__pycache__/test_pickle.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/__pycache__/test_reshape.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/__pycache__/test_setops.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/__pycache__/test_where.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/test_constructors.py +80 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/test_formats.py +163 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/test_indexing.py +104 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/test_pickle.py +11 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/test_reshape.py +95 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/test_setops.py +266 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/test_where.py +13 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/conftest.py +41 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/conftest.py +27 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/test_astype.py +30 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/test_copy.py +96 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/test_equivalence.py +284 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/test_get_set.py +384 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/test_indexing.py +1001 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/test_integrity.py +289 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/test_lexsort.py +46 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/test_missing.py +111 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/test_partial_indexing.py +148 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/test_pickle.py +10 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/test_reindex.py +174 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/test_setops.py +772 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/test_sorting.py +349 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/test_take.py +78 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/object/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/object/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/object/__pycache__/test_astype.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/object/__pycache__/test_indexing.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/object/test_astype.py +33 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/object/test_indexing.py +243 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/ranges/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/ranges/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/ranges/__pycache__/test_constructors.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/ranges/__pycache__/test_indexing.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/ranges/__pycache__/test_join.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/ranges/__pycache__/test_range.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/ranges/__pycache__/test_setops.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/ranges/test_constructors.py +164 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/ranges/test_indexing.py +137 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/ranges/test_join.py +177 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/ranges/test_range.py +622 -0
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (204 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/__pycache__/test_constructors.cpython-310.pyc
ADDED
Binary file (3.35 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/__pycache__/test_formats.cpython-310.pyc
ADDED
Binary file (5.1 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/__pycache__/test_indexing.cpython-310.pyc
ADDED
Binary file (4.34 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/__pycache__/test_pickle.cpython-310.pyc
ADDED
Binary file (572 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/__pycache__/test_reshape.cpython-310.pyc
ADDED
Binary file (3.52 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/__pycache__/test_setops.cpython-310.pyc
ADDED
Binary file (8.27 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/__pycache__/test_where.cpython-310.pyc
ADDED
Binary file (826 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/test_constructors.py
ADDED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
import pandas as pd
|
5 |
+
from pandas import (
|
6 |
+
Index,
|
7 |
+
MultiIndex,
|
8 |
+
Series,
|
9 |
+
)
|
10 |
+
import pandas._testing as tm
|
11 |
+
|
12 |
+
|
13 |
+
class TestIndexConstructor:
|
14 |
+
# Tests for the Index constructor, specifically for cases that do
|
15 |
+
# not return a subclass
|
16 |
+
|
17 |
+
@pytest.mark.parametrize("value", [1, np.int64(1)])
|
18 |
+
def test_constructor_corner(self, value):
|
19 |
+
# corner case
|
20 |
+
msg = (
|
21 |
+
r"Index\(\.\.\.\) must be called with a collection of some "
|
22 |
+
f"kind, {value} was passed"
|
23 |
+
)
|
24 |
+
with pytest.raises(TypeError, match=msg):
|
25 |
+
Index(value)
|
26 |
+
|
27 |
+
@pytest.mark.parametrize("index_vals", [[("A", 1), "B"], ["B", ("A", 1)]])
|
28 |
+
def test_construction_list_mixed_tuples(self, index_vals):
|
29 |
+
# see gh-10697: if we are constructing from a mixed list of tuples,
|
30 |
+
# make sure that we are independent of the sorting order.
|
31 |
+
index = Index(index_vals)
|
32 |
+
assert isinstance(index, Index)
|
33 |
+
assert not isinstance(index, MultiIndex)
|
34 |
+
|
35 |
+
def test_constructor_cast(self):
|
36 |
+
msg = "could not convert string to float"
|
37 |
+
with pytest.raises(ValueError, match=msg):
|
38 |
+
Index(["a", "b", "c"], dtype=float)
|
39 |
+
|
40 |
+
@pytest.mark.parametrize("tuple_list", [[()], [(), ()]])
|
41 |
+
def test_construct_empty_tuples(self, tuple_list):
|
42 |
+
# GH #45608
|
43 |
+
result = Index(tuple_list)
|
44 |
+
expected = MultiIndex.from_tuples(tuple_list)
|
45 |
+
|
46 |
+
tm.assert_index_equal(result, expected)
|
47 |
+
|
48 |
+
def test_index_string_inference(self):
|
49 |
+
# GH#54430
|
50 |
+
pytest.importorskip("pyarrow")
|
51 |
+
dtype = "string[pyarrow_numpy]"
|
52 |
+
expected = Index(["a", "b"], dtype=dtype)
|
53 |
+
with pd.option_context("future.infer_string", True):
|
54 |
+
ser = Index(["a", "b"])
|
55 |
+
tm.assert_index_equal(ser, expected)
|
56 |
+
|
57 |
+
expected = Index(["a", 1], dtype="object")
|
58 |
+
with pd.option_context("future.infer_string", True):
|
59 |
+
ser = Index(["a", 1])
|
60 |
+
tm.assert_index_equal(ser, expected)
|
61 |
+
|
62 |
+
def test_inference_on_pandas_objects(self):
|
63 |
+
# GH#56012
|
64 |
+
idx = Index([pd.Timestamp("2019-12-31")], dtype=object)
|
65 |
+
with tm.assert_produces_warning(FutureWarning, match="Dtype inference"):
|
66 |
+
result = Index(idx)
|
67 |
+
assert result.dtype != np.object_
|
68 |
+
|
69 |
+
ser = Series([pd.Timestamp("2019-12-31")], dtype=object)
|
70 |
+
|
71 |
+
with tm.assert_produces_warning(FutureWarning, match="Dtype inference"):
|
72 |
+
result = Index(ser)
|
73 |
+
assert result.dtype != np.object_
|
74 |
+
|
75 |
+
def test_constructor_not_read_only(self):
|
76 |
+
# GH#57130
|
77 |
+
ser = Series([1, 2], dtype=object)
|
78 |
+
with pd.option_context("mode.copy_on_write", True):
|
79 |
+
idx = Index(ser)
|
80 |
+
assert idx._values.flags.writeable
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/test_formats.py
ADDED
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas._config import using_pyarrow_string_dtype
|
5 |
+
import pandas._config.config as cf
|
6 |
+
|
7 |
+
from pandas import Index
|
8 |
+
import pandas._testing as tm
|
9 |
+
|
10 |
+
|
11 |
+
class TestIndexRendering:
|
12 |
+
def test_repr_is_valid_construction_code(self):
|
13 |
+
# for the case of Index, where the repr is traditional rather than
|
14 |
+
# stylized
|
15 |
+
idx = Index(["a", "b"])
|
16 |
+
res = eval(repr(idx))
|
17 |
+
tm.assert_index_equal(res, idx)
|
18 |
+
|
19 |
+
@pytest.mark.xfail(using_pyarrow_string_dtype(), reason="repr different")
|
20 |
+
@pytest.mark.parametrize(
|
21 |
+
"index,expected",
|
22 |
+
[
|
23 |
+
# ASCII
|
24 |
+
# short
|
25 |
+
(
|
26 |
+
Index(["a", "bb", "ccc"]),
|
27 |
+
"""Index(['a', 'bb', 'ccc'], dtype='object')""",
|
28 |
+
),
|
29 |
+
# multiple lines
|
30 |
+
(
|
31 |
+
Index(["a", "bb", "ccc"] * 10),
|
32 |
+
"Index(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', "
|
33 |
+
"'bb', 'ccc', 'a', 'bb', 'ccc',\n"
|
34 |
+
" 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', "
|
35 |
+
"'bb', 'ccc', 'a', 'bb', 'ccc',\n"
|
36 |
+
" 'a', 'bb', 'ccc', 'a', 'bb', 'ccc'],\n"
|
37 |
+
" dtype='object')",
|
38 |
+
),
|
39 |
+
# truncated
|
40 |
+
(
|
41 |
+
Index(["a", "bb", "ccc"] * 100),
|
42 |
+
"Index(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a',\n"
|
43 |
+
" ...\n"
|
44 |
+
" 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc'],\n"
|
45 |
+
" dtype='object', length=300)",
|
46 |
+
),
|
47 |
+
# Non-ASCII
|
48 |
+
# short
|
49 |
+
(
|
50 |
+
Index(["あ", "いい", "ううう"]),
|
51 |
+
"""Index(['あ', 'いい', 'ううう'], dtype='object')""",
|
52 |
+
),
|
53 |
+
# multiple lines
|
54 |
+
(
|
55 |
+
Index(["あ", "いい", "ううう"] * 10),
|
56 |
+
(
|
57 |
+
"Index(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', "
|
58 |
+
"'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう',\n"
|
59 |
+
" 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', "
|
60 |
+
"'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう',\n"
|
61 |
+
" 'あ', 'いい', 'ううう', 'あ', 'いい', "
|
62 |
+
"'ううう'],\n"
|
63 |
+
" dtype='object')"
|
64 |
+
),
|
65 |
+
),
|
66 |
+
# truncated
|
67 |
+
(
|
68 |
+
Index(["あ", "いい", "ううう"] * 100),
|
69 |
+
(
|
70 |
+
"Index(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', "
|
71 |
+
"'あ', 'いい', 'ううう', 'あ',\n"
|
72 |
+
" ...\n"
|
73 |
+
" 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', "
|
74 |
+
"'ううう', 'あ', 'いい', 'ううう'],\n"
|
75 |
+
" dtype='object', length=300)"
|
76 |
+
),
|
77 |
+
),
|
78 |
+
],
|
79 |
+
)
|
80 |
+
def test_string_index_repr(self, index, expected):
|
81 |
+
result = repr(index)
|
82 |
+
assert result == expected
|
83 |
+
|
84 |
+
@pytest.mark.xfail(using_pyarrow_string_dtype(), reason="repr different")
|
85 |
+
@pytest.mark.parametrize(
|
86 |
+
"index,expected",
|
87 |
+
[
|
88 |
+
# short
|
89 |
+
(
|
90 |
+
Index(["あ", "いい", "ううう"]),
|
91 |
+
("Index(['あ', 'いい', 'ううう'], dtype='object')"),
|
92 |
+
),
|
93 |
+
# multiple lines
|
94 |
+
(
|
95 |
+
Index(["あ", "いい", "ううう"] * 10),
|
96 |
+
(
|
97 |
+
"Index(['あ', 'いい', 'ううう', 'あ', 'いい', "
|
98 |
+
"'ううう', 'あ', 'いい', 'ううう',\n"
|
99 |
+
" 'あ', 'いい', 'ううう', 'あ', 'いい', "
|
100 |
+
"'ううう', 'あ', 'いい', 'ううう',\n"
|
101 |
+
" 'あ', 'いい', 'ううう', 'あ', 'いい', "
|
102 |
+
"'ううう', 'あ', 'いい', 'ううう',\n"
|
103 |
+
" 'あ', 'いい', 'ううう'],\n"
|
104 |
+
" dtype='object')"
|
105 |
+
""
|
106 |
+
),
|
107 |
+
),
|
108 |
+
# truncated
|
109 |
+
(
|
110 |
+
Index(["あ", "いい", "ううう"] * 100),
|
111 |
+
(
|
112 |
+
"Index(['あ', 'いい', 'ううう', 'あ', 'いい', "
|
113 |
+
"'ううう', 'あ', 'いい', 'ううう',\n"
|
114 |
+
" 'あ',\n"
|
115 |
+
" ...\n"
|
116 |
+
" 'ううう', 'あ', 'いい', 'ううう', 'あ', "
|
117 |
+
"'いい', 'ううう', 'あ', 'いい',\n"
|
118 |
+
" 'ううう'],\n"
|
119 |
+
" dtype='object', length=300)"
|
120 |
+
),
|
121 |
+
),
|
122 |
+
],
|
123 |
+
)
|
124 |
+
def test_string_index_repr_with_unicode_option(self, index, expected):
|
125 |
+
# Enable Unicode option -----------------------------------------
|
126 |
+
with cf.option_context("display.unicode.east_asian_width", True):
|
127 |
+
result = repr(index)
|
128 |
+
assert result == expected
|
129 |
+
|
130 |
+
def test_repr_summary(self):
|
131 |
+
with cf.option_context("display.max_seq_items", 10):
|
132 |
+
result = repr(Index(np.arange(1000)))
|
133 |
+
assert len(result) < 200
|
134 |
+
assert "..." in result
|
135 |
+
|
136 |
+
def test_summary_bug(self):
|
137 |
+
# GH#3869
|
138 |
+
ind = Index(["{other}%s", "~:{range}:0"], name="A")
|
139 |
+
result = ind._summary()
|
140 |
+
# shouldn't be formatted accidentally.
|
141 |
+
assert "~:{range}:0" in result
|
142 |
+
assert "{other}%s" in result
|
143 |
+
|
144 |
+
def test_index_repr_bool_nan(self):
|
145 |
+
# GH32146
|
146 |
+
arr = Index([True, False, np.nan], dtype=object)
|
147 |
+
msg = "Index.format is deprecated"
|
148 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
149 |
+
exp1 = arr.format()
|
150 |
+
out1 = ["True", "False", "NaN"]
|
151 |
+
assert out1 == exp1
|
152 |
+
|
153 |
+
exp2 = repr(arr)
|
154 |
+
out2 = "Index([True, False, nan], dtype='object')"
|
155 |
+
assert out2 == exp2
|
156 |
+
|
157 |
+
def test_format_different_scalar_lengths(self):
|
158 |
+
# GH#35439
|
159 |
+
idx = Index(["aaaaaaaaa", "b"])
|
160 |
+
expected = ["aaaaaaaaa", "b"]
|
161 |
+
msg = r"Index\.format is deprecated"
|
162 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
163 |
+
assert idx.format() == expected
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/test_indexing.py
ADDED
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas._libs import index as libindex
|
5 |
+
|
6 |
+
import pandas as pd
|
7 |
+
from pandas import (
|
8 |
+
Index,
|
9 |
+
NaT,
|
10 |
+
)
|
11 |
+
import pandas._testing as tm
|
12 |
+
|
13 |
+
|
14 |
+
class TestGetSliceBounds:
|
15 |
+
@pytest.mark.parametrize("side, expected", [("left", 4), ("right", 5)])
|
16 |
+
def test_get_slice_bounds_within(self, side, expected):
|
17 |
+
index = Index(list("abcdef"))
|
18 |
+
result = index.get_slice_bound("e", side=side)
|
19 |
+
assert result == expected
|
20 |
+
|
21 |
+
@pytest.mark.parametrize("side", ["left", "right"])
|
22 |
+
@pytest.mark.parametrize(
|
23 |
+
"data, bound, expected", [(list("abcdef"), "x", 6), (list("bcdefg"), "a", 0)]
|
24 |
+
)
|
25 |
+
def test_get_slice_bounds_outside(self, side, expected, data, bound):
|
26 |
+
index = Index(data)
|
27 |
+
result = index.get_slice_bound(bound, side=side)
|
28 |
+
assert result == expected
|
29 |
+
|
30 |
+
def test_get_slice_bounds_invalid_side(self):
|
31 |
+
with pytest.raises(ValueError, match="Invalid value for side kwarg"):
|
32 |
+
Index([]).get_slice_bound("a", side="middle")
|
33 |
+
|
34 |
+
|
35 |
+
class TestGetIndexerNonUnique:
|
36 |
+
def test_get_indexer_non_unique_dtype_mismatch(self):
|
37 |
+
# GH#25459
|
38 |
+
indexes, missing = Index(["A", "B"]).get_indexer_non_unique(Index([0]))
|
39 |
+
tm.assert_numpy_array_equal(np.array([-1], dtype=np.intp), indexes)
|
40 |
+
tm.assert_numpy_array_equal(np.array([0], dtype=np.intp), missing)
|
41 |
+
|
42 |
+
@pytest.mark.parametrize(
|
43 |
+
"idx_values,idx_non_unique",
|
44 |
+
[
|
45 |
+
([np.nan, 100, 200, 100], [np.nan, 100]),
|
46 |
+
([np.nan, 100.0, 200.0, 100.0], [np.nan, 100.0]),
|
47 |
+
],
|
48 |
+
)
|
49 |
+
def test_get_indexer_non_unique_int_index(self, idx_values, idx_non_unique):
|
50 |
+
indexes, missing = Index(idx_values).get_indexer_non_unique(Index([np.nan]))
|
51 |
+
tm.assert_numpy_array_equal(np.array([0], dtype=np.intp), indexes)
|
52 |
+
tm.assert_numpy_array_equal(np.array([], dtype=np.intp), missing)
|
53 |
+
|
54 |
+
indexes, missing = Index(idx_values).get_indexer_non_unique(
|
55 |
+
Index(idx_non_unique)
|
56 |
+
)
|
57 |
+
tm.assert_numpy_array_equal(np.array([0, 1, 3], dtype=np.intp), indexes)
|
58 |
+
tm.assert_numpy_array_equal(np.array([], dtype=np.intp), missing)
|
59 |
+
|
60 |
+
|
61 |
+
class TestGetLoc:
|
62 |
+
@pytest.mark.slow # to_flat_index takes a while
|
63 |
+
def test_get_loc_tuple_monotonic_above_size_cutoff(self, monkeypatch):
|
64 |
+
# Go through the libindex path for which using
|
65 |
+
# _bin_search vs ndarray.searchsorted makes a difference
|
66 |
+
|
67 |
+
with monkeypatch.context():
|
68 |
+
monkeypatch.setattr(libindex, "_SIZE_CUTOFF", 100)
|
69 |
+
lev = list("ABCD")
|
70 |
+
dti = pd.date_range("2016-01-01", periods=10)
|
71 |
+
|
72 |
+
mi = pd.MultiIndex.from_product([lev, range(5), dti])
|
73 |
+
oidx = mi.to_flat_index()
|
74 |
+
|
75 |
+
loc = len(oidx) // 2
|
76 |
+
tup = oidx[loc]
|
77 |
+
|
78 |
+
res = oidx.get_loc(tup)
|
79 |
+
assert res == loc
|
80 |
+
|
81 |
+
def test_get_loc_nan_object_dtype_nonmonotonic_nonunique(self):
|
82 |
+
# case that goes through _maybe_get_bool_indexer
|
83 |
+
idx = Index(["foo", np.nan, None, "foo", 1.0, None], dtype=object)
|
84 |
+
|
85 |
+
# we dont raise KeyError on nan
|
86 |
+
res = idx.get_loc(np.nan)
|
87 |
+
assert res == 1
|
88 |
+
|
89 |
+
# we only match on None, not on np.nan
|
90 |
+
res = idx.get_loc(None)
|
91 |
+
expected = np.array([False, False, True, False, False, True])
|
92 |
+
tm.assert_numpy_array_equal(res, expected)
|
93 |
+
|
94 |
+
# we don't match at all on mismatched NA
|
95 |
+
with pytest.raises(KeyError, match="NaT"):
|
96 |
+
idx.get_loc(NaT)
|
97 |
+
|
98 |
+
|
99 |
+
def test_getitem_boolean_ea_indexer():
|
100 |
+
# GH#45806
|
101 |
+
ser = pd.Series([True, False, pd.NA], dtype="boolean")
|
102 |
+
result = ser.index[ser]
|
103 |
+
expected = Index([0])
|
104 |
+
tm.assert_index_equal(result, expected)
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/test_pickle.py
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from pandas import Index
|
2 |
+
import pandas._testing as tm
|
3 |
+
|
4 |
+
|
5 |
+
def test_pickle_preserves_object_dtype():
|
6 |
+
# GH#43188, GH#43155 don't infer numeric dtype
|
7 |
+
index = Index([1, 2, 3], dtype=object)
|
8 |
+
|
9 |
+
result = tm.round_trip_pickle(index)
|
10 |
+
assert result.dtype == object
|
11 |
+
tm.assert_index_equal(index, result)
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/test_reshape.py
ADDED
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Tests for ndarray-like method on the base Index class
|
3 |
+
"""
|
4 |
+
import numpy as np
|
5 |
+
import pytest
|
6 |
+
|
7 |
+
from pandas import Index
|
8 |
+
import pandas._testing as tm
|
9 |
+
|
10 |
+
|
11 |
+
class TestReshape:
|
12 |
+
def test_repeat(self):
|
13 |
+
repeats = 2
|
14 |
+
index = Index([1, 2, 3])
|
15 |
+
expected = Index([1, 1, 2, 2, 3, 3])
|
16 |
+
|
17 |
+
result = index.repeat(repeats)
|
18 |
+
tm.assert_index_equal(result, expected)
|
19 |
+
|
20 |
+
def test_insert(self):
|
21 |
+
# GH 7256
|
22 |
+
# validate neg/pos inserts
|
23 |
+
result = Index(["b", "c", "d"])
|
24 |
+
|
25 |
+
# test 0th element
|
26 |
+
tm.assert_index_equal(Index(["a", "b", "c", "d"]), result.insert(0, "a"))
|
27 |
+
|
28 |
+
# test Nth element that follows Python list behavior
|
29 |
+
tm.assert_index_equal(Index(["b", "c", "e", "d"]), result.insert(-1, "e"))
|
30 |
+
|
31 |
+
# test loc +/- neq (0, -1)
|
32 |
+
tm.assert_index_equal(result.insert(1, "z"), result.insert(-2, "z"))
|
33 |
+
|
34 |
+
# test empty
|
35 |
+
null_index = Index([])
|
36 |
+
tm.assert_index_equal(Index(["a"], dtype=object), null_index.insert(0, "a"))
|
37 |
+
|
38 |
+
def test_insert_missing(self, nulls_fixture, using_infer_string):
|
39 |
+
# GH#22295
|
40 |
+
# test there is no mangling of NA values
|
41 |
+
expected = Index(["a", nulls_fixture, "b", "c"], dtype=object)
|
42 |
+
result = Index(list("abc"), dtype=object).insert(
|
43 |
+
1, Index([nulls_fixture], dtype=object)
|
44 |
+
)
|
45 |
+
tm.assert_index_equal(result, expected)
|
46 |
+
|
47 |
+
@pytest.mark.parametrize(
|
48 |
+
"val", [(1, 2), np.datetime64("2019-12-31"), np.timedelta64(1, "D")]
|
49 |
+
)
|
50 |
+
@pytest.mark.parametrize("loc", [-1, 2])
|
51 |
+
def test_insert_datetime_into_object(self, loc, val):
|
52 |
+
# GH#44509
|
53 |
+
idx = Index(["1", "2", "3"])
|
54 |
+
result = idx.insert(loc, val)
|
55 |
+
expected = Index(["1", "2", val, "3"])
|
56 |
+
tm.assert_index_equal(result, expected)
|
57 |
+
assert type(expected[2]) is type(val)
|
58 |
+
|
59 |
+
def test_insert_none_into_string_numpy(self):
|
60 |
+
# GH#55365
|
61 |
+
pytest.importorskip("pyarrow")
|
62 |
+
index = Index(["a", "b", "c"], dtype="string[pyarrow_numpy]")
|
63 |
+
result = index.insert(-1, None)
|
64 |
+
expected = Index(["a", "b", None, "c"], dtype="string[pyarrow_numpy]")
|
65 |
+
tm.assert_index_equal(result, expected)
|
66 |
+
|
67 |
+
@pytest.mark.parametrize(
|
68 |
+
"pos,expected",
|
69 |
+
[
|
70 |
+
(0, Index(["b", "c", "d"], name="index")),
|
71 |
+
(-1, Index(["a", "b", "c"], name="index")),
|
72 |
+
],
|
73 |
+
)
|
74 |
+
def test_delete(self, pos, expected):
|
75 |
+
index = Index(["a", "b", "c", "d"], name="index")
|
76 |
+
result = index.delete(pos)
|
77 |
+
tm.assert_index_equal(result, expected)
|
78 |
+
assert result.name == expected.name
|
79 |
+
|
80 |
+
def test_delete_raises(self):
|
81 |
+
index = Index(["a", "b", "c", "d"], name="index")
|
82 |
+
msg = "index 5 is out of bounds for axis 0 with size 4"
|
83 |
+
with pytest.raises(IndexError, match=msg):
|
84 |
+
index.delete(5)
|
85 |
+
|
86 |
+
def test_append_multiple(self):
|
87 |
+
index = Index(["a", "b", "c", "d", "e", "f"])
|
88 |
+
|
89 |
+
foos = [index[:2], index[2:4], index[4:]]
|
90 |
+
result = foos[0].append(foos[1:])
|
91 |
+
tm.assert_index_equal(result, index)
|
92 |
+
|
93 |
+
# empty
|
94 |
+
result = index.append([])
|
95 |
+
tm.assert_index_equal(result, index)
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/test_setops.py
ADDED
@@ -0,0 +1,266 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from datetime import datetime
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
import pytest
|
5 |
+
|
6 |
+
import pandas as pd
|
7 |
+
from pandas import (
|
8 |
+
Index,
|
9 |
+
Series,
|
10 |
+
)
|
11 |
+
import pandas._testing as tm
|
12 |
+
from pandas.core.algorithms import safe_sort
|
13 |
+
|
14 |
+
|
15 |
+
def equal_contents(arr1, arr2) -> bool:
|
16 |
+
"""
|
17 |
+
Checks if the set of unique elements of arr1 and arr2 are equivalent.
|
18 |
+
"""
|
19 |
+
return frozenset(arr1) == frozenset(arr2)
|
20 |
+
|
21 |
+
|
22 |
+
class TestIndexSetOps:
|
23 |
+
@pytest.mark.parametrize(
|
24 |
+
"method", ["union", "intersection", "difference", "symmetric_difference"]
|
25 |
+
)
|
26 |
+
def test_setops_sort_validation(self, method):
|
27 |
+
idx1 = Index(["a", "b"])
|
28 |
+
idx2 = Index(["b", "c"])
|
29 |
+
|
30 |
+
with pytest.raises(ValueError, match="The 'sort' keyword only takes"):
|
31 |
+
getattr(idx1, method)(idx2, sort=2)
|
32 |
+
|
33 |
+
# sort=True is supported as of GH#??
|
34 |
+
getattr(idx1, method)(idx2, sort=True)
|
35 |
+
|
36 |
+
def test_setops_preserve_object_dtype(self):
|
37 |
+
idx = Index([1, 2, 3], dtype=object)
|
38 |
+
result = idx.intersection(idx[1:])
|
39 |
+
expected = idx[1:]
|
40 |
+
tm.assert_index_equal(result, expected)
|
41 |
+
|
42 |
+
# if other is not monotonic increasing, intersection goes through
|
43 |
+
# a different route
|
44 |
+
result = idx.intersection(idx[1:][::-1])
|
45 |
+
tm.assert_index_equal(result, expected)
|
46 |
+
|
47 |
+
result = idx._union(idx[1:], sort=None)
|
48 |
+
expected = idx
|
49 |
+
tm.assert_numpy_array_equal(result, expected.values)
|
50 |
+
|
51 |
+
result = idx.union(idx[1:], sort=None)
|
52 |
+
tm.assert_index_equal(result, expected)
|
53 |
+
|
54 |
+
# if other is not monotonic increasing, _union goes through
|
55 |
+
# a different route
|
56 |
+
result = idx._union(idx[1:][::-1], sort=None)
|
57 |
+
tm.assert_numpy_array_equal(result, expected.values)
|
58 |
+
|
59 |
+
result = idx.union(idx[1:][::-1], sort=None)
|
60 |
+
tm.assert_index_equal(result, expected)
|
61 |
+
|
62 |
+
def test_union_base(self):
|
63 |
+
index = Index([0, "a", 1, "b", 2, "c"])
|
64 |
+
first = index[3:]
|
65 |
+
second = index[:5]
|
66 |
+
|
67 |
+
result = first.union(second)
|
68 |
+
|
69 |
+
expected = Index([0, 1, 2, "a", "b", "c"])
|
70 |
+
tm.assert_index_equal(result, expected)
|
71 |
+
|
72 |
+
@pytest.mark.parametrize("klass", [np.array, Series, list])
|
73 |
+
def test_union_different_type_base(self, klass):
|
74 |
+
# GH 10149
|
75 |
+
index = Index([0, "a", 1, "b", 2, "c"])
|
76 |
+
first = index[3:]
|
77 |
+
second = index[:5]
|
78 |
+
|
79 |
+
result = first.union(klass(second.values))
|
80 |
+
|
81 |
+
assert equal_contents(result, index)
|
82 |
+
|
83 |
+
def test_union_sort_other_incomparable(self):
|
84 |
+
# https://github.com/pandas-dev/pandas/issues/24959
|
85 |
+
idx = Index([1, pd.Timestamp("2000")])
|
86 |
+
# default (sort=None)
|
87 |
+
with tm.assert_produces_warning(RuntimeWarning):
|
88 |
+
result = idx.union(idx[:1])
|
89 |
+
|
90 |
+
tm.assert_index_equal(result, idx)
|
91 |
+
|
92 |
+
# sort=None
|
93 |
+
with tm.assert_produces_warning(RuntimeWarning):
|
94 |
+
result = idx.union(idx[:1], sort=None)
|
95 |
+
tm.assert_index_equal(result, idx)
|
96 |
+
|
97 |
+
# sort=False
|
98 |
+
result = idx.union(idx[:1], sort=False)
|
99 |
+
tm.assert_index_equal(result, idx)
|
100 |
+
|
101 |
+
def test_union_sort_other_incomparable_true(self):
|
102 |
+
idx = Index([1, pd.Timestamp("2000")])
|
103 |
+
with pytest.raises(TypeError, match=".*"):
|
104 |
+
idx.union(idx[:1], sort=True)
|
105 |
+
|
106 |
+
def test_intersection_equal_sort_true(self):
|
107 |
+
idx = Index(["c", "a", "b"])
|
108 |
+
sorted_ = Index(["a", "b", "c"])
|
109 |
+
tm.assert_index_equal(idx.intersection(idx, sort=True), sorted_)
|
110 |
+
|
111 |
+
def test_intersection_base(self, sort):
|
112 |
+
# (same results for py2 and py3 but sortedness not tested elsewhere)
|
113 |
+
index = Index([0, "a", 1, "b", 2, "c"])
|
114 |
+
first = index[:5]
|
115 |
+
second = index[:3]
|
116 |
+
|
117 |
+
expected = Index([0, 1, "a"]) if sort is None else Index([0, "a", 1])
|
118 |
+
result = first.intersection(second, sort=sort)
|
119 |
+
tm.assert_index_equal(result, expected)
|
120 |
+
|
121 |
+
@pytest.mark.parametrize("klass", [np.array, Series, list])
|
122 |
+
def test_intersection_different_type_base(self, klass, sort):
|
123 |
+
# GH 10149
|
124 |
+
index = Index([0, "a", 1, "b", 2, "c"])
|
125 |
+
first = index[:5]
|
126 |
+
second = index[:3]
|
127 |
+
|
128 |
+
result = first.intersection(klass(second.values), sort=sort)
|
129 |
+
assert equal_contents(result, second)
|
130 |
+
|
131 |
+
def test_intersection_nosort(self):
|
132 |
+
result = Index(["c", "b", "a"]).intersection(["b", "a"])
|
133 |
+
expected = Index(["b", "a"])
|
134 |
+
tm.assert_index_equal(result, expected)
|
135 |
+
|
136 |
+
def test_intersection_equal_sort(self):
|
137 |
+
idx = Index(["c", "a", "b"])
|
138 |
+
tm.assert_index_equal(idx.intersection(idx, sort=False), idx)
|
139 |
+
tm.assert_index_equal(idx.intersection(idx, sort=None), idx)
|
140 |
+
|
141 |
+
def test_intersection_str_dates(self, sort):
|
142 |
+
dt_dates = [datetime(2012, 2, 9), datetime(2012, 2, 22)]
|
143 |
+
|
144 |
+
i1 = Index(dt_dates, dtype=object)
|
145 |
+
i2 = Index(["aa"], dtype=object)
|
146 |
+
result = i2.intersection(i1, sort=sort)
|
147 |
+
|
148 |
+
assert len(result) == 0
|
149 |
+
|
150 |
+
@pytest.mark.parametrize(
|
151 |
+
"index2,expected_arr",
|
152 |
+
[(Index(["B", "D"]), ["B"]), (Index(["B", "D", "A"]), ["A", "B"])],
|
153 |
+
)
|
154 |
+
def test_intersection_non_monotonic_non_unique(self, index2, expected_arr, sort):
|
155 |
+
# non-monotonic non-unique
|
156 |
+
index1 = Index(["A", "B", "A", "C"])
|
157 |
+
expected = Index(expected_arr)
|
158 |
+
result = index1.intersection(index2, sort=sort)
|
159 |
+
if sort is None:
|
160 |
+
expected = expected.sort_values()
|
161 |
+
tm.assert_index_equal(result, expected)
|
162 |
+
|
163 |
+
def test_difference_base(self, sort):
|
164 |
+
# (same results for py2 and py3 but sortedness not tested elsewhere)
|
165 |
+
index = Index([0, "a", 1, "b", 2, "c"])
|
166 |
+
first = index[:4]
|
167 |
+
second = index[3:]
|
168 |
+
|
169 |
+
result = first.difference(second, sort)
|
170 |
+
expected = Index([0, "a", 1])
|
171 |
+
if sort is None:
|
172 |
+
expected = Index(safe_sort(expected))
|
173 |
+
tm.assert_index_equal(result, expected)
|
174 |
+
|
175 |
+
def test_symmetric_difference(self):
|
176 |
+
# (same results for py2 and py3 but sortedness not tested elsewhere)
|
177 |
+
index = Index([0, "a", 1, "b", 2, "c"])
|
178 |
+
first = index[:4]
|
179 |
+
second = index[3:]
|
180 |
+
|
181 |
+
result = first.symmetric_difference(second)
|
182 |
+
expected = Index([0, 1, 2, "a", "c"])
|
183 |
+
tm.assert_index_equal(result, expected)
|
184 |
+
|
185 |
+
@pytest.mark.parametrize(
|
186 |
+
"method,expected,sort",
|
187 |
+
[
|
188 |
+
(
|
189 |
+
"intersection",
|
190 |
+
np.array(
|
191 |
+
[(1, "A"), (2, "A"), (1, "B"), (2, "B")],
|
192 |
+
dtype=[("num", int), ("let", "S1")],
|
193 |
+
),
|
194 |
+
False,
|
195 |
+
),
|
196 |
+
(
|
197 |
+
"intersection",
|
198 |
+
np.array(
|
199 |
+
[(1, "A"), (1, "B"), (2, "A"), (2, "B")],
|
200 |
+
dtype=[("num", int), ("let", "S1")],
|
201 |
+
),
|
202 |
+
None,
|
203 |
+
),
|
204 |
+
(
|
205 |
+
"union",
|
206 |
+
np.array(
|
207 |
+
[(1, "A"), (1, "B"), (1, "C"), (2, "A"), (2, "B"), (2, "C")],
|
208 |
+
dtype=[("num", int), ("let", "S1")],
|
209 |
+
),
|
210 |
+
None,
|
211 |
+
),
|
212 |
+
],
|
213 |
+
)
|
214 |
+
def test_tuple_union_bug(self, method, expected, sort):
|
215 |
+
index1 = Index(
|
216 |
+
np.array(
|
217 |
+
[(1, "A"), (2, "A"), (1, "B"), (2, "B")],
|
218 |
+
dtype=[("num", int), ("let", "S1")],
|
219 |
+
)
|
220 |
+
)
|
221 |
+
index2 = Index(
|
222 |
+
np.array(
|
223 |
+
[(1, "A"), (2, "A"), (1, "B"), (2, "B"), (1, "C"), (2, "C")],
|
224 |
+
dtype=[("num", int), ("let", "S1")],
|
225 |
+
)
|
226 |
+
)
|
227 |
+
|
228 |
+
result = getattr(index1, method)(index2, sort=sort)
|
229 |
+
assert result.ndim == 1
|
230 |
+
|
231 |
+
expected = Index(expected)
|
232 |
+
tm.assert_index_equal(result, expected)
|
233 |
+
|
234 |
+
@pytest.mark.parametrize("first_list", [["b", "a"], []])
|
235 |
+
@pytest.mark.parametrize("second_list", [["a", "b"], []])
|
236 |
+
@pytest.mark.parametrize(
|
237 |
+
"first_name, second_name, expected_name",
|
238 |
+
[("A", "B", None), (None, "B", None), ("A", None, None)],
|
239 |
+
)
|
240 |
+
def test_union_name_preservation(
|
241 |
+
self, first_list, second_list, first_name, second_name, expected_name, sort
|
242 |
+
):
|
243 |
+
first = Index(first_list, name=first_name)
|
244 |
+
second = Index(second_list, name=second_name)
|
245 |
+
union = first.union(second, sort=sort)
|
246 |
+
|
247 |
+
vals = set(first_list).union(second_list)
|
248 |
+
|
249 |
+
if sort is None and len(first_list) > 0 and len(second_list) > 0:
|
250 |
+
expected = Index(sorted(vals), name=expected_name)
|
251 |
+
tm.assert_index_equal(union, expected)
|
252 |
+
else:
|
253 |
+
expected = Index(vals, name=expected_name)
|
254 |
+
tm.assert_index_equal(union.sort_values(), expected.sort_values())
|
255 |
+
|
256 |
+
@pytest.mark.parametrize(
|
257 |
+
"diff_type, expected",
|
258 |
+
[["difference", [1, "B"]], ["symmetric_difference", [1, 2, "B", "C"]]],
|
259 |
+
)
|
260 |
+
def test_difference_object_type(self, diff_type, expected):
|
261 |
+
# GH 13432
|
262 |
+
idx1 = Index([0, 1, "A", "B"])
|
263 |
+
idx2 = Index([0, 2, "A", "C"])
|
264 |
+
result = getattr(idx1, diff_type)(idx2)
|
265 |
+
expected = Index(expected)
|
266 |
+
tm.assert_index_equal(result, expected)
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/base_class/test_where.py
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
|
3 |
+
from pandas import Index
|
4 |
+
import pandas._testing as tm
|
5 |
+
|
6 |
+
|
7 |
+
class TestWhere:
|
8 |
+
def test_where_intlike_str_doesnt_cast_ints(self):
|
9 |
+
idx = Index(range(3))
|
10 |
+
mask = np.array([True, False, True])
|
11 |
+
res = idx.where(mask, "2")
|
12 |
+
expected = Index([0, "2", 2])
|
13 |
+
tm.assert_index_equal(res, expected)
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/conftest.py
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas import (
|
5 |
+
Series,
|
6 |
+
array,
|
7 |
+
)
|
8 |
+
|
9 |
+
|
10 |
+
@pytest.fixture(params=[None, False])
|
11 |
+
def sort(request):
|
12 |
+
"""
|
13 |
+
Valid values for the 'sort' parameter used in the Index
|
14 |
+
setops methods (intersection, union, etc.)
|
15 |
+
|
16 |
+
Caution:
|
17 |
+
Don't confuse this one with the "sort" fixture used
|
18 |
+
for DataFrame.append or concat. That one has
|
19 |
+
parameters [True, False].
|
20 |
+
|
21 |
+
We can't combine them as sort=True is not permitted
|
22 |
+
in the Index setops methods.
|
23 |
+
"""
|
24 |
+
return request.param
|
25 |
+
|
26 |
+
|
27 |
+
@pytest.fixture(params=["D", "3D", "-3D", "h", "2h", "-2h", "min", "2min", "s", "-3s"])
|
28 |
+
def freq_sample(request):
|
29 |
+
"""
|
30 |
+
Valid values for 'freq' parameter used to create date_range and
|
31 |
+
timedelta_range..
|
32 |
+
"""
|
33 |
+
return request.param
|
34 |
+
|
35 |
+
|
36 |
+
@pytest.fixture(params=[list, tuple, np.array, array, Series])
|
37 |
+
def listlike_box(request):
|
38 |
+
"""
|
39 |
+
Types that may be passed as the indexer to searchsorted.
|
40 |
+
"""
|
41 |
+
return request.param
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/conftest.py
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas import (
|
5 |
+
Index,
|
6 |
+
MultiIndex,
|
7 |
+
)
|
8 |
+
|
9 |
+
|
10 |
+
# Note: identical the "multi" entry in the top-level "index" fixture
|
11 |
+
@pytest.fixture
|
12 |
+
def idx():
|
13 |
+
# a MultiIndex used to test the general functionality of the
|
14 |
+
# general functionality of this object
|
15 |
+
major_axis = Index(["foo", "bar", "baz", "qux"])
|
16 |
+
minor_axis = Index(["one", "two"])
|
17 |
+
|
18 |
+
major_codes = np.array([0, 0, 1, 2, 3, 3])
|
19 |
+
minor_codes = np.array([0, 1, 0, 1, 0, 1])
|
20 |
+
index_names = ["first", "second"]
|
21 |
+
mi = MultiIndex(
|
22 |
+
levels=[major_axis, minor_axis],
|
23 |
+
codes=[major_codes, minor_codes],
|
24 |
+
names=index_names,
|
25 |
+
verify_integrity=False,
|
26 |
+
)
|
27 |
+
return mi
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/test_astype.py
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas.core.dtypes.dtypes import CategoricalDtype
|
5 |
+
|
6 |
+
import pandas._testing as tm
|
7 |
+
|
8 |
+
|
9 |
+
def test_astype(idx):
|
10 |
+
expected = idx.copy()
|
11 |
+
actual = idx.astype("O")
|
12 |
+
tm.assert_copy(actual.levels, expected.levels)
|
13 |
+
tm.assert_copy(actual.codes, expected.codes)
|
14 |
+
assert actual.names == list(expected.names)
|
15 |
+
|
16 |
+
with pytest.raises(TypeError, match="^Setting.*dtype.*object"):
|
17 |
+
idx.astype(np.dtype(int))
|
18 |
+
|
19 |
+
|
20 |
+
@pytest.mark.parametrize("ordered", [True, False])
|
21 |
+
def test_astype_category(idx, ordered):
|
22 |
+
# GH 18630
|
23 |
+
msg = "> 1 ndim Categorical are not supported at this time"
|
24 |
+
with pytest.raises(NotImplementedError, match=msg):
|
25 |
+
idx.astype(CategoricalDtype(ordered=ordered))
|
26 |
+
|
27 |
+
if ordered is False:
|
28 |
+
# dtype='category' defaults to ordered=False, so only test once
|
29 |
+
with pytest.raises(NotImplementedError, match=msg):
|
30 |
+
idx.astype("category")
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/test_copy.py
ADDED
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from copy import (
|
2 |
+
copy,
|
3 |
+
deepcopy,
|
4 |
+
)
|
5 |
+
|
6 |
+
import pytest
|
7 |
+
|
8 |
+
from pandas import MultiIndex
|
9 |
+
import pandas._testing as tm
|
10 |
+
|
11 |
+
|
12 |
+
def assert_multiindex_copied(copy, original):
|
13 |
+
# Levels should be (at least, shallow copied)
|
14 |
+
tm.assert_copy(copy.levels, original.levels)
|
15 |
+
tm.assert_almost_equal(copy.codes, original.codes)
|
16 |
+
|
17 |
+
# Labels doesn't matter which way copied
|
18 |
+
tm.assert_almost_equal(copy.codes, original.codes)
|
19 |
+
assert copy.codes is not original.codes
|
20 |
+
|
21 |
+
# Names doesn't matter which way copied
|
22 |
+
assert copy.names == original.names
|
23 |
+
assert copy.names is not original.names
|
24 |
+
|
25 |
+
# Sort order should be copied
|
26 |
+
assert copy.sortorder == original.sortorder
|
27 |
+
|
28 |
+
|
29 |
+
def test_copy(idx):
|
30 |
+
i_copy = idx.copy()
|
31 |
+
|
32 |
+
assert_multiindex_copied(i_copy, idx)
|
33 |
+
|
34 |
+
|
35 |
+
def test_shallow_copy(idx):
|
36 |
+
i_copy = idx._view()
|
37 |
+
|
38 |
+
assert_multiindex_copied(i_copy, idx)
|
39 |
+
|
40 |
+
|
41 |
+
def test_view(idx):
|
42 |
+
i_view = idx.view()
|
43 |
+
assert_multiindex_copied(i_view, idx)
|
44 |
+
|
45 |
+
|
46 |
+
@pytest.mark.parametrize("func", [copy, deepcopy])
|
47 |
+
def test_copy_and_deepcopy(func):
|
48 |
+
idx = MultiIndex(
|
49 |
+
levels=[["foo", "bar"], ["fizz", "buzz"]],
|
50 |
+
codes=[[0, 0, 0, 1], [0, 0, 1, 1]],
|
51 |
+
names=["first", "second"],
|
52 |
+
)
|
53 |
+
idx_copy = func(idx)
|
54 |
+
assert idx_copy is not idx
|
55 |
+
assert idx_copy.equals(idx)
|
56 |
+
|
57 |
+
|
58 |
+
@pytest.mark.parametrize("deep", [True, False])
|
59 |
+
def test_copy_method(deep):
|
60 |
+
idx = MultiIndex(
|
61 |
+
levels=[["foo", "bar"], ["fizz", "buzz"]],
|
62 |
+
codes=[[0, 0, 0, 1], [0, 0, 1, 1]],
|
63 |
+
names=["first", "second"],
|
64 |
+
)
|
65 |
+
idx_copy = idx.copy(deep=deep)
|
66 |
+
assert idx_copy.equals(idx)
|
67 |
+
|
68 |
+
|
69 |
+
@pytest.mark.parametrize("deep", [True, False])
|
70 |
+
@pytest.mark.parametrize(
|
71 |
+
"kwarg, value",
|
72 |
+
[
|
73 |
+
("names", ["third", "fourth"]),
|
74 |
+
],
|
75 |
+
)
|
76 |
+
def test_copy_method_kwargs(deep, kwarg, value):
|
77 |
+
# gh-12309: Check that the "name" argument as well other kwargs are honored
|
78 |
+
idx = MultiIndex(
|
79 |
+
levels=[["foo", "bar"], ["fizz", "buzz"]],
|
80 |
+
codes=[[0, 0, 0, 1], [0, 0, 1, 1]],
|
81 |
+
names=["first", "second"],
|
82 |
+
)
|
83 |
+
idx_copy = idx.copy(**{kwarg: value, "deep": deep})
|
84 |
+
assert getattr(idx_copy, kwarg) == value
|
85 |
+
|
86 |
+
|
87 |
+
def test_copy_deep_false_retains_id():
|
88 |
+
# GH#47878
|
89 |
+
idx = MultiIndex(
|
90 |
+
levels=[["foo", "bar"], ["fizz", "buzz"]],
|
91 |
+
codes=[[0, 0, 0, 1], [0, 0, 1, 1]],
|
92 |
+
names=["first", "second"],
|
93 |
+
)
|
94 |
+
|
95 |
+
res = idx.copy(deep=False)
|
96 |
+
assert res._id is idx._id
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/test_equivalence.py
ADDED
@@ -0,0 +1,284 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas.core.dtypes.common import is_any_real_numeric_dtype
|
5 |
+
|
6 |
+
import pandas as pd
|
7 |
+
from pandas import (
|
8 |
+
Index,
|
9 |
+
MultiIndex,
|
10 |
+
Series,
|
11 |
+
)
|
12 |
+
import pandas._testing as tm
|
13 |
+
|
14 |
+
|
15 |
+
def test_equals(idx):
|
16 |
+
assert idx.equals(idx)
|
17 |
+
assert idx.equals(idx.copy())
|
18 |
+
assert idx.equals(idx.astype(object))
|
19 |
+
assert idx.equals(idx.to_flat_index())
|
20 |
+
assert idx.equals(idx.to_flat_index().astype("category"))
|
21 |
+
|
22 |
+
assert not idx.equals(list(idx))
|
23 |
+
assert not idx.equals(np.array(idx))
|
24 |
+
|
25 |
+
same_values = Index(idx, dtype=object)
|
26 |
+
assert idx.equals(same_values)
|
27 |
+
assert same_values.equals(idx)
|
28 |
+
|
29 |
+
if idx.nlevels == 1:
|
30 |
+
# do not test MultiIndex
|
31 |
+
assert not idx.equals(Series(idx))
|
32 |
+
|
33 |
+
|
34 |
+
def test_equals_op(idx):
|
35 |
+
# GH9947, GH10637
|
36 |
+
index_a = idx
|
37 |
+
|
38 |
+
n = len(index_a)
|
39 |
+
index_b = index_a[0:-1]
|
40 |
+
index_c = index_a[0:-1].append(index_a[-2:-1])
|
41 |
+
index_d = index_a[0:1]
|
42 |
+
with pytest.raises(ValueError, match="Lengths must match"):
|
43 |
+
index_a == index_b
|
44 |
+
expected1 = np.array([True] * n)
|
45 |
+
expected2 = np.array([True] * (n - 1) + [False])
|
46 |
+
tm.assert_numpy_array_equal(index_a == index_a, expected1)
|
47 |
+
tm.assert_numpy_array_equal(index_a == index_c, expected2)
|
48 |
+
|
49 |
+
# test comparisons with numpy arrays
|
50 |
+
array_a = np.array(index_a)
|
51 |
+
array_b = np.array(index_a[0:-1])
|
52 |
+
array_c = np.array(index_a[0:-1].append(index_a[-2:-1]))
|
53 |
+
array_d = np.array(index_a[0:1])
|
54 |
+
with pytest.raises(ValueError, match="Lengths must match"):
|
55 |
+
index_a == array_b
|
56 |
+
tm.assert_numpy_array_equal(index_a == array_a, expected1)
|
57 |
+
tm.assert_numpy_array_equal(index_a == array_c, expected2)
|
58 |
+
|
59 |
+
# test comparisons with Series
|
60 |
+
series_a = Series(array_a)
|
61 |
+
series_b = Series(array_b)
|
62 |
+
series_c = Series(array_c)
|
63 |
+
series_d = Series(array_d)
|
64 |
+
with pytest.raises(ValueError, match="Lengths must match"):
|
65 |
+
index_a == series_b
|
66 |
+
|
67 |
+
tm.assert_numpy_array_equal(index_a == series_a, expected1)
|
68 |
+
tm.assert_numpy_array_equal(index_a == series_c, expected2)
|
69 |
+
|
70 |
+
# cases where length is 1 for one of them
|
71 |
+
with pytest.raises(ValueError, match="Lengths must match"):
|
72 |
+
index_a == index_d
|
73 |
+
with pytest.raises(ValueError, match="Lengths must match"):
|
74 |
+
index_a == series_d
|
75 |
+
with pytest.raises(ValueError, match="Lengths must match"):
|
76 |
+
index_a == array_d
|
77 |
+
msg = "Can only compare identically-labeled Series objects"
|
78 |
+
with pytest.raises(ValueError, match=msg):
|
79 |
+
series_a == series_d
|
80 |
+
with pytest.raises(ValueError, match="Lengths must match"):
|
81 |
+
series_a == array_d
|
82 |
+
|
83 |
+
# comparing with a scalar should broadcast; note that we are excluding
|
84 |
+
# MultiIndex because in this case each item in the index is a tuple of
|
85 |
+
# length 2, and therefore is considered an array of length 2 in the
|
86 |
+
# comparison instead of a scalar
|
87 |
+
if not isinstance(index_a, MultiIndex):
|
88 |
+
expected3 = np.array([False] * (len(index_a) - 2) + [True, False])
|
89 |
+
# assuming the 2nd to last item is unique in the data
|
90 |
+
item = index_a[-2]
|
91 |
+
tm.assert_numpy_array_equal(index_a == item, expected3)
|
92 |
+
tm.assert_series_equal(series_a == item, Series(expected3))
|
93 |
+
|
94 |
+
|
95 |
+
def test_compare_tuple():
|
96 |
+
# GH#21517
|
97 |
+
mi = MultiIndex.from_product([[1, 2]] * 2)
|
98 |
+
|
99 |
+
all_false = np.array([False, False, False, False])
|
100 |
+
|
101 |
+
result = mi == mi[0]
|
102 |
+
expected = np.array([True, False, False, False])
|
103 |
+
tm.assert_numpy_array_equal(result, expected)
|
104 |
+
|
105 |
+
result = mi != mi[0]
|
106 |
+
tm.assert_numpy_array_equal(result, ~expected)
|
107 |
+
|
108 |
+
result = mi < mi[0]
|
109 |
+
tm.assert_numpy_array_equal(result, all_false)
|
110 |
+
|
111 |
+
result = mi <= mi[0]
|
112 |
+
tm.assert_numpy_array_equal(result, expected)
|
113 |
+
|
114 |
+
result = mi > mi[0]
|
115 |
+
tm.assert_numpy_array_equal(result, ~expected)
|
116 |
+
|
117 |
+
result = mi >= mi[0]
|
118 |
+
tm.assert_numpy_array_equal(result, ~all_false)
|
119 |
+
|
120 |
+
|
121 |
+
def test_compare_tuple_strs():
|
122 |
+
# GH#34180
|
123 |
+
|
124 |
+
mi = MultiIndex.from_tuples([("a", "b"), ("b", "c"), ("c", "a")])
|
125 |
+
|
126 |
+
result = mi == ("c", "a")
|
127 |
+
expected = np.array([False, False, True])
|
128 |
+
tm.assert_numpy_array_equal(result, expected)
|
129 |
+
|
130 |
+
result = mi == ("c",)
|
131 |
+
expected = np.array([False, False, False])
|
132 |
+
tm.assert_numpy_array_equal(result, expected)
|
133 |
+
|
134 |
+
|
135 |
+
def test_equals_multi(idx):
|
136 |
+
assert idx.equals(idx)
|
137 |
+
assert not idx.equals(idx.values)
|
138 |
+
assert idx.equals(Index(idx.values))
|
139 |
+
|
140 |
+
assert idx.equal_levels(idx)
|
141 |
+
assert not idx.equals(idx[:-1])
|
142 |
+
assert not idx.equals(idx[-1])
|
143 |
+
|
144 |
+
# different number of levels
|
145 |
+
index = MultiIndex(
|
146 |
+
levels=[Index(list(range(4))), Index(list(range(4))), Index(list(range(4)))],
|
147 |
+
codes=[
|
148 |
+
np.array([0, 0, 1, 2, 2, 2, 3, 3]),
|
149 |
+
np.array([0, 1, 0, 0, 0, 1, 0, 1]),
|
150 |
+
np.array([1, 0, 1, 1, 0, 0, 1, 0]),
|
151 |
+
],
|
152 |
+
)
|
153 |
+
|
154 |
+
index2 = MultiIndex(levels=index.levels[:-1], codes=index.codes[:-1])
|
155 |
+
assert not index.equals(index2)
|
156 |
+
assert not index.equal_levels(index2)
|
157 |
+
|
158 |
+
# levels are different
|
159 |
+
major_axis = Index(list(range(4)))
|
160 |
+
minor_axis = Index(list(range(2)))
|
161 |
+
|
162 |
+
major_codes = np.array([0, 0, 1, 2, 2, 3])
|
163 |
+
minor_codes = np.array([0, 1, 0, 0, 1, 0])
|
164 |
+
|
165 |
+
index = MultiIndex(
|
166 |
+
levels=[major_axis, minor_axis], codes=[major_codes, minor_codes]
|
167 |
+
)
|
168 |
+
assert not idx.equals(index)
|
169 |
+
assert not idx.equal_levels(index)
|
170 |
+
|
171 |
+
# some of the labels are different
|
172 |
+
major_axis = Index(["foo", "bar", "baz", "qux"])
|
173 |
+
minor_axis = Index(["one", "two"])
|
174 |
+
|
175 |
+
major_codes = np.array([0, 0, 2, 2, 3, 3])
|
176 |
+
minor_codes = np.array([0, 1, 0, 1, 0, 1])
|
177 |
+
|
178 |
+
index = MultiIndex(
|
179 |
+
levels=[major_axis, minor_axis], codes=[major_codes, minor_codes]
|
180 |
+
)
|
181 |
+
assert not idx.equals(index)
|
182 |
+
|
183 |
+
|
184 |
+
def test_identical(idx):
|
185 |
+
mi = idx.copy()
|
186 |
+
mi2 = idx.copy()
|
187 |
+
assert mi.identical(mi2)
|
188 |
+
|
189 |
+
mi = mi.set_names(["new1", "new2"])
|
190 |
+
assert mi.equals(mi2)
|
191 |
+
assert not mi.identical(mi2)
|
192 |
+
|
193 |
+
mi2 = mi2.set_names(["new1", "new2"])
|
194 |
+
assert mi.identical(mi2)
|
195 |
+
|
196 |
+
mi4 = Index(mi.tolist(), tupleize_cols=False)
|
197 |
+
assert not mi.identical(mi4)
|
198 |
+
assert mi.equals(mi4)
|
199 |
+
|
200 |
+
|
201 |
+
def test_equals_operator(idx):
|
202 |
+
# GH9785
|
203 |
+
assert (idx == idx).all()
|
204 |
+
|
205 |
+
|
206 |
+
def test_equals_missing_values():
|
207 |
+
# make sure take is not using -1
|
208 |
+
i = MultiIndex.from_tuples([(0, pd.NaT), (0, pd.Timestamp("20130101"))])
|
209 |
+
result = i[0:1].equals(i[0])
|
210 |
+
assert not result
|
211 |
+
result = i[1:2].equals(i[1])
|
212 |
+
assert not result
|
213 |
+
|
214 |
+
|
215 |
+
def test_equals_missing_values_differently_sorted():
|
216 |
+
# GH#38439
|
217 |
+
mi1 = MultiIndex.from_tuples([(81.0, np.nan), (np.nan, np.nan)])
|
218 |
+
mi2 = MultiIndex.from_tuples([(np.nan, np.nan), (81.0, np.nan)])
|
219 |
+
assert not mi1.equals(mi2)
|
220 |
+
|
221 |
+
mi2 = MultiIndex.from_tuples([(81.0, np.nan), (np.nan, np.nan)])
|
222 |
+
assert mi1.equals(mi2)
|
223 |
+
|
224 |
+
|
225 |
+
def test_is_():
|
226 |
+
mi = MultiIndex.from_tuples(zip(range(10), range(10)))
|
227 |
+
assert mi.is_(mi)
|
228 |
+
assert mi.is_(mi.view())
|
229 |
+
assert mi.is_(mi.view().view().view().view())
|
230 |
+
mi2 = mi.view()
|
231 |
+
# names are metadata, they don't change id
|
232 |
+
mi2.names = ["A", "B"]
|
233 |
+
assert mi2.is_(mi)
|
234 |
+
assert mi.is_(mi2)
|
235 |
+
|
236 |
+
assert not mi.is_(mi.set_names(["C", "D"]))
|
237 |
+
# levels are inherent properties, they change identity
|
238 |
+
mi3 = mi2.set_levels([list(range(10)), list(range(10))])
|
239 |
+
assert not mi3.is_(mi2)
|
240 |
+
# shouldn't change
|
241 |
+
assert mi2.is_(mi)
|
242 |
+
mi4 = mi3.view()
|
243 |
+
|
244 |
+
# GH 17464 - Remove duplicate MultiIndex levels
|
245 |
+
mi4 = mi4.set_levels([list(range(10)), list(range(10))])
|
246 |
+
assert not mi4.is_(mi3)
|
247 |
+
mi5 = mi.view()
|
248 |
+
mi5 = mi5.set_levels(mi5.levels)
|
249 |
+
assert not mi5.is_(mi)
|
250 |
+
|
251 |
+
|
252 |
+
def test_is_all_dates(idx):
|
253 |
+
assert not idx._is_all_dates
|
254 |
+
|
255 |
+
|
256 |
+
def test_is_numeric(idx):
|
257 |
+
# MultiIndex is never numeric
|
258 |
+
assert not is_any_real_numeric_dtype(idx)
|
259 |
+
|
260 |
+
|
261 |
+
def test_multiindex_compare():
|
262 |
+
# GH 21149
|
263 |
+
# Ensure comparison operations for MultiIndex with nlevels == 1
|
264 |
+
# behave consistently with those for MultiIndex with nlevels > 1
|
265 |
+
|
266 |
+
midx = MultiIndex.from_product([[0, 1]])
|
267 |
+
|
268 |
+
# Equality self-test: MultiIndex object vs self
|
269 |
+
expected = Series([True, True])
|
270 |
+
result = Series(midx == midx)
|
271 |
+
tm.assert_series_equal(result, expected)
|
272 |
+
|
273 |
+
# Greater than comparison: MultiIndex object vs self
|
274 |
+
expected = Series([False, False])
|
275 |
+
result = Series(midx > midx)
|
276 |
+
tm.assert_series_equal(result, expected)
|
277 |
+
|
278 |
+
|
279 |
+
def test_equals_ea_int_regular_int():
|
280 |
+
# GH#46026
|
281 |
+
mi1 = MultiIndex.from_arrays([Index([1, 2], dtype="Int64"), [3, 4]])
|
282 |
+
mi2 = MultiIndex.from_arrays([[1, 2], [3, 4]])
|
283 |
+
assert not mi1.equals(mi2)
|
284 |
+
assert not mi2.equals(mi1)
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/test_get_set.py
ADDED
@@ -0,0 +1,384 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas.compat import PY311
|
5 |
+
|
6 |
+
from pandas.core.dtypes.dtypes import DatetimeTZDtype
|
7 |
+
|
8 |
+
import pandas as pd
|
9 |
+
from pandas import (
|
10 |
+
CategoricalIndex,
|
11 |
+
MultiIndex,
|
12 |
+
)
|
13 |
+
import pandas._testing as tm
|
14 |
+
|
15 |
+
|
16 |
+
def assert_matching(actual, expected, check_dtype=False):
|
17 |
+
# avoid specifying internal representation
|
18 |
+
# as much as possible
|
19 |
+
assert len(actual) == len(expected)
|
20 |
+
for act, exp in zip(actual, expected):
|
21 |
+
act = np.asarray(act)
|
22 |
+
exp = np.asarray(exp)
|
23 |
+
tm.assert_numpy_array_equal(act, exp, check_dtype=check_dtype)
|
24 |
+
|
25 |
+
|
26 |
+
def test_get_level_number_integer(idx):
|
27 |
+
idx.names = [1, 0]
|
28 |
+
assert idx._get_level_number(1) == 0
|
29 |
+
assert idx._get_level_number(0) == 1
|
30 |
+
msg = "Too many levels: Index has only 2 levels, not 3"
|
31 |
+
with pytest.raises(IndexError, match=msg):
|
32 |
+
idx._get_level_number(2)
|
33 |
+
with pytest.raises(KeyError, match="Level fourth not found"):
|
34 |
+
idx._get_level_number("fourth")
|
35 |
+
|
36 |
+
|
37 |
+
def test_get_dtypes(using_infer_string):
|
38 |
+
# Test MultiIndex.dtypes (# Gh37062)
|
39 |
+
idx_multitype = MultiIndex.from_product(
|
40 |
+
[[1, 2, 3], ["a", "b", "c"], pd.date_range("20200101", periods=2, tz="UTC")],
|
41 |
+
names=["int", "string", "dt"],
|
42 |
+
)
|
43 |
+
|
44 |
+
exp = "object" if not using_infer_string else "string"
|
45 |
+
expected = pd.Series(
|
46 |
+
{
|
47 |
+
"int": np.dtype("int64"),
|
48 |
+
"string": exp,
|
49 |
+
"dt": DatetimeTZDtype(tz="utc"),
|
50 |
+
}
|
51 |
+
)
|
52 |
+
tm.assert_series_equal(expected, idx_multitype.dtypes)
|
53 |
+
|
54 |
+
|
55 |
+
def test_get_dtypes_no_level_name(using_infer_string):
|
56 |
+
# Test MultiIndex.dtypes (# GH38580 )
|
57 |
+
idx_multitype = MultiIndex.from_product(
|
58 |
+
[
|
59 |
+
[1, 2, 3],
|
60 |
+
["a", "b", "c"],
|
61 |
+
pd.date_range("20200101", periods=2, tz="UTC"),
|
62 |
+
],
|
63 |
+
)
|
64 |
+
exp = "object" if not using_infer_string else "string"
|
65 |
+
expected = pd.Series(
|
66 |
+
{
|
67 |
+
"level_0": np.dtype("int64"),
|
68 |
+
"level_1": exp,
|
69 |
+
"level_2": DatetimeTZDtype(tz="utc"),
|
70 |
+
}
|
71 |
+
)
|
72 |
+
tm.assert_series_equal(expected, idx_multitype.dtypes)
|
73 |
+
|
74 |
+
|
75 |
+
def test_get_dtypes_duplicate_level_names(using_infer_string):
|
76 |
+
# Test MultiIndex.dtypes with non-unique level names (# GH45174)
|
77 |
+
result = MultiIndex.from_product(
|
78 |
+
[
|
79 |
+
[1, 2, 3],
|
80 |
+
["a", "b", "c"],
|
81 |
+
pd.date_range("20200101", periods=2, tz="UTC"),
|
82 |
+
],
|
83 |
+
names=["A", "A", "A"],
|
84 |
+
).dtypes
|
85 |
+
exp = "object" if not using_infer_string else "string"
|
86 |
+
expected = pd.Series(
|
87 |
+
[np.dtype("int64"), exp, DatetimeTZDtype(tz="utc")],
|
88 |
+
index=["A", "A", "A"],
|
89 |
+
)
|
90 |
+
tm.assert_series_equal(result, expected)
|
91 |
+
|
92 |
+
|
93 |
+
def test_get_level_number_out_of_bounds(multiindex_dataframe_random_data):
|
94 |
+
frame = multiindex_dataframe_random_data
|
95 |
+
|
96 |
+
with pytest.raises(IndexError, match="Too many levels"):
|
97 |
+
frame.index._get_level_number(2)
|
98 |
+
with pytest.raises(IndexError, match="not a valid level number"):
|
99 |
+
frame.index._get_level_number(-3)
|
100 |
+
|
101 |
+
|
102 |
+
def test_set_name_methods(idx):
|
103 |
+
# so long as these are synonyms, we don't need to test set_names
|
104 |
+
index_names = ["first", "second"]
|
105 |
+
assert idx.rename == idx.set_names
|
106 |
+
new_names = [name + "SUFFIX" for name in index_names]
|
107 |
+
ind = idx.set_names(new_names)
|
108 |
+
assert idx.names == index_names
|
109 |
+
assert ind.names == new_names
|
110 |
+
msg = "Length of names must match number of levels in MultiIndex"
|
111 |
+
with pytest.raises(ValueError, match=msg):
|
112 |
+
ind.set_names(new_names + new_names)
|
113 |
+
new_names2 = [name + "SUFFIX2" for name in new_names]
|
114 |
+
res = ind.set_names(new_names2, inplace=True)
|
115 |
+
assert res is None
|
116 |
+
assert ind.names == new_names2
|
117 |
+
|
118 |
+
# set names for specific level (# GH7792)
|
119 |
+
ind = idx.set_names(new_names[0], level=0)
|
120 |
+
assert idx.names == index_names
|
121 |
+
assert ind.names == [new_names[0], index_names[1]]
|
122 |
+
|
123 |
+
res = ind.set_names(new_names2[0], level=0, inplace=True)
|
124 |
+
assert res is None
|
125 |
+
assert ind.names == [new_names2[0], index_names[1]]
|
126 |
+
|
127 |
+
# set names for multiple levels
|
128 |
+
ind = idx.set_names(new_names, level=[0, 1])
|
129 |
+
assert idx.names == index_names
|
130 |
+
assert ind.names == new_names
|
131 |
+
|
132 |
+
res = ind.set_names(new_names2, level=[0, 1], inplace=True)
|
133 |
+
assert res is None
|
134 |
+
assert ind.names == new_names2
|
135 |
+
|
136 |
+
|
137 |
+
def test_set_levels_codes_directly(idx):
|
138 |
+
# setting levels/codes directly raises AttributeError
|
139 |
+
|
140 |
+
levels = idx.levels
|
141 |
+
new_levels = [[lev + "a" for lev in level] for level in levels]
|
142 |
+
|
143 |
+
codes = idx.codes
|
144 |
+
major_codes, minor_codes = codes
|
145 |
+
major_codes = [(x + 1) % 3 for x in major_codes]
|
146 |
+
minor_codes = [(x + 1) % 1 for x in minor_codes]
|
147 |
+
new_codes = [major_codes, minor_codes]
|
148 |
+
|
149 |
+
msg = "Can't set attribute"
|
150 |
+
with pytest.raises(AttributeError, match=msg):
|
151 |
+
idx.levels = new_levels
|
152 |
+
|
153 |
+
msg = (
|
154 |
+
"property 'codes' of 'MultiIndex' object has no setter"
|
155 |
+
if PY311
|
156 |
+
else "can't set attribute"
|
157 |
+
)
|
158 |
+
with pytest.raises(AttributeError, match=msg):
|
159 |
+
idx.codes = new_codes
|
160 |
+
|
161 |
+
|
162 |
+
def test_set_levels(idx):
|
163 |
+
# side note - you probably wouldn't want to use levels and codes
|
164 |
+
# directly like this - but it is possible.
|
165 |
+
levels = idx.levels
|
166 |
+
new_levels = [[lev + "a" for lev in level] for level in levels]
|
167 |
+
|
168 |
+
# level changing [w/o mutation]
|
169 |
+
ind2 = idx.set_levels(new_levels)
|
170 |
+
assert_matching(ind2.levels, new_levels)
|
171 |
+
assert_matching(idx.levels, levels)
|
172 |
+
|
173 |
+
# level changing specific level [w/o mutation]
|
174 |
+
ind2 = idx.set_levels(new_levels[0], level=0)
|
175 |
+
assert_matching(ind2.levels, [new_levels[0], levels[1]])
|
176 |
+
assert_matching(idx.levels, levels)
|
177 |
+
|
178 |
+
ind2 = idx.set_levels(new_levels[1], level=1)
|
179 |
+
assert_matching(ind2.levels, [levels[0], new_levels[1]])
|
180 |
+
assert_matching(idx.levels, levels)
|
181 |
+
|
182 |
+
# level changing multiple levels [w/o mutation]
|
183 |
+
ind2 = idx.set_levels(new_levels, level=[0, 1])
|
184 |
+
assert_matching(ind2.levels, new_levels)
|
185 |
+
assert_matching(idx.levels, levels)
|
186 |
+
|
187 |
+
# illegal level changing should not change levels
|
188 |
+
# GH 13754
|
189 |
+
original_index = idx.copy()
|
190 |
+
with pytest.raises(ValueError, match="^On"):
|
191 |
+
idx.set_levels(["c"], level=0)
|
192 |
+
assert_matching(idx.levels, original_index.levels, check_dtype=True)
|
193 |
+
|
194 |
+
with pytest.raises(ValueError, match="^On"):
|
195 |
+
idx.set_codes([0, 1, 2, 3, 4, 5], level=0)
|
196 |
+
assert_matching(idx.codes, original_index.codes, check_dtype=True)
|
197 |
+
|
198 |
+
with pytest.raises(TypeError, match="^Levels"):
|
199 |
+
idx.set_levels("c", level=0)
|
200 |
+
assert_matching(idx.levels, original_index.levels, check_dtype=True)
|
201 |
+
|
202 |
+
with pytest.raises(TypeError, match="^Codes"):
|
203 |
+
idx.set_codes(1, level=0)
|
204 |
+
assert_matching(idx.codes, original_index.codes, check_dtype=True)
|
205 |
+
|
206 |
+
|
207 |
+
def test_set_codes(idx):
|
208 |
+
# side note - you probably wouldn't want to use levels and codes
|
209 |
+
# directly like this - but it is possible.
|
210 |
+
codes = idx.codes
|
211 |
+
major_codes, minor_codes = codes
|
212 |
+
major_codes = [(x + 1) % 3 for x in major_codes]
|
213 |
+
minor_codes = [(x + 1) % 1 for x in minor_codes]
|
214 |
+
new_codes = [major_codes, minor_codes]
|
215 |
+
|
216 |
+
# changing codes w/o mutation
|
217 |
+
ind2 = idx.set_codes(new_codes)
|
218 |
+
assert_matching(ind2.codes, new_codes)
|
219 |
+
assert_matching(idx.codes, codes)
|
220 |
+
|
221 |
+
# codes changing specific level w/o mutation
|
222 |
+
ind2 = idx.set_codes(new_codes[0], level=0)
|
223 |
+
assert_matching(ind2.codes, [new_codes[0], codes[1]])
|
224 |
+
assert_matching(idx.codes, codes)
|
225 |
+
|
226 |
+
ind2 = idx.set_codes(new_codes[1], level=1)
|
227 |
+
assert_matching(ind2.codes, [codes[0], new_codes[1]])
|
228 |
+
assert_matching(idx.codes, codes)
|
229 |
+
|
230 |
+
# codes changing multiple levels w/o mutation
|
231 |
+
ind2 = idx.set_codes(new_codes, level=[0, 1])
|
232 |
+
assert_matching(ind2.codes, new_codes)
|
233 |
+
assert_matching(idx.codes, codes)
|
234 |
+
|
235 |
+
# label changing for levels of different magnitude of categories
|
236 |
+
ind = MultiIndex.from_tuples([(0, i) for i in range(130)])
|
237 |
+
new_codes = range(129, -1, -1)
|
238 |
+
expected = MultiIndex.from_tuples([(0, i) for i in new_codes])
|
239 |
+
|
240 |
+
# [w/o mutation]
|
241 |
+
result = ind.set_codes(codes=new_codes, level=1)
|
242 |
+
assert result.equals(expected)
|
243 |
+
|
244 |
+
|
245 |
+
def test_set_levels_codes_names_bad_input(idx):
|
246 |
+
levels, codes = idx.levels, idx.codes
|
247 |
+
names = idx.names
|
248 |
+
|
249 |
+
with pytest.raises(ValueError, match="Length of levels"):
|
250 |
+
idx.set_levels([levels[0]])
|
251 |
+
|
252 |
+
with pytest.raises(ValueError, match="Length of codes"):
|
253 |
+
idx.set_codes([codes[0]])
|
254 |
+
|
255 |
+
with pytest.raises(ValueError, match="Length of names"):
|
256 |
+
idx.set_names([names[0]])
|
257 |
+
|
258 |
+
# shouldn't scalar data error, instead should demand list-like
|
259 |
+
with pytest.raises(TypeError, match="list of lists-like"):
|
260 |
+
idx.set_levels(levels[0])
|
261 |
+
|
262 |
+
# shouldn't scalar data error, instead should demand list-like
|
263 |
+
with pytest.raises(TypeError, match="list of lists-like"):
|
264 |
+
idx.set_codes(codes[0])
|
265 |
+
|
266 |
+
# shouldn't scalar data error, instead should demand list-like
|
267 |
+
with pytest.raises(TypeError, match="list-like"):
|
268 |
+
idx.set_names(names[0])
|
269 |
+
|
270 |
+
# should have equal lengths
|
271 |
+
with pytest.raises(TypeError, match="list of lists-like"):
|
272 |
+
idx.set_levels(levels[0], level=[0, 1])
|
273 |
+
|
274 |
+
with pytest.raises(TypeError, match="list-like"):
|
275 |
+
idx.set_levels(levels, level=0)
|
276 |
+
|
277 |
+
# should have equal lengths
|
278 |
+
with pytest.raises(TypeError, match="list of lists-like"):
|
279 |
+
idx.set_codes(codes[0], level=[0, 1])
|
280 |
+
|
281 |
+
with pytest.raises(TypeError, match="list-like"):
|
282 |
+
idx.set_codes(codes, level=0)
|
283 |
+
|
284 |
+
# should have equal lengths
|
285 |
+
with pytest.raises(ValueError, match="Length of names"):
|
286 |
+
idx.set_names(names[0], level=[0, 1])
|
287 |
+
|
288 |
+
with pytest.raises(TypeError, match="Names must be a"):
|
289 |
+
idx.set_names(names, level=0)
|
290 |
+
|
291 |
+
|
292 |
+
@pytest.mark.parametrize("inplace", [True, False])
|
293 |
+
def test_set_names_with_nlevel_1(inplace):
|
294 |
+
# GH 21149
|
295 |
+
# Ensure that .set_names for MultiIndex with
|
296 |
+
# nlevels == 1 does not raise any errors
|
297 |
+
expected = MultiIndex(levels=[[0, 1]], codes=[[0, 1]], names=["first"])
|
298 |
+
m = MultiIndex.from_product([[0, 1]])
|
299 |
+
result = m.set_names("first", level=0, inplace=inplace)
|
300 |
+
|
301 |
+
if inplace:
|
302 |
+
result = m
|
303 |
+
|
304 |
+
tm.assert_index_equal(result, expected)
|
305 |
+
|
306 |
+
|
307 |
+
@pytest.mark.parametrize("ordered", [True, False])
|
308 |
+
def test_set_levels_categorical(ordered):
|
309 |
+
# GH13854
|
310 |
+
index = MultiIndex.from_arrays([list("xyzx"), [0, 1, 2, 3]])
|
311 |
+
|
312 |
+
cidx = CategoricalIndex(list("bac"), ordered=ordered)
|
313 |
+
result = index.set_levels(cidx, level=0)
|
314 |
+
expected = MultiIndex(levels=[cidx, [0, 1, 2, 3]], codes=index.codes)
|
315 |
+
tm.assert_index_equal(result, expected)
|
316 |
+
|
317 |
+
result_lvl = result.get_level_values(0)
|
318 |
+
expected_lvl = CategoricalIndex(
|
319 |
+
list("bacb"), categories=cidx.categories, ordered=cidx.ordered
|
320 |
+
)
|
321 |
+
tm.assert_index_equal(result_lvl, expected_lvl)
|
322 |
+
|
323 |
+
|
324 |
+
def test_set_value_keeps_names():
|
325 |
+
# motivating example from #3742
|
326 |
+
lev1 = ["hans", "hans", "hans", "grethe", "grethe", "grethe"]
|
327 |
+
lev2 = ["1", "2", "3"] * 2
|
328 |
+
idx = MultiIndex.from_arrays([lev1, lev2], names=["Name", "Number"])
|
329 |
+
df = pd.DataFrame(
|
330 |
+
np.random.default_rng(2).standard_normal((6, 4)),
|
331 |
+
columns=["one", "two", "three", "four"],
|
332 |
+
index=idx,
|
333 |
+
)
|
334 |
+
df = df.sort_index()
|
335 |
+
assert df._is_copy is None
|
336 |
+
assert df.index.names == ("Name", "Number")
|
337 |
+
df.at[("grethe", "4"), "one"] = 99.34
|
338 |
+
assert df._is_copy is None
|
339 |
+
assert df.index.names == ("Name", "Number")
|
340 |
+
|
341 |
+
|
342 |
+
def test_set_levels_with_iterable():
|
343 |
+
# GH23273
|
344 |
+
sizes = [1, 2, 3]
|
345 |
+
colors = ["black"] * 3
|
346 |
+
index = MultiIndex.from_arrays([sizes, colors], names=["size", "color"])
|
347 |
+
|
348 |
+
result = index.set_levels(map(int, ["3", "2", "1"]), level="size")
|
349 |
+
|
350 |
+
expected_sizes = [3, 2, 1]
|
351 |
+
expected = MultiIndex.from_arrays([expected_sizes, colors], names=["size", "color"])
|
352 |
+
tm.assert_index_equal(result, expected)
|
353 |
+
|
354 |
+
|
355 |
+
def test_set_empty_level():
|
356 |
+
# GH#48636
|
357 |
+
midx = MultiIndex.from_arrays([[]], names=["A"])
|
358 |
+
result = midx.set_levels(pd.DatetimeIndex([]), level=0)
|
359 |
+
expected = MultiIndex.from_arrays([pd.DatetimeIndex([])], names=["A"])
|
360 |
+
tm.assert_index_equal(result, expected)
|
361 |
+
|
362 |
+
|
363 |
+
def test_set_levels_pos_args_removal():
|
364 |
+
# https://github.com/pandas-dev/pandas/issues/41485
|
365 |
+
idx = MultiIndex.from_tuples(
|
366 |
+
[
|
367 |
+
(1, "one"),
|
368 |
+
(3, "one"),
|
369 |
+
],
|
370 |
+
names=["foo", "bar"],
|
371 |
+
)
|
372 |
+
with pytest.raises(TypeError, match="positional arguments"):
|
373 |
+
idx.set_levels(["a", "b", "c"], 0)
|
374 |
+
|
375 |
+
with pytest.raises(TypeError, match="positional arguments"):
|
376 |
+
idx.set_codes([[0, 1], [1, 0]], 0)
|
377 |
+
|
378 |
+
|
379 |
+
def test_set_levels_categorical_keep_dtype():
|
380 |
+
# GH#52125
|
381 |
+
midx = MultiIndex.from_arrays([[5, 6]])
|
382 |
+
result = midx.set_levels(levels=pd.Categorical([1, 2]), level=0)
|
383 |
+
expected = MultiIndex.from_arrays([pd.Categorical([1, 2])])
|
384 |
+
tm.assert_index_equal(result, expected)
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/test_indexing.py
ADDED
@@ -0,0 +1,1001 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from datetime import timedelta
|
2 |
+
import re
|
3 |
+
|
4 |
+
import numpy as np
|
5 |
+
import pytest
|
6 |
+
|
7 |
+
from pandas._libs import index as libindex
|
8 |
+
from pandas.errors import (
|
9 |
+
InvalidIndexError,
|
10 |
+
PerformanceWarning,
|
11 |
+
)
|
12 |
+
|
13 |
+
import pandas as pd
|
14 |
+
from pandas import (
|
15 |
+
Categorical,
|
16 |
+
DataFrame,
|
17 |
+
Index,
|
18 |
+
MultiIndex,
|
19 |
+
date_range,
|
20 |
+
)
|
21 |
+
import pandas._testing as tm
|
22 |
+
|
23 |
+
|
24 |
+
class TestSliceLocs:
|
25 |
+
def test_slice_locs_partial(self, idx):
|
26 |
+
sorted_idx, _ = idx.sortlevel(0)
|
27 |
+
|
28 |
+
result = sorted_idx.slice_locs(("foo", "two"), ("qux", "one"))
|
29 |
+
assert result == (1, 5)
|
30 |
+
|
31 |
+
result = sorted_idx.slice_locs(None, ("qux", "one"))
|
32 |
+
assert result == (0, 5)
|
33 |
+
|
34 |
+
result = sorted_idx.slice_locs(("foo", "two"), None)
|
35 |
+
assert result == (1, len(sorted_idx))
|
36 |
+
|
37 |
+
result = sorted_idx.slice_locs("bar", "baz")
|
38 |
+
assert result == (2, 4)
|
39 |
+
|
40 |
+
def test_slice_locs(self):
|
41 |
+
df = DataFrame(
|
42 |
+
np.random.default_rng(2).standard_normal((50, 4)),
|
43 |
+
columns=Index(list("ABCD"), dtype=object),
|
44 |
+
index=date_range("2000-01-01", periods=50, freq="B"),
|
45 |
+
)
|
46 |
+
stacked = df.stack(future_stack=True)
|
47 |
+
idx = stacked.index
|
48 |
+
|
49 |
+
slob = slice(*idx.slice_locs(df.index[5], df.index[15]))
|
50 |
+
sliced = stacked[slob]
|
51 |
+
expected = df[5:16].stack(future_stack=True)
|
52 |
+
tm.assert_almost_equal(sliced.values, expected.values)
|
53 |
+
|
54 |
+
slob = slice(
|
55 |
+
*idx.slice_locs(
|
56 |
+
df.index[5] + timedelta(seconds=30),
|
57 |
+
df.index[15] - timedelta(seconds=30),
|
58 |
+
)
|
59 |
+
)
|
60 |
+
sliced = stacked[slob]
|
61 |
+
expected = df[6:15].stack(future_stack=True)
|
62 |
+
tm.assert_almost_equal(sliced.values, expected.values)
|
63 |
+
|
64 |
+
def test_slice_locs_with_type_mismatch(self):
|
65 |
+
df = DataFrame(
|
66 |
+
np.random.default_rng(2).standard_normal((10, 4)),
|
67 |
+
columns=Index(list("ABCD"), dtype=object),
|
68 |
+
index=date_range("2000-01-01", periods=10, freq="B"),
|
69 |
+
)
|
70 |
+
stacked = df.stack(future_stack=True)
|
71 |
+
idx = stacked.index
|
72 |
+
with pytest.raises(TypeError, match="^Level type mismatch"):
|
73 |
+
idx.slice_locs((1, 3))
|
74 |
+
with pytest.raises(TypeError, match="^Level type mismatch"):
|
75 |
+
idx.slice_locs(df.index[5] + timedelta(seconds=30), (5, 2))
|
76 |
+
df = DataFrame(
|
77 |
+
np.ones((5, 5)),
|
78 |
+
index=Index([f"i-{i}" for i in range(5)], name="a"),
|
79 |
+
columns=Index([f"i-{i}" for i in range(5)], name="a"),
|
80 |
+
)
|
81 |
+
stacked = df.stack(future_stack=True)
|
82 |
+
idx = stacked.index
|
83 |
+
with pytest.raises(TypeError, match="^Level type mismatch"):
|
84 |
+
idx.slice_locs(timedelta(seconds=30))
|
85 |
+
# TODO: Try creating a UnicodeDecodeError in exception message
|
86 |
+
with pytest.raises(TypeError, match="^Level type mismatch"):
|
87 |
+
idx.slice_locs(df.index[1], (16, "a"))
|
88 |
+
|
89 |
+
def test_slice_locs_not_sorted(self):
|
90 |
+
index = MultiIndex(
|
91 |
+
levels=[Index(np.arange(4)), Index(np.arange(4)), Index(np.arange(4))],
|
92 |
+
codes=[
|
93 |
+
np.array([0, 0, 1, 2, 2, 2, 3, 3]),
|
94 |
+
np.array([0, 1, 0, 0, 0, 1, 0, 1]),
|
95 |
+
np.array([1, 0, 1, 1, 0, 0, 1, 0]),
|
96 |
+
],
|
97 |
+
)
|
98 |
+
msg = "[Kk]ey length.*greater than MultiIndex lexsort depth"
|
99 |
+
with pytest.raises(KeyError, match=msg):
|
100 |
+
index.slice_locs((1, 0, 1), (2, 1, 0))
|
101 |
+
|
102 |
+
# works
|
103 |
+
sorted_index, _ = index.sortlevel(0)
|
104 |
+
# should there be a test case here???
|
105 |
+
sorted_index.slice_locs((1, 0, 1), (2, 1, 0))
|
106 |
+
|
107 |
+
def test_slice_locs_not_contained(self):
|
108 |
+
# some searchsorted action
|
109 |
+
|
110 |
+
index = MultiIndex(
|
111 |
+
levels=[[0, 2, 4, 6], [0, 2, 4]],
|
112 |
+
codes=[[0, 0, 0, 1, 1, 2, 3, 3, 3], [0, 1, 2, 1, 2, 2, 0, 1, 2]],
|
113 |
+
)
|
114 |
+
|
115 |
+
result = index.slice_locs((1, 0), (5, 2))
|
116 |
+
assert result == (3, 6)
|
117 |
+
|
118 |
+
result = index.slice_locs(1, 5)
|
119 |
+
assert result == (3, 6)
|
120 |
+
|
121 |
+
result = index.slice_locs((2, 2), (5, 2))
|
122 |
+
assert result == (3, 6)
|
123 |
+
|
124 |
+
result = index.slice_locs(2, 5)
|
125 |
+
assert result == (3, 6)
|
126 |
+
|
127 |
+
result = index.slice_locs((1, 0), (6, 3))
|
128 |
+
assert result == (3, 8)
|
129 |
+
|
130 |
+
result = index.slice_locs(-1, 10)
|
131 |
+
assert result == (0, len(index))
|
132 |
+
|
133 |
+
@pytest.mark.parametrize(
|
134 |
+
"index_arr,expected,start_idx,end_idx",
|
135 |
+
[
|
136 |
+
([[np.nan, "a", "b"], ["c", "d", "e"]], (0, 3), np.nan, None),
|
137 |
+
([[np.nan, "a", "b"], ["c", "d", "e"]], (0, 3), np.nan, "b"),
|
138 |
+
([[np.nan, "a", "b"], ["c", "d", "e"]], (0, 3), np.nan, ("b", "e")),
|
139 |
+
([["a", "b", "c"], ["d", np.nan, "e"]], (1, 3), ("b", np.nan), None),
|
140 |
+
([["a", "b", "c"], ["d", np.nan, "e"]], (1, 3), ("b", np.nan), "c"),
|
141 |
+
([["a", "b", "c"], ["d", np.nan, "e"]], (1, 3), ("b", np.nan), ("c", "e")),
|
142 |
+
],
|
143 |
+
)
|
144 |
+
def test_slice_locs_with_missing_value(
|
145 |
+
self, index_arr, expected, start_idx, end_idx
|
146 |
+
):
|
147 |
+
# issue 19132
|
148 |
+
idx = MultiIndex.from_arrays(index_arr)
|
149 |
+
result = idx.slice_locs(start=start_idx, end=end_idx)
|
150 |
+
assert result == expected
|
151 |
+
|
152 |
+
|
153 |
+
class TestPutmask:
|
154 |
+
def test_putmask_with_wrong_mask(self, idx):
|
155 |
+
# GH18368
|
156 |
+
|
157 |
+
msg = "putmask: mask and data must be the same size"
|
158 |
+
with pytest.raises(ValueError, match=msg):
|
159 |
+
idx.putmask(np.ones(len(idx) + 1, np.bool_), 1)
|
160 |
+
|
161 |
+
with pytest.raises(ValueError, match=msg):
|
162 |
+
idx.putmask(np.ones(len(idx) - 1, np.bool_), 1)
|
163 |
+
|
164 |
+
with pytest.raises(ValueError, match=msg):
|
165 |
+
idx.putmask("foo", 1)
|
166 |
+
|
167 |
+
def test_putmask_multiindex_other(self):
|
168 |
+
# GH#43212 `value` is also a MultiIndex
|
169 |
+
|
170 |
+
left = MultiIndex.from_tuples([(np.nan, 6), (np.nan, 6), ("a", 4)])
|
171 |
+
right = MultiIndex.from_tuples([("a", 1), ("a", 1), ("d", 1)])
|
172 |
+
mask = np.array([True, True, False])
|
173 |
+
|
174 |
+
result = left.putmask(mask, right)
|
175 |
+
|
176 |
+
expected = MultiIndex.from_tuples([right[0], right[1], left[2]])
|
177 |
+
tm.assert_index_equal(result, expected)
|
178 |
+
|
179 |
+
def test_putmask_keep_dtype(self, any_numeric_ea_dtype):
|
180 |
+
# GH#49830
|
181 |
+
midx = MultiIndex.from_arrays(
|
182 |
+
[pd.Series([1, 2, 3], dtype=any_numeric_ea_dtype), [10, 11, 12]]
|
183 |
+
)
|
184 |
+
midx2 = MultiIndex.from_arrays(
|
185 |
+
[pd.Series([5, 6, 7], dtype=any_numeric_ea_dtype), [-1, -2, -3]]
|
186 |
+
)
|
187 |
+
result = midx.putmask([True, False, False], midx2)
|
188 |
+
expected = MultiIndex.from_arrays(
|
189 |
+
[pd.Series([5, 2, 3], dtype=any_numeric_ea_dtype), [-1, 11, 12]]
|
190 |
+
)
|
191 |
+
tm.assert_index_equal(result, expected)
|
192 |
+
|
193 |
+
def test_putmask_keep_dtype_shorter_value(self, any_numeric_ea_dtype):
|
194 |
+
# GH#49830
|
195 |
+
midx = MultiIndex.from_arrays(
|
196 |
+
[pd.Series([1, 2, 3], dtype=any_numeric_ea_dtype), [10, 11, 12]]
|
197 |
+
)
|
198 |
+
midx2 = MultiIndex.from_arrays(
|
199 |
+
[pd.Series([5], dtype=any_numeric_ea_dtype), [-1]]
|
200 |
+
)
|
201 |
+
result = midx.putmask([True, False, False], midx2)
|
202 |
+
expected = MultiIndex.from_arrays(
|
203 |
+
[pd.Series([5, 2, 3], dtype=any_numeric_ea_dtype), [-1, 11, 12]]
|
204 |
+
)
|
205 |
+
tm.assert_index_equal(result, expected)
|
206 |
+
|
207 |
+
|
208 |
+
class TestGetIndexer:
|
209 |
+
def test_get_indexer(self):
|
210 |
+
major_axis = Index(np.arange(4))
|
211 |
+
minor_axis = Index(np.arange(2))
|
212 |
+
|
213 |
+
major_codes = np.array([0, 0, 1, 2, 2, 3, 3], dtype=np.intp)
|
214 |
+
minor_codes = np.array([0, 1, 0, 0, 1, 0, 1], dtype=np.intp)
|
215 |
+
|
216 |
+
index = MultiIndex(
|
217 |
+
levels=[major_axis, minor_axis], codes=[major_codes, minor_codes]
|
218 |
+
)
|
219 |
+
idx1 = index[:5]
|
220 |
+
idx2 = index[[1, 3, 5]]
|
221 |
+
|
222 |
+
r1 = idx1.get_indexer(idx2)
|
223 |
+
tm.assert_almost_equal(r1, np.array([1, 3, -1], dtype=np.intp))
|
224 |
+
|
225 |
+
r1 = idx2.get_indexer(idx1, method="pad")
|
226 |
+
e1 = np.array([-1, 0, 0, 1, 1], dtype=np.intp)
|
227 |
+
tm.assert_almost_equal(r1, e1)
|
228 |
+
|
229 |
+
r2 = idx2.get_indexer(idx1[::-1], method="pad")
|
230 |
+
tm.assert_almost_equal(r2, e1[::-1])
|
231 |
+
|
232 |
+
rffill1 = idx2.get_indexer(idx1, method="ffill")
|
233 |
+
tm.assert_almost_equal(r1, rffill1)
|
234 |
+
|
235 |
+
r1 = idx2.get_indexer(idx1, method="backfill")
|
236 |
+
e1 = np.array([0, 0, 1, 1, 2], dtype=np.intp)
|
237 |
+
tm.assert_almost_equal(r1, e1)
|
238 |
+
|
239 |
+
r2 = idx2.get_indexer(idx1[::-1], method="backfill")
|
240 |
+
tm.assert_almost_equal(r2, e1[::-1])
|
241 |
+
|
242 |
+
rbfill1 = idx2.get_indexer(idx1, method="bfill")
|
243 |
+
tm.assert_almost_equal(r1, rbfill1)
|
244 |
+
|
245 |
+
# pass non-MultiIndex
|
246 |
+
r1 = idx1.get_indexer(idx2.values)
|
247 |
+
rexp1 = idx1.get_indexer(idx2)
|
248 |
+
tm.assert_almost_equal(r1, rexp1)
|
249 |
+
|
250 |
+
r1 = idx1.get_indexer([1, 2, 3])
|
251 |
+
assert (r1 == [-1, -1, -1]).all()
|
252 |
+
|
253 |
+
# create index with duplicates
|
254 |
+
idx1 = Index(list(range(10)) + list(range(10)))
|
255 |
+
idx2 = Index(list(range(20)))
|
256 |
+
|
257 |
+
msg = "Reindexing only valid with uniquely valued Index objects"
|
258 |
+
with pytest.raises(InvalidIndexError, match=msg):
|
259 |
+
idx1.get_indexer(idx2)
|
260 |
+
|
261 |
+
def test_get_indexer_nearest(self):
|
262 |
+
midx = MultiIndex.from_tuples([("a", 1), ("b", 2)])
|
263 |
+
msg = (
|
264 |
+
"method='nearest' not implemented yet for MultiIndex; "
|
265 |
+
"see GitHub issue 9365"
|
266 |
+
)
|
267 |
+
with pytest.raises(NotImplementedError, match=msg):
|
268 |
+
midx.get_indexer(["a"], method="nearest")
|
269 |
+
msg = "tolerance not implemented yet for MultiIndex"
|
270 |
+
with pytest.raises(NotImplementedError, match=msg):
|
271 |
+
midx.get_indexer(["a"], method="pad", tolerance=2)
|
272 |
+
|
273 |
+
def test_get_indexer_categorical_time(self):
|
274 |
+
# https://github.com/pandas-dev/pandas/issues/21390
|
275 |
+
midx = MultiIndex.from_product(
|
276 |
+
[
|
277 |
+
Categorical(["a", "b", "c"]),
|
278 |
+
Categorical(date_range("2012-01-01", periods=3, freq="h")),
|
279 |
+
]
|
280 |
+
)
|
281 |
+
result = midx.get_indexer(midx)
|
282 |
+
tm.assert_numpy_array_equal(result, np.arange(9, dtype=np.intp))
|
283 |
+
|
284 |
+
@pytest.mark.parametrize(
|
285 |
+
"index_arr,labels,expected",
|
286 |
+
[
|
287 |
+
(
|
288 |
+
[[1, np.nan, 2], [3, 4, 5]],
|
289 |
+
[1, np.nan, 2],
|
290 |
+
np.array([-1, -1, -1], dtype=np.intp),
|
291 |
+
),
|
292 |
+
([[1, np.nan, 2], [3, 4, 5]], [(np.nan, 4)], np.array([1], dtype=np.intp)),
|
293 |
+
([[1, 2, 3], [np.nan, 4, 5]], [(1, np.nan)], np.array([0], dtype=np.intp)),
|
294 |
+
(
|
295 |
+
[[1, 2, 3], [np.nan, 4, 5]],
|
296 |
+
[np.nan, 4, 5],
|
297 |
+
np.array([-1, -1, -1], dtype=np.intp),
|
298 |
+
),
|
299 |
+
],
|
300 |
+
)
|
301 |
+
def test_get_indexer_with_missing_value(self, index_arr, labels, expected):
|
302 |
+
# issue 19132
|
303 |
+
idx = MultiIndex.from_arrays(index_arr)
|
304 |
+
result = idx.get_indexer(labels)
|
305 |
+
tm.assert_numpy_array_equal(result, expected)
|
306 |
+
|
307 |
+
def test_get_indexer_methods(self):
|
308 |
+
# https://github.com/pandas-dev/pandas/issues/29896
|
309 |
+
# test getting an indexer for another index with different methods
|
310 |
+
# confirms that getting an indexer without a filling method, getting an
|
311 |
+
# indexer and backfilling, and getting an indexer and padding all behave
|
312 |
+
# correctly in the case where all of the target values fall in between
|
313 |
+
# several levels in the MultiIndex into which they are getting an indexer
|
314 |
+
#
|
315 |
+
# visually, the MultiIndexes used in this test are:
|
316 |
+
# mult_idx_1:
|
317 |
+
# 0: -1 0
|
318 |
+
# 1: 2
|
319 |
+
# 2: 3
|
320 |
+
# 3: 4
|
321 |
+
# 4: 0 0
|
322 |
+
# 5: 2
|
323 |
+
# 6: 3
|
324 |
+
# 7: 4
|
325 |
+
# 8: 1 0
|
326 |
+
# 9: 2
|
327 |
+
# 10: 3
|
328 |
+
# 11: 4
|
329 |
+
#
|
330 |
+
# mult_idx_2:
|
331 |
+
# 0: 0 1
|
332 |
+
# 1: 3
|
333 |
+
# 2: 4
|
334 |
+
mult_idx_1 = MultiIndex.from_product([[-1, 0, 1], [0, 2, 3, 4]])
|
335 |
+
mult_idx_2 = MultiIndex.from_product([[0], [1, 3, 4]])
|
336 |
+
|
337 |
+
indexer = mult_idx_1.get_indexer(mult_idx_2)
|
338 |
+
expected = np.array([-1, 6, 7], dtype=indexer.dtype)
|
339 |
+
tm.assert_almost_equal(expected, indexer)
|
340 |
+
|
341 |
+
backfill_indexer = mult_idx_1.get_indexer(mult_idx_2, method="backfill")
|
342 |
+
expected = np.array([5, 6, 7], dtype=backfill_indexer.dtype)
|
343 |
+
tm.assert_almost_equal(expected, backfill_indexer)
|
344 |
+
|
345 |
+
# ensure the legacy "bfill" option functions identically to "backfill"
|
346 |
+
backfill_indexer = mult_idx_1.get_indexer(mult_idx_2, method="bfill")
|
347 |
+
expected = np.array([5, 6, 7], dtype=backfill_indexer.dtype)
|
348 |
+
tm.assert_almost_equal(expected, backfill_indexer)
|
349 |
+
|
350 |
+
pad_indexer = mult_idx_1.get_indexer(mult_idx_2, method="pad")
|
351 |
+
expected = np.array([4, 6, 7], dtype=pad_indexer.dtype)
|
352 |
+
tm.assert_almost_equal(expected, pad_indexer)
|
353 |
+
|
354 |
+
# ensure the legacy "ffill" option functions identically to "pad"
|
355 |
+
pad_indexer = mult_idx_1.get_indexer(mult_idx_2, method="ffill")
|
356 |
+
expected = np.array([4, 6, 7], dtype=pad_indexer.dtype)
|
357 |
+
tm.assert_almost_equal(expected, pad_indexer)
|
358 |
+
|
359 |
+
@pytest.mark.parametrize("method", ["pad", "ffill", "backfill", "bfill", "nearest"])
|
360 |
+
def test_get_indexer_methods_raise_for_non_monotonic(self, method):
|
361 |
+
# 53452
|
362 |
+
mi = MultiIndex.from_arrays([[0, 4, 2], [0, 4, 2]])
|
363 |
+
if method == "nearest":
|
364 |
+
err = NotImplementedError
|
365 |
+
msg = "not implemented yet for MultiIndex"
|
366 |
+
else:
|
367 |
+
err = ValueError
|
368 |
+
msg = "index must be monotonic increasing or decreasing"
|
369 |
+
with pytest.raises(err, match=msg):
|
370 |
+
mi.get_indexer([(1, 1)], method=method)
|
371 |
+
|
372 |
+
def test_get_indexer_three_or_more_levels(self):
|
373 |
+
# https://github.com/pandas-dev/pandas/issues/29896
|
374 |
+
# tests get_indexer() on MultiIndexes with 3+ levels
|
375 |
+
# visually, these are
|
376 |
+
# mult_idx_1:
|
377 |
+
# 0: 1 2 5
|
378 |
+
# 1: 7
|
379 |
+
# 2: 4 5
|
380 |
+
# 3: 7
|
381 |
+
# 4: 6 5
|
382 |
+
# 5: 7
|
383 |
+
# 6: 3 2 5
|
384 |
+
# 7: 7
|
385 |
+
# 8: 4 5
|
386 |
+
# 9: 7
|
387 |
+
# 10: 6 5
|
388 |
+
# 11: 7
|
389 |
+
#
|
390 |
+
# mult_idx_2:
|
391 |
+
# 0: 1 1 8
|
392 |
+
# 1: 1 5 9
|
393 |
+
# 2: 1 6 7
|
394 |
+
# 3: 2 1 6
|
395 |
+
# 4: 2 7 6
|
396 |
+
# 5: 2 7 8
|
397 |
+
# 6: 3 6 8
|
398 |
+
mult_idx_1 = MultiIndex.from_product([[1, 3], [2, 4, 6], [5, 7]])
|
399 |
+
mult_idx_2 = MultiIndex.from_tuples(
|
400 |
+
[
|
401 |
+
(1, 1, 8),
|
402 |
+
(1, 5, 9),
|
403 |
+
(1, 6, 7),
|
404 |
+
(2, 1, 6),
|
405 |
+
(2, 7, 7),
|
406 |
+
(2, 7, 8),
|
407 |
+
(3, 6, 8),
|
408 |
+
]
|
409 |
+
)
|
410 |
+
# sanity check
|
411 |
+
assert mult_idx_1.is_monotonic_increasing
|
412 |
+
assert mult_idx_1.is_unique
|
413 |
+
assert mult_idx_2.is_monotonic_increasing
|
414 |
+
assert mult_idx_2.is_unique
|
415 |
+
|
416 |
+
# show the relationships between the two
|
417 |
+
assert mult_idx_2[0] < mult_idx_1[0]
|
418 |
+
assert mult_idx_1[3] < mult_idx_2[1] < mult_idx_1[4]
|
419 |
+
assert mult_idx_1[5] == mult_idx_2[2]
|
420 |
+
assert mult_idx_1[5] < mult_idx_2[3] < mult_idx_1[6]
|
421 |
+
assert mult_idx_1[5] < mult_idx_2[4] < mult_idx_1[6]
|
422 |
+
assert mult_idx_1[5] < mult_idx_2[5] < mult_idx_1[6]
|
423 |
+
assert mult_idx_1[-1] < mult_idx_2[6]
|
424 |
+
|
425 |
+
indexer_no_fill = mult_idx_1.get_indexer(mult_idx_2)
|
426 |
+
expected = np.array([-1, -1, 5, -1, -1, -1, -1], dtype=indexer_no_fill.dtype)
|
427 |
+
tm.assert_almost_equal(expected, indexer_no_fill)
|
428 |
+
|
429 |
+
# test with backfilling
|
430 |
+
indexer_backfilled = mult_idx_1.get_indexer(mult_idx_2, method="backfill")
|
431 |
+
expected = np.array([0, 4, 5, 6, 6, 6, -1], dtype=indexer_backfilled.dtype)
|
432 |
+
tm.assert_almost_equal(expected, indexer_backfilled)
|
433 |
+
|
434 |
+
# now, the same thing, but forward-filled (aka "padded")
|
435 |
+
indexer_padded = mult_idx_1.get_indexer(mult_idx_2, method="pad")
|
436 |
+
expected = np.array([-1, 3, 5, 5, 5, 5, 11], dtype=indexer_padded.dtype)
|
437 |
+
tm.assert_almost_equal(expected, indexer_padded)
|
438 |
+
|
439 |
+
# now, do the indexing in the other direction
|
440 |
+
assert mult_idx_2[0] < mult_idx_1[0] < mult_idx_2[1]
|
441 |
+
assert mult_idx_2[0] < mult_idx_1[1] < mult_idx_2[1]
|
442 |
+
assert mult_idx_2[0] < mult_idx_1[2] < mult_idx_2[1]
|
443 |
+
assert mult_idx_2[0] < mult_idx_1[3] < mult_idx_2[1]
|
444 |
+
assert mult_idx_2[1] < mult_idx_1[4] < mult_idx_2[2]
|
445 |
+
assert mult_idx_2[2] == mult_idx_1[5]
|
446 |
+
assert mult_idx_2[5] < mult_idx_1[6] < mult_idx_2[6]
|
447 |
+
assert mult_idx_2[5] < mult_idx_1[7] < mult_idx_2[6]
|
448 |
+
assert mult_idx_2[5] < mult_idx_1[8] < mult_idx_2[6]
|
449 |
+
assert mult_idx_2[5] < mult_idx_1[9] < mult_idx_2[6]
|
450 |
+
assert mult_idx_2[5] < mult_idx_1[10] < mult_idx_2[6]
|
451 |
+
assert mult_idx_2[5] < mult_idx_1[11] < mult_idx_2[6]
|
452 |
+
|
453 |
+
indexer = mult_idx_2.get_indexer(mult_idx_1)
|
454 |
+
expected = np.array(
|
455 |
+
[-1, -1, -1, -1, -1, 2, -1, -1, -1, -1, -1, -1], dtype=indexer.dtype
|
456 |
+
)
|
457 |
+
tm.assert_almost_equal(expected, indexer)
|
458 |
+
|
459 |
+
backfill_indexer = mult_idx_2.get_indexer(mult_idx_1, method="bfill")
|
460 |
+
expected = np.array(
|
461 |
+
[1, 1, 1, 1, 2, 2, 6, 6, 6, 6, 6, 6], dtype=backfill_indexer.dtype
|
462 |
+
)
|
463 |
+
tm.assert_almost_equal(expected, backfill_indexer)
|
464 |
+
|
465 |
+
pad_indexer = mult_idx_2.get_indexer(mult_idx_1, method="pad")
|
466 |
+
expected = np.array(
|
467 |
+
[0, 0, 0, 0, 1, 2, 5, 5, 5, 5, 5, 5], dtype=pad_indexer.dtype
|
468 |
+
)
|
469 |
+
tm.assert_almost_equal(expected, pad_indexer)
|
470 |
+
|
471 |
+
def test_get_indexer_crossing_levels(self):
|
472 |
+
# https://github.com/pandas-dev/pandas/issues/29896
|
473 |
+
# tests a corner case with get_indexer() with MultiIndexes where, when we
|
474 |
+
# need to "carry" across levels, proper tuple ordering is respected
|
475 |
+
#
|
476 |
+
# the MultiIndexes used in this test, visually, are:
|
477 |
+
# mult_idx_1:
|
478 |
+
# 0: 1 1 1 1
|
479 |
+
# 1: 2
|
480 |
+
# 2: 2 1
|
481 |
+
# 3: 2
|
482 |
+
# 4: 1 2 1 1
|
483 |
+
# 5: 2
|
484 |
+
# 6: 2 1
|
485 |
+
# 7: 2
|
486 |
+
# 8: 2 1 1 1
|
487 |
+
# 9: 2
|
488 |
+
# 10: 2 1
|
489 |
+
# 11: 2
|
490 |
+
# 12: 2 2 1 1
|
491 |
+
# 13: 2
|
492 |
+
# 14: 2 1
|
493 |
+
# 15: 2
|
494 |
+
#
|
495 |
+
# mult_idx_2:
|
496 |
+
# 0: 1 3 2 2
|
497 |
+
# 1: 2 3 2 2
|
498 |
+
mult_idx_1 = MultiIndex.from_product([[1, 2]] * 4)
|
499 |
+
mult_idx_2 = MultiIndex.from_tuples([(1, 3, 2, 2), (2, 3, 2, 2)])
|
500 |
+
|
501 |
+
# show the tuple orderings, which get_indexer() should respect
|
502 |
+
assert mult_idx_1[7] < mult_idx_2[0] < mult_idx_1[8]
|
503 |
+
assert mult_idx_1[-1] < mult_idx_2[1]
|
504 |
+
|
505 |
+
indexer = mult_idx_1.get_indexer(mult_idx_2)
|
506 |
+
expected = np.array([-1, -1], dtype=indexer.dtype)
|
507 |
+
tm.assert_almost_equal(expected, indexer)
|
508 |
+
|
509 |
+
backfill_indexer = mult_idx_1.get_indexer(mult_idx_2, method="bfill")
|
510 |
+
expected = np.array([8, -1], dtype=backfill_indexer.dtype)
|
511 |
+
tm.assert_almost_equal(expected, backfill_indexer)
|
512 |
+
|
513 |
+
pad_indexer = mult_idx_1.get_indexer(mult_idx_2, method="ffill")
|
514 |
+
expected = np.array([7, 15], dtype=pad_indexer.dtype)
|
515 |
+
tm.assert_almost_equal(expected, pad_indexer)
|
516 |
+
|
517 |
+
def test_get_indexer_kwarg_validation(self):
|
518 |
+
# GH#41918
|
519 |
+
mi = MultiIndex.from_product([range(3), ["A", "B"]])
|
520 |
+
|
521 |
+
msg = "limit argument only valid if doing pad, backfill or nearest"
|
522 |
+
with pytest.raises(ValueError, match=msg):
|
523 |
+
mi.get_indexer(mi[:-1], limit=4)
|
524 |
+
|
525 |
+
msg = "tolerance argument only valid if doing pad, backfill or nearest"
|
526 |
+
with pytest.raises(ValueError, match=msg):
|
527 |
+
mi.get_indexer(mi[:-1], tolerance="piano")
|
528 |
+
|
529 |
+
def test_get_indexer_nan(self):
|
530 |
+
# GH#37222
|
531 |
+
idx1 = MultiIndex.from_product([["A"], [1.0, 2.0]], names=["id1", "id2"])
|
532 |
+
idx2 = MultiIndex.from_product([["A"], [np.nan, 2.0]], names=["id1", "id2"])
|
533 |
+
expected = np.array([-1, 1])
|
534 |
+
result = idx2.get_indexer(idx1)
|
535 |
+
tm.assert_numpy_array_equal(result, expected, check_dtype=False)
|
536 |
+
result = idx1.get_indexer(idx2)
|
537 |
+
tm.assert_numpy_array_equal(result, expected, check_dtype=False)
|
538 |
+
|
539 |
+
|
540 |
+
def test_getitem(idx):
|
541 |
+
# scalar
|
542 |
+
assert idx[2] == ("bar", "one")
|
543 |
+
|
544 |
+
# slice
|
545 |
+
result = idx[2:5]
|
546 |
+
expected = idx[[2, 3, 4]]
|
547 |
+
assert result.equals(expected)
|
548 |
+
|
549 |
+
# boolean
|
550 |
+
result = idx[[True, False, True, False, True, True]]
|
551 |
+
result2 = idx[np.array([True, False, True, False, True, True])]
|
552 |
+
expected = idx[[0, 2, 4, 5]]
|
553 |
+
assert result.equals(expected)
|
554 |
+
assert result2.equals(expected)
|
555 |
+
|
556 |
+
|
557 |
+
def test_getitem_group_select(idx):
|
558 |
+
sorted_idx, _ = idx.sortlevel(0)
|
559 |
+
assert sorted_idx.get_loc("baz") == slice(3, 4)
|
560 |
+
assert sorted_idx.get_loc("foo") == slice(0, 2)
|
561 |
+
|
562 |
+
|
563 |
+
@pytest.mark.parametrize("ind1", [[True] * 5, Index([True] * 5)])
|
564 |
+
@pytest.mark.parametrize(
|
565 |
+
"ind2",
|
566 |
+
[[True, False, True, False, False], Index([True, False, True, False, False])],
|
567 |
+
)
|
568 |
+
def test_getitem_bool_index_all(ind1, ind2):
|
569 |
+
# GH#22533
|
570 |
+
idx = MultiIndex.from_tuples([(10, 1), (20, 2), (30, 3), (40, 4), (50, 5)])
|
571 |
+
tm.assert_index_equal(idx[ind1], idx)
|
572 |
+
|
573 |
+
expected = MultiIndex.from_tuples([(10, 1), (30, 3)])
|
574 |
+
tm.assert_index_equal(idx[ind2], expected)
|
575 |
+
|
576 |
+
|
577 |
+
@pytest.mark.parametrize("ind1", [[True], Index([True])])
|
578 |
+
@pytest.mark.parametrize("ind2", [[False], Index([False])])
|
579 |
+
def test_getitem_bool_index_single(ind1, ind2):
|
580 |
+
# GH#22533
|
581 |
+
idx = MultiIndex.from_tuples([(10, 1)])
|
582 |
+
tm.assert_index_equal(idx[ind1], idx)
|
583 |
+
|
584 |
+
expected = MultiIndex(
|
585 |
+
levels=[np.array([], dtype=np.int64), np.array([], dtype=np.int64)],
|
586 |
+
codes=[[], []],
|
587 |
+
)
|
588 |
+
tm.assert_index_equal(idx[ind2], expected)
|
589 |
+
|
590 |
+
|
591 |
+
class TestGetLoc:
|
592 |
+
def test_get_loc(self, idx):
|
593 |
+
assert idx.get_loc(("foo", "two")) == 1
|
594 |
+
assert idx.get_loc(("baz", "two")) == 3
|
595 |
+
with pytest.raises(KeyError, match=r"^\('bar', 'two'\)$"):
|
596 |
+
idx.get_loc(("bar", "two"))
|
597 |
+
with pytest.raises(KeyError, match=r"^'quux'$"):
|
598 |
+
idx.get_loc("quux")
|
599 |
+
|
600 |
+
# 3 levels
|
601 |
+
index = MultiIndex(
|
602 |
+
levels=[Index(np.arange(4)), Index(np.arange(4)), Index(np.arange(4))],
|
603 |
+
codes=[
|
604 |
+
np.array([0, 0, 1, 2, 2, 2, 3, 3]),
|
605 |
+
np.array([0, 1, 0, 0, 0, 1, 0, 1]),
|
606 |
+
np.array([1, 0, 1, 1, 0, 0, 1, 0]),
|
607 |
+
],
|
608 |
+
)
|
609 |
+
with pytest.raises(KeyError, match=r"^\(1, 1\)$"):
|
610 |
+
index.get_loc((1, 1))
|
611 |
+
assert index.get_loc((2, 0)) == slice(3, 5)
|
612 |
+
|
613 |
+
def test_get_loc_duplicates(self):
|
614 |
+
index = Index([2, 2, 2, 2])
|
615 |
+
result = index.get_loc(2)
|
616 |
+
expected = slice(0, 4)
|
617 |
+
assert result == expected
|
618 |
+
|
619 |
+
index = Index(["c", "a", "a", "b", "b"])
|
620 |
+
rs = index.get_loc("c")
|
621 |
+
xp = 0
|
622 |
+
assert rs == xp
|
623 |
+
|
624 |
+
with pytest.raises(KeyError, match="2"):
|
625 |
+
index.get_loc(2)
|
626 |
+
|
627 |
+
def test_get_loc_level(self):
|
628 |
+
index = MultiIndex(
|
629 |
+
levels=[Index(np.arange(4)), Index(np.arange(4)), Index(np.arange(4))],
|
630 |
+
codes=[
|
631 |
+
np.array([0, 0, 1, 2, 2, 2, 3, 3]),
|
632 |
+
np.array([0, 1, 0, 0, 0, 1, 0, 1]),
|
633 |
+
np.array([1, 0, 1, 1, 0, 0, 1, 0]),
|
634 |
+
],
|
635 |
+
)
|
636 |
+
loc, new_index = index.get_loc_level((0, 1))
|
637 |
+
expected = slice(1, 2)
|
638 |
+
exp_index = index[expected].droplevel(0).droplevel(0)
|
639 |
+
assert loc == expected
|
640 |
+
assert new_index.equals(exp_index)
|
641 |
+
|
642 |
+
loc, new_index = index.get_loc_level((0, 1, 0))
|
643 |
+
expected = 1
|
644 |
+
assert loc == expected
|
645 |
+
assert new_index is None
|
646 |
+
|
647 |
+
with pytest.raises(KeyError, match=r"^\(2, 2\)$"):
|
648 |
+
index.get_loc_level((2, 2))
|
649 |
+
# GH 22221: unused label
|
650 |
+
with pytest.raises(KeyError, match=r"^2$"):
|
651 |
+
index.drop(2).get_loc_level(2)
|
652 |
+
# Unused label on unsorted level:
|
653 |
+
with pytest.raises(KeyError, match=r"^2$"):
|
654 |
+
index.drop(1, level=2).get_loc_level(2, level=2)
|
655 |
+
|
656 |
+
index = MultiIndex(
|
657 |
+
levels=[[2000], list(range(4))],
|
658 |
+
codes=[np.array([0, 0, 0, 0]), np.array([0, 1, 2, 3])],
|
659 |
+
)
|
660 |
+
result, new_index = index.get_loc_level((2000, slice(None, None)))
|
661 |
+
expected = slice(None, None)
|
662 |
+
assert result == expected
|
663 |
+
assert new_index.equals(index.droplevel(0))
|
664 |
+
|
665 |
+
@pytest.mark.parametrize("dtype1", [int, float, bool, str])
|
666 |
+
@pytest.mark.parametrize("dtype2", [int, float, bool, str])
|
667 |
+
def test_get_loc_multiple_dtypes(self, dtype1, dtype2):
|
668 |
+
# GH 18520
|
669 |
+
levels = [np.array([0, 1]).astype(dtype1), np.array([0, 1]).astype(dtype2)]
|
670 |
+
idx = MultiIndex.from_product(levels)
|
671 |
+
assert idx.get_loc(idx[2]) == 2
|
672 |
+
|
673 |
+
@pytest.mark.parametrize("level", [0, 1])
|
674 |
+
@pytest.mark.parametrize("dtypes", [[int, float], [float, int]])
|
675 |
+
def test_get_loc_implicit_cast(self, level, dtypes):
|
676 |
+
# GH 18818, GH 15994 : as flat index, cast int to float and vice-versa
|
677 |
+
levels = [["a", "b"], ["c", "d"]]
|
678 |
+
key = ["b", "d"]
|
679 |
+
lev_dtype, key_dtype = dtypes
|
680 |
+
levels[level] = np.array([0, 1], dtype=lev_dtype)
|
681 |
+
key[level] = key_dtype(1)
|
682 |
+
idx = MultiIndex.from_product(levels)
|
683 |
+
assert idx.get_loc(tuple(key)) == 3
|
684 |
+
|
685 |
+
@pytest.mark.parametrize("dtype", [bool, object])
|
686 |
+
def test_get_loc_cast_bool(self, dtype):
|
687 |
+
# GH 19086 : int is casted to bool, but not vice-versa (for object dtype)
|
688 |
+
# With bool dtype, we don't cast in either direction.
|
689 |
+
levels = [Index([False, True], dtype=dtype), np.arange(2, dtype="int64")]
|
690 |
+
idx = MultiIndex.from_product(levels)
|
691 |
+
|
692 |
+
if dtype is bool:
|
693 |
+
with pytest.raises(KeyError, match=r"^\(0, 1\)$"):
|
694 |
+
assert idx.get_loc((0, 1)) == 1
|
695 |
+
with pytest.raises(KeyError, match=r"^\(1, 0\)$"):
|
696 |
+
assert idx.get_loc((1, 0)) == 2
|
697 |
+
else:
|
698 |
+
# We use python object comparisons, which treat 0 == False and 1 == True
|
699 |
+
assert idx.get_loc((0, 1)) == 1
|
700 |
+
assert idx.get_loc((1, 0)) == 2
|
701 |
+
|
702 |
+
with pytest.raises(KeyError, match=r"^\(False, True\)$"):
|
703 |
+
idx.get_loc((False, True))
|
704 |
+
with pytest.raises(KeyError, match=r"^\(True, False\)$"):
|
705 |
+
idx.get_loc((True, False))
|
706 |
+
|
707 |
+
@pytest.mark.parametrize("level", [0, 1])
|
708 |
+
def test_get_loc_nan(self, level, nulls_fixture):
|
709 |
+
# GH 18485 : NaN in MultiIndex
|
710 |
+
levels = [["a", "b"], ["c", "d"]]
|
711 |
+
key = ["b", "d"]
|
712 |
+
levels[level] = np.array([0, nulls_fixture], dtype=type(nulls_fixture))
|
713 |
+
key[level] = nulls_fixture
|
714 |
+
idx = MultiIndex.from_product(levels)
|
715 |
+
assert idx.get_loc(tuple(key)) == 3
|
716 |
+
|
717 |
+
def test_get_loc_missing_nan(self):
|
718 |
+
# GH 8569
|
719 |
+
idx = MultiIndex.from_arrays([[1.0, 2.0], [3.0, 4.0]])
|
720 |
+
assert isinstance(idx.get_loc(1), slice)
|
721 |
+
with pytest.raises(KeyError, match=r"^3$"):
|
722 |
+
idx.get_loc(3)
|
723 |
+
with pytest.raises(KeyError, match=r"^nan$"):
|
724 |
+
idx.get_loc(np.nan)
|
725 |
+
with pytest.raises(InvalidIndexError, match=r"\[nan\]"):
|
726 |
+
# listlike/non-hashable raises TypeError
|
727 |
+
idx.get_loc([np.nan])
|
728 |
+
|
729 |
+
def test_get_loc_with_values_including_missing_values(self):
|
730 |
+
# issue 19132
|
731 |
+
idx = MultiIndex.from_product([[np.nan, 1]] * 2)
|
732 |
+
expected = slice(0, 2, None)
|
733 |
+
assert idx.get_loc(np.nan) == expected
|
734 |
+
|
735 |
+
idx = MultiIndex.from_arrays([[np.nan, 1, 2, np.nan]])
|
736 |
+
expected = np.array([True, False, False, True])
|
737 |
+
tm.assert_numpy_array_equal(idx.get_loc(np.nan), expected)
|
738 |
+
|
739 |
+
idx = MultiIndex.from_product([[np.nan, 1]] * 3)
|
740 |
+
expected = slice(2, 4, None)
|
741 |
+
assert idx.get_loc((np.nan, 1)) == expected
|
742 |
+
|
743 |
+
def test_get_loc_duplicates2(self):
|
744 |
+
# TODO: de-duplicate with test_get_loc_duplicates above?
|
745 |
+
index = MultiIndex(
|
746 |
+
levels=[["D", "B", "C"], [0, 26, 27, 37, 57, 67, 75, 82]],
|
747 |
+
codes=[[0, 0, 0, 1, 2, 2, 2, 2, 2, 2], [1, 3, 4, 6, 0, 2, 2, 3, 5, 7]],
|
748 |
+
names=["tag", "day"],
|
749 |
+
)
|
750 |
+
|
751 |
+
assert index.get_loc("D") == slice(0, 3)
|
752 |
+
|
753 |
+
def test_get_loc_past_lexsort_depth(self):
|
754 |
+
# GH#30053
|
755 |
+
idx = MultiIndex(
|
756 |
+
levels=[["a"], [0, 7], [1]],
|
757 |
+
codes=[[0, 0], [1, 0], [0, 0]],
|
758 |
+
names=["x", "y", "z"],
|
759 |
+
sortorder=0,
|
760 |
+
)
|
761 |
+
key = ("a", 7)
|
762 |
+
|
763 |
+
with tm.assert_produces_warning(PerformanceWarning):
|
764 |
+
# PerformanceWarning: indexing past lexsort depth may impact performance
|
765 |
+
result = idx.get_loc(key)
|
766 |
+
|
767 |
+
assert result == slice(0, 1, None)
|
768 |
+
|
769 |
+
def test_multiindex_get_loc_list_raises(self):
|
770 |
+
# GH#35878
|
771 |
+
idx = MultiIndex.from_tuples([("a", 1), ("b", 2)])
|
772 |
+
msg = r"\[\]"
|
773 |
+
with pytest.raises(InvalidIndexError, match=msg):
|
774 |
+
idx.get_loc([])
|
775 |
+
|
776 |
+
def test_get_loc_nested_tuple_raises_keyerror(self):
|
777 |
+
# raise KeyError, not TypeError
|
778 |
+
mi = MultiIndex.from_product([range(3), range(4), range(5), range(6)])
|
779 |
+
key = ((2, 3, 4), "foo")
|
780 |
+
|
781 |
+
with pytest.raises(KeyError, match=re.escape(str(key))):
|
782 |
+
mi.get_loc(key)
|
783 |
+
|
784 |
+
|
785 |
+
class TestWhere:
|
786 |
+
def test_where(self):
|
787 |
+
i = MultiIndex.from_tuples([("A", 1), ("A", 2)])
|
788 |
+
|
789 |
+
msg = r"\.where is not supported for MultiIndex operations"
|
790 |
+
with pytest.raises(NotImplementedError, match=msg):
|
791 |
+
i.where(True)
|
792 |
+
|
793 |
+
def test_where_array_like(self, listlike_box):
|
794 |
+
mi = MultiIndex.from_tuples([("A", 1), ("A", 2)])
|
795 |
+
cond = [False, True]
|
796 |
+
msg = r"\.where is not supported for MultiIndex operations"
|
797 |
+
with pytest.raises(NotImplementedError, match=msg):
|
798 |
+
mi.where(listlike_box(cond))
|
799 |
+
|
800 |
+
|
801 |
+
class TestContains:
|
802 |
+
def test_contains_top_level(self):
|
803 |
+
midx = MultiIndex.from_product([["A", "B"], [1, 2]])
|
804 |
+
assert "A" in midx
|
805 |
+
assert "A" not in midx._engine
|
806 |
+
|
807 |
+
def test_contains_with_nat(self):
|
808 |
+
# MI with a NaT
|
809 |
+
mi = MultiIndex(
|
810 |
+
levels=[["C"], date_range("2012-01-01", periods=5)],
|
811 |
+
codes=[[0, 0, 0, 0, 0, 0], [-1, 0, 1, 2, 3, 4]],
|
812 |
+
names=[None, "B"],
|
813 |
+
)
|
814 |
+
assert ("C", pd.Timestamp("2012-01-01")) in mi
|
815 |
+
for val in mi.values:
|
816 |
+
assert val in mi
|
817 |
+
|
818 |
+
def test_contains(self, idx):
|
819 |
+
assert ("foo", "two") in idx
|
820 |
+
assert ("bar", "two") not in idx
|
821 |
+
assert None not in idx
|
822 |
+
|
823 |
+
def test_contains_with_missing_value(self):
|
824 |
+
# GH#19132
|
825 |
+
idx = MultiIndex.from_arrays([[1, np.nan, 2]])
|
826 |
+
assert np.nan in idx
|
827 |
+
|
828 |
+
idx = MultiIndex.from_arrays([[1, 2], [np.nan, 3]])
|
829 |
+
assert np.nan not in idx
|
830 |
+
assert (1, np.nan) in idx
|
831 |
+
|
832 |
+
def test_multiindex_contains_dropped(self):
|
833 |
+
# GH#19027
|
834 |
+
# test that dropped MultiIndex levels are not in the MultiIndex
|
835 |
+
# despite continuing to be in the MultiIndex's levels
|
836 |
+
idx = MultiIndex.from_product([[1, 2], [3, 4]])
|
837 |
+
assert 2 in idx
|
838 |
+
idx = idx.drop(2)
|
839 |
+
|
840 |
+
# drop implementation keeps 2 in the levels
|
841 |
+
assert 2 in idx.levels[0]
|
842 |
+
# but it should no longer be in the index itself
|
843 |
+
assert 2 not in idx
|
844 |
+
|
845 |
+
# also applies to strings
|
846 |
+
idx = MultiIndex.from_product([["a", "b"], ["c", "d"]])
|
847 |
+
assert "a" in idx
|
848 |
+
idx = idx.drop("a")
|
849 |
+
assert "a" in idx.levels[0]
|
850 |
+
assert "a" not in idx
|
851 |
+
|
852 |
+
def test_contains_td64_level(self):
|
853 |
+
# GH#24570
|
854 |
+
tx = pd.timedelta_range("09:30:00", "16:00:00", freq="30 min")
|
855 |
+
idx = MultiIndex.from_arrays([tx, np.arange(len(tx))])
|
856 |
+
assert tx[0] in idx
|
857 |
+
assert "element_not_exit" not in idx
|
858 |
+
assert "0 day 09:30:00" in idx
|
859 |
+
|
860 |
+
def test_large_mi_contains(self, monkeypatch):
|
861 |
+
# GH#10645
|
862 |
+
with monkeypatch.context():
|
863 |
+
monkeypatch.setattr(libindex, "_SIZE_CUTOFF", 10)
|
864 |
+
result = MultiIndex.from_arrays([range(10), range(10)])
|
865 |
+
assert (10, 0) not in result
|
866 |
+
|
867 |
+
|
868 |
+
def test_timestamp_multiindex_indexer():
|
869 |
+
# https://github.com/pandas-dev/pandas/issues/26944
|
870 |
+
idx = MultiIndex.from_product(
|
871 |
+
[
|
872 |
+
date_range("2019-01-01T00:15:33", periods=100, freq="h", name="date"),
|
873 |
+
["x"],
|
874 |
+
[3],
|
875 |
+
]
|
876 |
+
)
|
877 |
+
df = DataFrame({"foo": np.arange(len(idx))}, idx)
|
878 |
+
result = df.loc[pd.IndexSlice["2019-1-2":, "x", :], "foo"]
|
879 |
+
qidx = MultiIndex.from_product(
|
880 |
+
[
|
881 |
+
date_range(
|
882 |
+
start="2019-01-02T00:15:33",
|
883 |
+
end="2019-01-05T03:15:33",
|
884 |
+
freq="h",
|
885 |
+
name="date",
|
886 |
+
),
|
887 |
+
["x"],
|
888 |
+
[3],
|
889 |
+
]
|
890 |
+
)
|
891 |
+
should_be = pd.Series(data=np.arange(24, len(qidx) + 24), index=qidx, name="foo")
|
892 |
+
tm.assert_series_equal(result, should_be)
|
893 |
+
|
894 |
+
|
895 |
+
@pytest.mark.parametrize(
|
896 |
+
"index_arr,expected,target,algo",
|
897 |
+
[
|
898 |
+
([[np.nan, "a", "b"], ["c", "d", "e"]], 0, np.nan, "left"),
|
899 |
+
([[np.nan, "a", "b"], ["c", "d", "e"]], 1, (np.nan, "c"), "right"),
|
900 |
+
([["a", "b", "c"], ["d", np.nan, "d"]], 1, ("b", np.nan), "left"),
|
901 |
+
],
|
902 |
+
)
|
903 |
+
def test_get_slice_bound_with_missing_value(index_arr, expected, target, algo):
|
904 |
+
# issue 19132
|
905 |
+
idx = MultiIndex.from_arrays(index_arr)
|
906 |
+
result = idx.get_slice_bound(target, side=algo)
|
907 |
+
assert result == expected
|
908 |
+
|
909 |
+
|
910 |
+
@pytest.mark.parametrize(
|
911 |
+
"index_arr,expected,start_idx,end_idx",
|
912 |
+
[
|
913 |
+
([[np.nan, 1, 2], [3, 4, 5]], slice(0, 2, None), np.nan, 1),
|
914 |
+
([[np.nan, 1, 2], [3, 4, 5]], slice(0, 3, None), np.nan, (2, 5)),
|
915 |
+
([[1, 2, 3], [4, np.nan, 5]], slice(1, 3, None), (2, np.nan), 3),
|
916 |
+
([[1, 2, 3], [4, np.nan, 5]], slice(1, 3, None), (2, np.nan), (3, 5)),
|
917 |
+
],
|
918 |
+
)
|
919 |
+
def test_slice_indexer_with_missing_value(index_arr, expected, start_idx, end_idx):
|
920 |
+
# issue 19132
|
921 |
+
idx = MultiIndex.from_arrays(index_arr)
|
922 |
+
result = idx.slice_indexer(start=start_idx, end=end_idx)
|
923 |
+
assert result == expected
|
924 |
+
|
925 |
+
|
926 |
+
def test_pyint_engine():
|
927 |
+
# GH#18519 : when combinations of codes cannot be represented in 64
|
928 |
+
# bits, the index underlying the MultiIndex engine works with Python
|
929 |
+
# integers, rather than uint64.
|
930 |
+
N = 5
|
931 |
+
keys = [
|
932 |
+
tuple(arr)
|
933 |
+
for arr in [
|
934 |
+
[0] * 10 * N,
|
935 |
+
[1] * 10 * N,
|
936 |
+
[2] * 10 * N,
|
937 |
+
[np.nan] * N + [2] * 9 * N,
|
938 |
+
[0] * N + [2] * 9 * N,
|
939 |
+
[np.nan] * N + [2] * 8 * N + [0] * N,
|
940 |
+
]
|
941 |
+
]
|
942 |
+
# Each level contains 4 elements (including NaN), so it is represented
|
943 |
+
# in 2 bits, for a total of 2*N*10 = 100 > 64 bits. If we were using a
|
944 |
+
# 64 bit engine and truncating the first levels, the fourth and fifth
|
945 |
+
# keys would collide; if truncating the last levels, the fifth and
|
946 |
+
# sixth; if rotating bits rather than shifting, the third and fifth.
|
947 |
+
|
948 |
+
for idx, key_value in enumerate(keys):
|
949 |
+
index = MultiIndex.from_tuples(keys)
|
950 |
+
assert index.get_loc(key_value) == idx
|
951 |
+
|
952 |
+
expected = np.arange(idx + 1, dtype=np.intp)
|
953 |
+
result = index.get_indexer([keys[i] for i in expected])
|
954 |
+
tm.assert_numpy_array_equal(result, expected)
|
955 |
+
|
956 |
+
# With missing key:
|
957 |
+
idces = range(len(keys))
|
958 |
+
expected = np.array([-1] + list(idces), dtype=np.intp)
|
959 |
+
missing = tuple([0, 1] * 5 * N)
|
960 |
+
result = index.get_indexer([missing] + [keys[i] for i in idces])
|
961 |
+
tm.assert_numpy_array_equal(result, expected)
|
962 |
+
|
963 |
+
|
964 |
+
@pytest.mark.parametrize(
|
965 |
+
"keys,expected",
|
966 |
+
[
|
967 |
+
((slice(None), [5, 4]), [1, 0]),
|
968 |
+
((slice(None), [4, 5]), [0, 1]),
|
969 |
+
(([True, False, True], [4, 6]), [0, 2]),
|
970 |
+
(([True, False, True], [6, 4]), [0, 2]),
|
971 |
+
((2, [4, 5]), [0, 1]),
|
972 |
+
((2, [5, 4]), [1, 0]),
|
973 |
+
(([2], [4, 5]), [0, 1]),
|
974 |
+
(([2], [5, 4]), [1, 0]),
|
975 |
+
],
|
976 |
+
)
|
977 |
+
def test_get_locs_reordering(keys, expected):
|
978 |
+
# GH48384
|
979 |
+
idx = MultiIndex.from_arrays(
|
980 |
+
[
|
981 |
+
[2, 2, 1],
|
982 |
+
[4, 5, 6],
|
983 |
+
]
|
984 |
+
)
|
985 |
+
result = idx.get_locs(keys)
|
986 |
+
expected = np.array(expected, dtype=np.intp)
|
987 |
+
tm.assert_numpy_array_equal(result, expected)
|
988 |
+
|
989 |
+
|
990 |
+
def test_get_indexer_for_multiindex_with_nans(nulls_fixture):
|
991 |
+
# GH37222
|
992 |
+
idx1 = MultiIndex.from_product([["A"], [1.0, 2.0]], names=["id1", "id2"])
|
993 |
+
idx2 = MultiIndex.from_product([["A"], [nulls_fixture, 2.0]], names=["id1", "id2"])
|
994 |
+
|
995 |
+
result = idx2.get_indexer(idx1)
|
996 |
+
expected = np.array([-1, 1], dtype=np.intp)
|
997 |
+
tm.assert_numpy_array_equal(result, expected)
|
998 |
+
|
999 |
+
result = idx1.get_indexer(idx2)
|
1000 |
+
expected = np.array([-1, 1], dtype=np.intp)
|
1001 |
+
tm.assert_numpy_array_equal(result, expected)
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/test_integrity.py
ADDED
@@ -0,0 +1,289 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
import pytest
|
5 |
+
|
6 |
+
from pandas._libs import index as libindex
|
7 |
+
|
8 |
+
from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike
|
9 |
+
|
10 |
+
import pandas as pd
|
11 |
+
from pandas import (
|
12 |
+
Index,
|
13 |
+
IntervalIndex,
|
14 |
+
MultiIndex,
|
15 |
+
RangeIndex,
|
16 |
+
)
|
17 |
+
import pandas._testing as tm
|
18 |
+
|
19 |
+
|
20 |
+
def test_labels_dtypes():
|
21 |
+
# GH 8456
|
22 |
+
i = MultiIndex.from_tuples([("A", 1), ("A", 2)])
|
23 |
+
assert i.codes[0].dtype == "int8"
|
24 |
+
assert i.codes[1].dtype == "int8"
|
25 |
+
|
26 |
+
i = MultiIndex.from_product([["a"], range(40)])
|
27 |
+
assert i.codes[1].dtype == "int8"
|
28 |
+
i = MultiIndex.from_product([["a"], range(400)])
|
29 |
+
assert i.codes[1].dtype == "int16"
|
30 |
+
i = MultiIndex.from_product([["a"], range(40000)])
|
31 |
+
assert i.codes[1].dtype == "int32"
|
32 |
+
|
33 |
+
i = MultiIndex.from_product([["a"], range(1000)])
|
34 |
+
assert (i.codes[0] >= 0).all()
|
35 |
+
assert (i.codes[1] >= 0).all()
|
36 |
+
|
37 |
+
|
38 |
+
def test_values_boxed():
|
39 |
+
tuples = [
|
40 |
+
(1, pd.Timestamp("2000-01-01")),
|
41 |
+
(2, pd.NaT),
|
42 |
+
(3, pd.Timestamp("2000-01-03")),
|
43 |
+
(1, pd.Timestamp("2000-01-04")),
|
44 |
+
(2, pd.Timestamp("2000-01-02")),
|
45 |
+
(3, pd.Timestamp("2000-01-03")),
|
46 |
+
]
|
47 |
+
result = MultiIndex.from_tuples(tuples)
|
48 |
+
expected = construct_1d_object_array_from_listlike(tuples)
|
49 |
+
tm.assert_numpy_array_equal(result.values, expected)
|
50 |
+
# Check that code branches for boxed values produce identical results
|
51 |
+
tm.assert_numpy_array_equal(result.values[:4], result[:4].values)
|
52 |
+
|
53 |
+
|
54 |
+
def test_values_multiindex_datetimeindex():
|
55 |
+
# Test to ensure we hit the boxing / nobox part of MI.values
|
56 |
+
ints = np.arange(10**18, 10**18 + 5)
|
57 |
+
naive = pd.DatetimeIndex(ints)
|
58 |
+
|
59 |
+
aware = pd.DatetimeIndex(ints, tz="US/Central")
|
60 |
+
|
61 |
+
idx = MultiIndex.from_arrays([naive, aware])
|
62 |
+
result = idx.values
|
63 |
+
|
64 |
+
outer = pd.DatetimeIndex([x[0] for x in result])
|
65 |
+
tm.assert_index_equal(outer, naive)
|
66 |
+
|
67 |
+
inner = pd.DatetimeIndex([x[1] for x in result])
|
68 |
+
tm.assert_index_equal(inner, aware)
|
69 |
+
|
70 |
+
# n_lev > n_lab
|
71 |
+
result = idx[:2].values
|
72 |
+
|
73 |
+
outer = pd.DatetimeIndex([x[0] for x in result])
|
74 |
+
tm.assert_index_equal(outer, naive[:2])
|
75 |
+
|
76 |
+
inner = pd.DatetimeIndex([x[1] for x in result])
|
77 |
+
tm.assert_index_equal(inner, aware[:2])
|
78 |
+
|
79 |
+
|
80 |
+
def test_values_multiindex_periodindex():
|
81 |
+
# Test to ensure we hit the boxing / nobox part of MI.values
|
82 |
+
ints = np.arange(2007, 2012)
|
83 |
+
pidx = pd.PeriodIndex(ints, freq="D")
|
84 |
+
|
85 |
+
idx = MultiIndex.from_arrays([ints, pidx])
|
86 |
+
result = idx.values
|
87 |
+
|
88 |
+
outer = Index([x[0] for x in result])
|
89 |
+
tm.assert_index_equal(outer, Index(ints, dtype=np.int64))
|
90 |
+
|
91 |
+
inner = pd.PeriodIndex([x[1] for x in result])
|
92 |
+
tm.assert_index_equal(inner, pidx)
|
93 |
+
|
94 |
+
# n_lev > n_lab
|
95 |
+
result = idx[:2].values
|
96 |
+
|
97 |
+
outer = Index([x[0] for x in result])
|
98 |
+
tm.assert_index_equal(outer, Index(ints[:2], dtype=np.int64))
|
99 |
+
|
100 |
+
inner = pd.PeriodIndex([x[1] for x in result])
|
101 |
+
tm.assert_index_equal(inner, pidx[:2])
|
102 |
+
|
103 |
+
|
104 |
+
def test_consistency():
|
105 |
+
# need to construct an overflow
|
106 |
+
major_axis = list(range(70000))
|
107 |
+
minor_axis = list(range(10))
|
108 |
+
|
109 |
+
major_codes = np.arange(70000)
|
110 |
+
minor_codes = np.repeat(range(10), 7000)
|
111 |
+
|
112 |
+
# the fact that is works means it's consistent
|
113 |
+
index = MultiIndex(
|
114 |
+
levels=[major_axis, minor_axis], codes=[major_codes, minor_codes]
|
115 |
+
)
|
116 |
+
|
117 |
+
# inconsistent
|
118 |
+
major_codes = np.array([0, 0, 1, 1, 1, 2, 2, 3, 3])
|
119 |
+
minor_codes = np.array([0, 1, 0, 1, 1, 0, 1, 0, 1])
|
120 |
+
index = MultiIndex(
|
121 |
+
levels=[major_axis, minor_axis], codes=[major_codes, minor_codes]
|
122 |
+
)
|
123 |
+
|
124 |
+
assert index.is_unique is False
|
125 |
+
|
126 |
+
|
127 |
+
@pytest.mark.slow
|
128 |
+
def test_hash_collisions(monkeypatch):
|
129 |
+
# non-smoke test that we don't get hash collisions
|
130 |
+
size_cutoff = 50
|
131 |
+
with monkeypatch.context() as m:
|
132 |
+
m.setattr(libindex, "_SIZE_CUTOFF", size_cutoff)
|
133 |
+
index = MultiIndex.from_product(
|
134 |
+
[np.arange(8), np.arange(8)], names=["one", "two"]
|
135 |
+
)
|
136 |
+
result = index.get_indexer(index.values)
|
137 |
+
tm.assert_numpy_array_equal(result, np.arange(len(index), dtype="intp"))
|
138 |
+
|
139 |
+
for i in [0, 1, len(index) - 2, len(index) - 1]:
|
140 |
+
result = index.get_loc(index[i])
|
141 |
+
assert result == i
|
142 |
+
|
143 |
+
|
144 |
+
def test_dims():
|
145 |
+
pass
|
146 |
+
|
147 |
+
|
148 |
+
def test_take_invalid_kwargs():
|
149 |
+
vals = [["A", "B"], [pd.Timestamp("2011-01-01"), pd.Timestamp("2011-01-02")]]
|
150 |
+
idx = MultiIndex.from_product(vals, names=["str", "dt"])
|
151 |
+
indices = [1, 2]
|
152 |
+
|
153 |
+
msg = r"take\(\) got an unexpected keyword argument 'foo'"
|
154 |
+
with pytest.raises(TypeError, match=msg):
|
155 |
+
idx.take(indices, foo=2)
|
156 |
+
|
157 |
+
msg = "the 'out' parameter is not supported"
|
158 |
+
with pytest.raises(ValueError, match=msg):
|
159 |
+
idx.take(indices, out=indices)
|
160 |
+
|
161 |
+
msg = "the 'mode' parameter is not supported"
|
162 |
+
with pytest.raises(ValueError, match=msg):
|
163 |
+
idx.take(indices, mode="clip")
|
164 |
+
|
165 |
+
|
166 |
+
def test_isna_behavior(idx):
|
167 |
+
# should not segfault GH5123
|
168 |
+
# NOTE: if MI representation changes, may make sense to allow
|
169 |
+
# isna(MI)
|
170 |
+
msg = "isna is not defined for MultiIndex"
|
171 |
+
with pytest.raises(NotImplementedError, match=msg):
|
172 |
+
pd.isna(idx)
|
173 |
+
|
174 |
+
|
175 |
+
def test_large_multiindex_error(monkeypatch):
|
176 |
+
# GH12527
|
177 |
+
size_cutoff = 50
|
178 |
+
with monkeypatch.context() as m:
|
179 |
+
m.setattr(libindex, "_SIZE_CUTOFF", size_cutoff)
|
180 |
+
df_below_cutoff = pd.DataFrame(
|
181 |
+
1,
|
182 |
+
index=MultiIndex.from_product([[1, 2], range(size_cutoff - 1)]),
|
183 |
+
columns=["dest"],
|
184 |
+
)
|
185 |
+
with pytest.raises(KeyError, match=r"^\(-1, 0\)$"):
|
186 |
+
df_below_cutoff.loc[(-1, 0), "dest"]
|
187 |
+
with pytest.raises(KeyError, match=r"^\(3, 0\)$"):
|
188 |
+
df_below_cutoff.loc[(3, 0), "dest"]
|
189 |
+
df_above_cutoff = pd.DataFrame(
|
190 |
+
1,
|
191 |
+
index=MultiIndex.from_product([[1, 2], range(size_cutoff + 1)]),
|
192 |
+
columns=["dest"],
|
193 |
+
)
|
194 |
+
with pytest.raises(KeyError, match=r"^\(-1, 0\)$"):
|
195 |
+
df_above_cutoff.loc[(-1, 0), "dest"]
|
196 |
+
with pytest.raises(KeyError, match=r"^\(3, 0\)$"):
|
197 |
+
df_above_cutoff.loc[(3, 0), "dest"]
|
198 |
+
|
199 |
+
|
200 |
+
def test_mi_hashtable_populated_attribute_error(monkeypatch):
|
201 |
+
# GH 18165
|
202 |
+
monkeypatch.setattr(libindex, "_SIZE_CUTOFF", 50)
|
203 |
+
r = range(50)
|
204 |
+
df = pd.DataFrame({"a": r, "b": r}, index=MultiIndex.from_arrays([r, r]))
|
205 |
+
|
206 |
+
msg = "'Series' object has no attribute 'foo'"
|
207 |
+
with pytest.raises(AttributeError, match=msg):
|
208 |
+
df["a"].foo()
|
209 |
+
|
210 |
+
|
211 |
+
def test_can_hold_identifiers(idx):
|
212 |
+
key = idx[0]
|
213 |
+
assert idx._can_hold_identifiers_and_holds_name(key) is True
|
214 |
+
|
215 |
+
|
216 |
+
def test_metadata_immutable(idx):
|
217 |
+
levels, codes = idx.levels, idx.codes
|
218 |
+
# shouldn't be able to set at either the top level or base level
|
219 |
+
mutable_regex = re.compile("does not support mutable operations")
|
220 |
+
with pytest.raises(TypeError, match=mutable_regex):
|
221 |
+
levels[0] = levels[0]
|
222 |
+
with pytest.raises(TypeError, match=mutable_regex):
|
223 |
+
levels[0][0] = levels[0][0]
|
224 |
+
# ditto for labels
|
225 |
+
with pytest.raises(TypeError, match=mutable_regex):
|
226 |
+
codes[0] = codes[0]
|
227 |
+
with pytest.raises(ValueError, match="assignment destination is read-only"):
|
228 |
+
codes[0][0] = codes[0][0]
|
229 |
+
# and for names
|
230 |
+
names = idx.names
|
231 |
+
with pytest.raises(TypeError, match=mutable_regex):
|
232 |
+
names[0] = names[0]
|
233 |
+
|
234 |
+
|
235 |
+
def test_level_setting_resets_attributes():
|
236 |
+
ind = MultiIndex.from_arrays([["A", "A", "B", "B", "B"], [1, 2, 1, 2, 3]])
|
237 |
+
assert ind.is_monotonic_increasing
|
238 |
+
ind = ind.set_levels([["A", "B"], [1, 3, 2]])
|
239 |
+
# if this fails, probably didn't reset the cache correctly.
|
240 |
+
assert not ind.is_monotonic_increasing
|
241 |
+
|
242 |
+
|
243 |
+
def test_rangeindex_fallback_coercion_bug():
|
244 |
+
# GH 12893
|
245 |
+
df1 = pd.DataFrame(np.arange(100).reshape((10, 10)))
|
246 |
+
df2 = pd.DataFrame(np.arange(100).reshape((10, 10)))
|
247 |
+
df = pd.concat(
|
248 |
+
{"df1": df1.stack(future_stack=True), "df2": df2.stack(future_stack=True)},
|
249 |
+
axis=1,
|
250 |
+
)
|
251 |
+
df.index.names = ["fizz", "buzz"]
|
252 |
+
|
253 |
+
expected = pd.DataFrame(
|
254 |
+
{"df2": np.arange(100), "df1": np.arange(100)},
|
255 |
+
index=MultiIndex.from_product([range(10), range(10)], names=["fizz", "buzz"]),
|
256 |
+
)
|
257 |
+
tm.assert_frame_equal(df, expected, check_like=True)
|
258 |
+
|
259 |
+
result = df.index.get_level_values("fizz")
|
260 |
+
expected = Index(np.arange(10, dtype=np.int64), name="fizz").repeat(10)
|
261 |
+
tm.assert_index_equal(result, expected)
|
262 |
+
|
263 |
+
result = df.index.get_level_values("buzz")
|
264 |
+
expected = Index(np.tile(np.arange(10, dtype=np.int64), 10), name="buzz")
|
265 |
+
tm.assert_index_equal(result, expected)
|
266 |
+
|
267 |
+
|
268 |
+
def test_memory_usage(idx):
|
269 |
+
result = idx.memory_usage()
|
270 |
+
if len(idx):
|
271 |
+
idx.get_loc(idx[0])
|
272 |
+
result2 = idx.memory_usage()
|
273 |
+
result3 = idx.memory_usage(deep=True)
|
274 |
+
|
275 |
+
# RangeIndex, IntervalIndex
|
276 |
+
# don't have engines
|
277 |
+
if not isinstance(idx, (RangeIndex, IntervalIndex)):
|
278 |
+
assert result2 > result
|
279 |
+
|
280 |
+
if idx.inferred_type == "object":
|
281 |
+
assert result3 > result2
|
282 |
+
|
283 |
+
else:
|
284 |
+
# we report 0 for no-length
|
285 |
+
assert result == 0
|
286 |
+
|
287 |
+
|
288 |
+
def test_nlevels(idx):
|
289 |
+
assert idx.nlevels == 2
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/test_lexsort.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from pandas import MultiIndex
|
2 |
+
|
3 |
+
|
4 |
+
class TestIsLexsorted:
|
5 |
+
def test_is_lexsorted(self):
|
6 |
+
levels = [[0, 1], [0, 1, 2]]
|
7 |
+
|
8 |
+
index = MultiIndex(
|
9 |
+
levels=levels, codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]]
|
10 |
+
)
|
11 |
+
assert index._is_lexsorted()
|
12 |
+
|
13 |
+
index = MultiIndex(
|
14 |
+
levels=levels, codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 2, 1]]
|
15 |
+
)
|
16 |
+
assert not index._is_lexsorted()
|
17 |
+
|
18 |
+
index = MultiIndex(
|
19 |
+
levels=levels, codes=[[0, 0, 1, 0, 1, 1], [0, 1, 0, 2, 2, 1]]
|
20 |
+
)
|
21 |
+
assert not index._is_lexsorted()
|
22 |
+
assert index._lexsort_depth == 0
|
23 |
+
|
24 |
+
|
25 |
+
class TestLexsortDepth:
|
26 |
+
def test_lexsort_depth(self):
|
27 |
+
# Test that lexsort_depth return the correct sortorder
|
28 |
+
# when it was given to the MultiIndex const.
|
29 |
+
# GH#28518
|
30 |
+
|
31 |
+
levels = [[0, 1], [0, 1, 2]]
|
32 |
+
|
33 |
+
index = MultiIndex(
|
34 |
+
levels=levels, codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]], sortorder=2
|
35 |
+
)
|
36 |
+
assert index._lexsort_depth == 2
|
37 |
+
|
38 |
+
index = MultiIndex(
|
39 |
+
levels=levels, codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 2, 1]], sortorder=1
|
40 |
+
)
|
41 |
+
assert index._lexsort_depth == 1
|
42 |
+
|
43 |
+
index = MultiIndex(
|
44 |
+
levels=levels, codes=[[0, 0, 1, 0, 1, 1], [0, 1, 0, 2, 2, 1]], sortorder=0
|
45 |
+
)
|
46 |
+
assert index._lexsort_depth == 0
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/test_missing.py
ADDED
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
import pandas as pd
|
5 |
+
from pandas import MultiIndex
|
6 |
+
import pandas._testing as tm
|
7 |
+
|
8 |
+
|
9 |
+
def test_fillna(idx):
|
10 |
+
# GH 11343
|
11 |
+
msg = "isna is not defined for MultiIndex"
|
12 |
+
with pytest.raises(NotImplementedError, match=msg):
|
13 |
+
idx.fillna(idx[0])
|
14 |
+
|
15 |
+
|
16 |
+
def test_dropna():
|
17 |
+
# GH 6194
|
18 |
+
idx = MultiIndex.from_arrays(
|
19 |
+
[
|
20 |
+
[1, np.nan, 3, np.nan, 5],
|
21 |
+
[1, 2, np.nan, np.nan, 5],
|
22 |
+
["a", "b", "c", np.nan, "e"],
|
23 |
+
]
|
24 |
+
)
|
25 |
+
|
26 |
+
exp = MultiIndex.from_arrays([[1, 5], [1, 5], ["a", "e"]])
|
27 |
+
tm.assert_index_equal(idx.dropna(), exp)
|
28 |
+
tm.assert_index_equal(idx.dropna(how="any"), exp)
|
29 |
+
|
30 |
+
exp = MultiIndex.from_arrays(
|
31 |
+
[[1, np.nan, 3, 5], [1, 2, np.nan, 5], ["a", "b", "c", "e"]]
|
32 |
+
)
|
33 |
+
tm.assert_index_equal(idx.dropna(how="all"), exp)
|
34 |
+
|
35 |
+
msg = "invalid how option: xxx"
|
36 |
+
with pytest.raises(ValueError, match=msg):
|
37 |
+
idx.dropna(how="xxx")
|
38 |
+
|
39 |
+
# GH26408
|
40 |
+
# test if missing values are dropped for multiindex constructed
|
41 |
+
# from codes and values
|
42 |
+
idx = MultiIndex(
|
43 |
+
levels=[[np.nan, None, pd.NaT, "128", 2], [np.nan, None, pd.NaT, "128", 2]],
|
44 |
+
codes=[[0, -1, 1, 2, 3, 4], [0, -1, 3, 3, 3, 4]],
|
45 |
+
)
|
46 |
+
expected = MultiIndex.from_arrays([["128", 2], ["128", 2]])
|
47 |
+
tm.assert_index_equal(idx.dropna(), expected)
|
48 |
+
tm.assert_index_equal(idx.dropna(how="any"), expected)
|
49 |
+
|
50 |
+
expected = MultiIndex.from_arrays(
|
51 |
+
[[np.nan, np.nan, "128", 2], ["128", "128", "128", 2]]
|
52 |
+
)
|
53 |
+
tm.assert_index_equal(idx.dropna(how="all"), expected)
|
54 |
+
|
55 |
+
|
56 |
+
def test_nulls(idx):
|
57 |
+
# this is really a smoke test for the methods
|
58 |
+
# as these are adequately tested for function elsewhere
|
59 |
+
|
60 |
+
msg = "isna is not defined for MultiIndex"
|
61 |
+
with pytest.raises(NotImplementedError, match=msg):
|
62 |
+
idx.isna()
|
63 |
+
|
64 |
+
|
65 |
+
@pytest.mark.xfail(reason="isna is not defined for MultiIndex")
|
66 |
+
def test_hasnans_isnans(idx):
|
67 |
+
# GH 11343, added tests for hasnans / isnans
|
68 |
+
index = idx.copy()
|
69 |
+
|
70 |
+
# cases in indices doesn't include NaN
|
71 |
+
expected = np.array([False] * len(index), dtype=bool)
|
72 |
+
tm.assert_numpy_array_equal(index._isnan, expected)
|
73 |
+
assert index.hasnans is False
|
74 |
+
|
75 |
+
index = idx.copy()
|
76 |
+
values = index.values
|
77 |
+
values[1] = np.nan
|
78 |
+
|
79 |
+
index = type(idx)(values)
|
80 |
+
|
81 |
+
expected = np.array([False] * len(index), dtype=bool)
|
82 |
+
expected[1] = True
|
83 |
+
tm.assert_numpy_array_equal(index._isnan, expected)
|
84 |
+
assert index.hasnans is True
|
85 |
+
|
86 |
+
|
87 |
+
def test_nan_stays_float():
|
88 |
+
# GH 7031
|
89 |
+
idx0 = MultiIndex(levels=[["A", "B"], []], codes=[[1, 0], [-1, -1]], names=[0, 1])
|
90 |
+
idx1 = MultiIndex(levels=[["C"], ["D"]], codes=[[0], [0]], names=[0, 1])
|
91 |
+
idxm = idx0.join(idx1, how="outer")
|
92 |
+
assert pd.isna(idx0.get_level_values(1)).all()
|
93 |
+
# the following failed in 0.14.1
|
94 |
+
assert pd.isna(idxm.get_level_values(1)[:-1]).all()
|
95 |
+
|
96 |
+
df0 = pd.DataFrame([[1, 2]], index=idx0)
|
97 |
+
df1 = pd.DataFrame([[3, 4]], index=idx1)
|
98 |
+
dfm = df0 - df1
|
99 |
+
assert pd.isna(df0.index.get_level_values(1)).all()
|
100 |
+
# the following failed in 0.14.1
|
101 |
+
assert pd.isna(dfm.index.get_level_values(1)[:-1]).all()
|
102 |
+
|
103 |
+
|
104 |
+
def test_tuples_have_na():
|
105 |
+
index = MultiIndex(
|
106 |
+
levels=[[1, 0], [0, 1, 2, 3]],
|
107 |
+
codes=[[1, 1, 1, 1, -1, 0, 0, 0], [0, 1, 2, 3, 0, 1, 2, 3]],
|
108 |
+
)
|
109 |
+
|
110 |
+
assert pd.isna(index[4][0])
|
111 |
+
assert pd.isna(index.values[4][0])
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/test_partial_indexing.py
ADDED
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas import (
|
5 |
+
DataFrame,
|
6 |
+
IndexSlice,
|
7 |
+
MultiIndex,
|
8 |
+
date_range,
|
9 |
+
)
|
10 |
+
import pandas._testing as tm
|
11 |
+
|
12 |
+
|
13 |
+
@pytest.fixture
|
14 |
+
def df():
|
15 |
+
# c1
|
16 |
+
# 2016-01-01 00:00:00 a 0
|
17 |
+
# b 1
|
18 |
+
# c 2
|
19 |
+
# 2016-01-01 12:00:00 a 3
|
20 |
+
# b 4
|
21 |
+
# c 5
|
22 |
+
# 2016-01-02 00:00:00 a 6
|
23 |
+
# b 7
|
24 |
+
# c 8
|
25 |
+
# 2016-01-02 12:00:00 a 9
|
26 |
+
# b 10
|
27 |
+
# c 11
|
28 |
+
# 2016-01-03 00:00:00 a 12
|
29 |
+
# b 13
|
30 |
+
# c 14
|
31 |
+
dr = date_range("2016-01-01", "2016-01-03", freq="12h")
|
32 |
+
abc = ["a", "b", "c"]
|
33 |
+
mi = MultiIndex.from_product([dr, abc])
|
34 |
+
frame = DataFrame({"c1": range(15)}, index=mi)
|
35 |
+
return frame
|
36 |
+
|
37 |
+
|
38 |
+
def test_partial_string_matching_single_index(df):
|
39 |
+
# partial string matching on a single index
|
40 |
+
for df_swap in [df.swaplevel(), df.swaplevel(0), df.swaplevel(0, 1)]:
|
41 |
+
df_swap = df_swap.sort_index()
|
42 |
+
just_a = df_swap.loc["a"]
|
43 |
+
result = just_a.loc["2016-01-01"]
|
44 |
+
expected = df.loc[IndexSlice[:, "a"], :].iloc[0:2]
|
45 |
+
expected.index = expected.index.droplevel(1)
|
46 |
+
tm.assert_frame_equal(result, expected)
|
47 |
+
|
48 |
+
|
49 |
+
def test_get_loc_partial_timestamp_multiindex(df):
|
50 |
+
mi = df.index
|
51 |
+
key = ("2016-01-01", "a")
|
52 |
+
loc = mi.get_loc(key)
|
53 |
+
|
54 |
+
expected = np.zeros(len(mi), dtype=bool)
|
55 |
+
expected[[0, 3]] = True
|
56 |
+
tm.assert_numpy_array_equal(loc, expected)
|
57 |
+
|
58 |
+
key2 = ("2016-01-02", "a")
|
59 |
+
loc2 = mi.get_loc(key2)
|
60 |
+
expected2 = np.zeros(len(mi), dtype=bool)
|
61 |
+
expected2[[6, 9]] = True
|
62 |
+
tm.assert_numpy_array_equal(loc2, expected2)
|
63 |
+
|
64 |
+
key3 = ("2016-01", "a")
|
65 |
+
loc3 = mi.get_loc(key3)
|
66 |
+
expected3 = np.zeros(len(mi), dtype=bool)
|
67 |
+
expected3[mi.get_level_values(1).get_loc("a")] = True
|
68 |
+
tm.assert_numpy_array_equal(loc3, expected3)
|
69 |
+
|
70 |
+
key4 = ("2016", "a")
|
71 |
+
loc4 = mi.get_loc(key4)
|
72 |
+
expected4 = expected3
|
73 |
+
tm.assert_numpy_array_equal(loc4, expected4)
|
74 |
+
|
75 |
+
# non-monotonic
|
76 |
+
taker = np.arange(len(mi), dtype=np.intp)
|
77 |
+
taker[::2] = taker[::-2]
|
78 |
+
mi2 = mi.take(taker)
|
79 |
+
loc5 = mi2.get_loc(key)
|
80 |
+
expected5 = np.zeros(len(mi2), dtype=bool)
|
81 |
+
expected5[[3, 14]] = True
|
82 |
+
tm.assert_numpy_array_equal(loc5, expected5)
|
83 |
+
|
84 |
+
|
85 |
+
def test_partial_string_timestamp_multiindex(df):
|
86 |
+
# GH10331
|
87 |
+
df_swap = df.swaplevel(0, 1).sort_index()
|
88 |
+
SLC = IndexSlice
|
89 |
+
|
90 |
+
# indexing with IndexSlice
|
91 |
+
result = df.loc[SLC["2016-01-01":"2016-02-01", :], :]
|
92 |
+
expected = df
|
93 |
+
tm.assert_frame_equal(result, expected)
|
94 |
+
|
95 |
+
# match on secondary index
|
96 |
+
result = df_swap.loc[SLC[:, "2016-01-01":"2016-01-01"], :]
|
97 |
+
expected = df_swap.iloc[[0, 1, 5, 6, 10, 11]]
|
98 |
+
tm.assert_frame_equal(result, expected)
|
99 |
+
|
100 |
+
# partial string match on year only
|
101 |
+
result = df.loc["2016"]
|
102 |
+
expected = df
|
103 |
+
tm.assert_frame_equal(result, expected)
|
104 |
+
|
105 |
+
# partial string match on date
|
106 |
+
result = df.loc["2016-01-01"]
|
107 |
+
expected = df.iloc[0:6]
|
108 |
+
tm.assert_frame_equal(result, expected)
|
109 |
+
|
110 |
+
# partial string match on date and hour, from middle
|
111 |
+
result = df.loc["2016-01-02 12"]
|
112 |
+
# hourly resolution, same as index.levels[0], so we are _not_ slicing on
|
113 |
+
# that level, so that level gets dropped
|
114 |
+
expected = df.iloc[9:12].droplevel(0)
|
115 |
+
tm.assert_frame_equal(result, expected)
|
116 |
+
|
117 |
+
# partial string match on secondary index
|
118 |
+
result = df_swap.loc[SLC[:, "2016-01-02"], :]
|
119 |
+
expected = df_swap.iloc[[2, 3, 7, 8, 12, 13]]
|
120 |
+
tm.assert_frame_equal(result, expected)
|
121 |
+
|
122 |
+
# tuple selector with partial string match on date
|
123 |
+
# "2016-01-01" has daily resolution, so _is_ a slice on the first level.
|
124 |
+
result = df.loc[("2016-01-01", "a"), :]
|
125 |
+
expected = df.iloc[[0, 3]]
|
126 |
+
expected = df.iloc[[0, 3]].droplevel(1)
|
127 |
+
tm.assert_frame_equal(result, expected)
|
128 |
+
|
129 |
+
# Slicing date on first level should break (of course) bc the DTI is the
|
130 |
+
# second level on df_swap
|
131 |
+
with pytest.raises(KeyError, match="'2016-01-01'"):
|
132 |
+
df_swap.loc["2016-01-01"]
|
133 |
+
|
134 |
+
|
135 |
+
def test_partial_string_timestamp_multiindex_str_key_raises(df):
|
136 |
+
# Even though this syntax works on a single index, this is somewhat
|
137 |
+
# ambiguous and we don't want to extend this behavior forward to work
|
138 |
+
# in multi-indexes. This would amount to selecting a scalar from a
|
139 |
+
# column.
|
140 |
+
with pytest.raises(KeyError, match="'2016-01-01'"):
|
141 |
+
df["2016-01-01"]
|
142 |
+
|
143 |
+
|
144 |
+
def test_partial_string_timestamp_multiindex_daily_resolution(df):
|
145 |
+
# GH12685 (partial string with daily resolution or below)
|
146 |
+
result = df.loc[IndexSlice["2013-03":"2013-03", :], :]
|
147 |
+
expected = df.iloc[118:180]
|
148 |
+
tm.assert_frame_equal(result, expected)
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/test_pickle.py
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
from pandas import MultiIndex
|
4 |
+
|
5 |
+
|
6 |
+
def test_pickle_compat_construction():
|
7 |
+
# this is testing for pickle compat
|
8 |
+
# need an object to create with
|
9 |
+
with pytest.raises(TypeError, match="Must pass both levels and codes"):
|
10 |
+
MultiIndex()
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/test_reindex.py
ADDED
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
import pandas as pd
|
5 |
+
from pandas import (
|
6 |
+
Index,
|
7 |
+
MultiIndex,
|
8 |
+
)
|
9 |
+
import pandas._testing as tm
|
10 |
+
|
11 |
+
|
12 |
+
def test_reindex(idx):
|
13 |
+
result, indexer = idx.reindex(list(idx[:4]))
|
14 |
+
assert isinstance(result, MultiIndex)
|
15 |
+
assert result.names == ["first", "second"]
|
16 |
+
assert [level.name for level in result.levels] == ["first", "second"]
|
17 |
+
|
18 |
+
result, indexer = idx.reindex(list(idx))
|
19 |
+
assert isinstance(result, MultiIndex)
|
20 |
+
assert indexer is None
|
21 |
+
assert result.names == ["first", "second"]
|
22 |
+
assert [level.name for level in result.levels] == ["first", "second"]
|
23 |
+
|
24 |
+
|
25 |
+
def test_reindex_level(idx):
|
26 |
+
index = Index(["one"])
|
27 |
+
|
28 |
+
target, indexer = idx.reindex(index, level="second")
|
29 |
+
target2, indexer2 = index.reindex(idx, level="second")
|
30 |
+
|
31 |
+
exp_index = idx.join(index, level="second", how="right")
|
32 |
+
exp_index2 = idx.join(index, level="second", how="left")
|
33 |
+
|
34 |
+
assert target.equals(exp_index)
|
35 |
+
exp_indexer = np.array([0, 2, 4])
|
36 |
+
tm.assert_numpy_array_equal(indexer, exp_indexer, check_dtype=False)
|
37 |
+
|
38 |
+
assert target2.equals(exp_index2)
|
39 |
+
exp_indexer2 = np.array([0, -1, 0, -1, 0, -1])
|
40 |
+
tm.assert_numpy_array_equal(indexer2, exp_indexer2, check_dtype=False)
|
41 |
+
|
42 |
+
with pytest.raises(TypeError, match="Fill method not supported"):
|
43 |
+
idx.reindex(idx, method="pad", level="second")
|
44 |
+
|
45 |
+
|
46 |
+
def test_reindex_preserves_names_when_target_is_list_or_ndarray(idx):
|
47 |
+
# GH6552
|
48 |
+
idx = idx.copy()
|
49 |
+
target = idx.copy()
|
50 |
+
idx.names = target.names = [None, None]
|
51 |
+
|
52 |
+
other_dtype = MultiIndex.from_product([[1, 2], [3, 4]])
|
53 |
+
|
54 |
+
# list & ndarray cases
|
55 |
+
assert idx.reindex([])[0].names == [None, None]
|
56 |
+
assert idx.reindex(np.array([]))[0].names == [None, None]
|
57 |
+
assert idx.reindex(target.tolist())[0].names == [None, None]
|
58 |
+
assert idx.reindex(target.values)[0].names == [None, None]
|
59 |
+
assert idx.reindex(other_dtype.tolist())[0].names == [None, None]
|
60 |
+
assert idx.reindex(other_dtype.values)[0].names == [None, None]
|
61 |
+
|
62 |
+
idx.names = ["foo", "bar"]
|
63 |
+
assert idx.reindex([])[0].names == ["foo", "bar"]
|
64 |
+
assert idx.reindex(np.array([]))[0].names == ["foo", "bar"]
|
65 |
+
assert idx.reindex(target.tolist())[0].names == ["foo", "bar"]
|
66 |
+
assert idx.reindex(target.values)[0].names == ["foo", "bar"]
|
67 |
+
assert idx.reindex(other_dtype.tolist())[0].names == ["foo", "bar"]
|
68 |
+
assert idx.reindex(other_dtype.values)[0].names == ["foo", "bar"]
|
69 |
+
|
70 |
+
|
71 |
+
def test_reindex_lvl_preserves_names_when_target_is_list_or_array():
|
72 |
+
# GH7774
|
73 |
+
idx = MultiIndex.from_product([[0, 1], ["a", "b"]], names=["foo", "bar"])
|
74 |
+
assert idx.reindex([], level=0)[0].names == ["foo", "bar"]
|
75 |
+
assert idx.reindex([], level=1)[0].names == ["foo", "bar"]
|
76 |
+
|
77 |
+
|
78 |
+
def test_reindex_lvl_preserves_type_if_target_is_empty_list_or_array(
|
79 |
+
using_infer_string,
|
80 |
+
):
|
81 |
+
# GH7774
|
82 |
+
idx = MultiIndex.from_product([[0, 1], ["a", "b"]])
|
83 |
+
assert idx.reindex([], level=0)[0].levels[0].dtype.type == np.int64
|
84 |
+
exp = np.object_ if not using_infer_string else str
|
85 |
+
assert idx.reindex([], level=1)[0].levels[1].dtype.type == exp
|
86 |
+
|
87 |
+
# case with EA levels
|
88 |
+
cat = pd.Categorical(["foo", "bar"])
|
89 |
+
dti = pd.date_range("2016-01-01", periods=2, tz="US/Pacific")
|
90 |
+
mi = MultiIndex.from_product([cat, dti])
|
91 |
+
assert mi.reindex([], level=0)[0].levels[0].dtype == cat.dtype
|
92 |
+
assert mi.reindex([], level=1)[0].levels[1].dtype == dti.dtype
|
93 |
+
|
94 |
+
|
95 |
+
def test_reindex_base(idx):
|
96 |
+
expected = np.arange(idx.size, dtype=np.intp)
|
97 |
+
|
98 |
+
actual = idx.get_indexer(idx)
|
99 |
+
tm.assert_numpy_array_equal(expected, actual)
|
100 |
+
|
101 |
+
with pytest.raises(ValueError, match="Invalid fill method"):
|
102 |
+
idx.get_indexer(idx, method="invalid")
|
103 |
+
|
104 |
+
|
105 |
+
def test_reindex_non_unique():
|
106 |
+
idx = MultiIndex.from_tuples([(0, 0), (1, 1), (1, 1), (2, 2)])
|
107 |
+
a = pd.Series(np.arange(4), index=idx)
|
108 |
+
new_idx = MultiIndex.from_tuples([(0, 0), (1, 1), (2, 2)])
|
109 |
+
|
110 |
+
msg = "cannot handle a non-unique multi-index!"
|
111 |
+
with pytest.raises(ValueError, match=msg):
|
112 |
+
a.reindex(new_idx)
|
113 |
+
|
114 |
+
|
115 |
+
@pytest.mark.parametrize("values", [[["a"], ["x"]], [[], []]])
|
116 |
+
def test_reindex_empty_with_level(values):
|
117 |
+
# GH41170
|
118 |
+
idx = MultiIndex.from_arrays(values)
|
119 |
+
result, result_indexer = idx.reindex(np.array(["b"]), level=0)
|
120 |
+
expected = MultiIndex(levels=[["b"], values[1]], codes=[[], []])
|
121 |
+
expected_indexer = np.array([], dtype=result_indexer.dtype)
|
122 |
+
tm.assert_index_equal(result, expected)
|
123 |
+
tm.assert_numpy_array_equal(result_indexer, expected_indexer)
|
124 |
+
|
125 |
+
|
126 |
+
def test_reindex_not_all_tuples():
|
127 |
+
keys = [("i", "i"), ("i", "j"), ("j", "i"), "j"]
|
128 |
+
mi = MultiIndex.from_tuples(keys[:-1])
|
129 |
+
idx = Index(keys)
|
130 |
+
res, indexer = mi.reindex(idx)
|
131 |
+
|
132 |
+
tm.assert_index_equal(res, idx)
|
133 |
+
expected = np.array([0, 1, 2, -1], dtype=np.intp)
|
134 |
+
tm.assert_numpy_array_equal(indexer, expected)
|
135 |
+
|
136 |
+
|
137 |
+
def test_reindex_limit_arg_with_multiindex():
|
138 |
+
# GH21247
|
139 |
+
|
140 |
+
idx = MultiIndex.from_tuples([(3, "A"), (4, "A"), (4, "B")])
|
141 |
+
|
142 |
+
df = pd.Series([0.02, 0.01, 0.012], index=idx)
|
143 |
+
|
144 |
+
new_idx = MultiIndex.from_tuples(
|
145 |
+
[
|
146 |
+
(3, "A"),
|
147 |
+
(3, "B"),
|
148 |
+
(4, "A"),
|
149 |
+
(4, "B"),
|
150 |
+
(4, "C"),
|
151 |
+
(5, "B"),
|
152 |
+
(5, "C"),
|
153 |
+
(6, "B"),
|
154 |
+
(6, "C"),
|
155 |
+
]
|
156 |
+
)
|
157 |
+
|
158 |
+
with pytest.raises(
|
159 |
+
ValueError,
|
160 |
+
match="limit argument only valid if doing pad, backfill or nearest reindexing",
|
161 |
+
):
|
162 |
+
df.reindex(new_idx, fill_value=0, limit=1)
|
163 |
+
|
164 |
+
|
165 |
+
def test_reindex_with_none_in_nested_multiindex():
|
166 |
+
# GH42883
|
167 |
+
index = MultiIndex.from_tuples([(("a", None), 1), (("b", None), 2)])
|
168 |
+
index2 = MultiIndex.from_tuples([(("b", None), 2), (("a", None), 1)])
|
169 |
+
df1_dtype = pd.DataFrame([1, 2], index=index)
|
170 |
+
df2_dtype = pd.DataFrame([2, 1], index=index2)
|
171 |
+
|
172 |
+
result = df1_dtype.reindex_like(df2_dtype)
|
173 |
+
expected = df2_dtype
|
174 |
+
tm.assert_frame_equal(result, expected)
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/test_setops.py
ADDED
@@ -0,0 +1,772 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
import pandas as pd
|
5 |
+
from pandas import (
|
6 |
+
CategoricalIndex,
|
7 |
+
DataFrame,
|
8 |
+
Index,
|
9 |
+
IntervalIndex,
|
10 |
+
MultiIndex,
|
11 |
+
Series,
|
12 |
+
)
|
13 |
+
import pandas._testing as tm
|
14 |
+
from pandas.api.types import (
|
15 |
+
is_float_dtype,
|
16 |
+
is_unsigned_integer_dtype,
|
17 |
+
)
|
18 |
+
|
19 |
+
|
20 |
+
@pytest.mark.parametrize("case", [0.5, "xxx"])
|
21 |
+
@pytest.mark.parametrize(
|
22 |
+
"method", ["intersection", "union", "difference", "symmetric_difference"]
|
23 |
+
)
|
24 |
+
def test_set_ops_error_cases(idx, case, sort, method):
|
25 |
+
# non-iterable input
|
26 |
+
msg = "Input must be Index or array-like"
|
27 |
+
with pytest.raises(TypeError, match=msg):
|
28 |
+
getattr(idx, method)(case, sort=sort)
|
29 |
+
|
30 |
+
|
31 |
+
@pytest.mark.parametrize("klass", [MultiIndex, np.array, Series, list])
|
32 |
+
def test_intersection_base(idx, sort, klass):
|
33 |
+
first = idx[2::-1] # first 3 elements reversed
|
34 |
+
second = idx[:5]
|
35 |
+
|
36 |
+
if klass is not MultiIndex:
|
37 |
+
second = klass(second.values)
|
38 |
+
|
39 |
+
intersect = first.intersection(second, sort=sort)
|
40 |
+
if sort is None:
|
41 |
+
expected = first.sort_values()
|
42 |
+
else:
|
43 |
+
expected = first
|
44 |
+
tm.assert_index_equal(intersect, expected)
|
45 |
+
|
46 |
+
msg = "other must be a MultiIndex or a list of tuples"
|
47 |
+
with pytest.raises(TypeError, match=msg):
|
48 |
+
first.intersection([1, 2, 3], sort=sort)
|
49 |
+
|
50 |
+
|
51 |
+
@pytest.mark.arm_slow
|
52 |
+
@pytest.mark.parametrize("klass", [MultiIndex, np.array, Series, list])
|
53 |
+
def test_union_base(idx, sort, klass):
|
54 |
+
first = idx[::-1]
|
55 |
+
second = idx[:5]
|
56 |
+
|
57 |
+
if klass is not MultiIndex:
|
58 |
+
second = klass(second.values)
|
59 |
+
|
60 |
+
union = first.union(second, sort=sort)
|
61 |
+
if sort is None:
|
62 |
+
expected = first.sort_values()
|
63 |
+
else:
|
64 |
+
expected = first
|
65 |
+
tm.assert_index_equal(union, expected)
|
66 |
+
|
67 |
+
msg = "other must be a MultiIndex or a list of tuples"
|
68 |
+
with pytest.raises(TypeError, match=msg):
|
69 |
+
first.union([1, 2, 3], sort=sort)
|
70 |
+
|
71 |
+
|
72 |
+
def test_difference_base(idx, sort):
|
73 |
+
second = idx[4:]
|
74 |
+
answer = idx[:4]
|
75 |
+
result = idx.difference(second, sort=sort)
|
76 |
+
|
77 |
+
if sort is None:
|
78 |
+
answer = answer.sort_values()
|
79 |
+
|
80 |
+
assert result.equals(answer)
|
81 |
+
tm.assert_index_equal(result, answer)
|
82 |
+
|
83 |
+
# GH 10149
|
84 |
+
cases = [klass(second.values) for klass in [np.array, Series, list]]
|
85 |
+
for case in cases:
|
86 |
+
result = idx.difference(case, sort=sort)
|
87 |
+
tm.assert_index_equal(result, answer)
|
88 |
+
|
89 |
+
msg = "other must be a MultiIndex or a list of tuples"
|
90 |
+
with pytest.raises(TypeError, match=msg):
|
91 |
+
idx.difference([1, 2, 3], sort=sort)
|
92 |
+
|
93 |
+
|
94 |
+
def test_symmetric_difference(idx, sort):
|
95 |
+
first = idx[1:]
|
96 |
+
second = idx[:-1]
|
97 |
+
answer = idx[[-1, 0]]
|
98 |
+
result = first.symmetric_difference(second, sort=sort)
|
99 |
+
|
100 |
+
if sort is None:
|
101 |
+
answer = answer.sort_values()
|
102 |
+
|
103 |
+
tm.assert_index_equal(result, answer)
|
104 |
+
|
105 |
+
# GH 10149
|
106 |
+
cases = [klass(second.values) for klass in [np.array, Series, list]]
|
107 |
+
for case in cases:
|
108 |
+
result = first.symmetric_difference(case, sort=sort)
|
109 |
+
tm.assert_index_equal(result, answer)
|
110 |
+
|
111 |
+
msg = "other must be a MultiIndex or a list of tuples"
|
112 |
+
with pytest.raises(TypeError, match=msg):
|
113 |
+
first.symmetric_difference([1, 2, 3], sort=sort)
|
114 |
+
|
115 |
+
|
116 |
+
def test_multiindex_symmetric_difference():
|
117 |
+
# GH 13490
|
118 |
+
idx = MultiIndex.from_product([["a", "b"], ["A", "B"]], names=["a", "b"])
|
119 |
+
result = idx.symmetric_difference(idx)
|
120 |
+
assert result.names == idx.names
|
121 |
+
|
122 |
+
idx2 = idx.copy().rename(["A", "B"])
|
123 |
+
result = idx.symmetric_difference(idx2)
|
124 |
+
assert result.names == [None, None]
|
125 |
+
|
126 |
+
|
127 |
+
def test_empty(idx):
|
128 |
+
# GH 15270
|
129 |
+
assert not idx.empty
|
130 |
+
assert idx[:0].empty
|
131 |
+
|
132 |
+
|
133 |
+
def test_difference(idx, sort):
|
134 |
+
first = idx
|
135 |
+
result = first.difference(idx[-3:], sort=sort)
|
136 |
+
vals = idx[:-3].values
|
137 |
+
|
138 |
+
if sort is None:
|
139 |
+
vals = sorted(vals)
|
140 |
+
|
141 |
+
expected = MultiIndex.from_tuples(vals, sortorder=0, names=idx.names)
|
142 |
+
|
143 |
+
assert isinstance(result, MultiIndex)
|
144 |
+
assert result.equals(expected)
|
145 |
+
assert result.names == idx.names
|
146 |
+
tm.assert_index_equal(result, expected)
|
147 |
+
|
148 |
+
# empty difference: reflexive
|
149 |
+
result = idx.difference(idx, sort=sort)
|
150 |
+
expected = idx[:0]
|
151 |
+
assert result.equals(expected)
|
152 |
+
assert result.names == idx.names
|
153 |
+
|
154 |
+
# empty difference: superset
|
155 |
+
result = idx[-3:].difference(idx, sort=sort)
|
156 |
+
expected = idx[:0]
|
157 |
+
assert result.equals(expected)
|
158 |
+
assert result.names == idx.names
|
159 |
+
|
160 |
+
# empty difference: degenerate
|
161 |
+
result = idx[:0].difference(idx, sort=sort)
|
162 |
+
expected = idx[:0]
|
163 |
+
assert result.equals(expected)
|
164 |
+
assert result.names == idx.names
|
165 |
+
|
166 |
+
# names not the same
|
167 |
+
chunklet = idx[-3:]
|
168 |
+
chunklet.names = ["foo", "baz"]
|
169 |
+
result = first.difference(chunklet, sort=sort)
|
170 |
+
assert result.names == (None, None)
|
171 |
+
|
172 |
+
# empty, but non-equal
|
173 |
+
result = idx.difference(idx.sortlevel(1)[0], sort=sort)
|
174 |
+
assert len(result) == 0
|
175 |
+
|
176 |
+
# raise Exception called with non-MultiIndex
|
177 |
+
result = first.difference(first.values, sort=sort)
|
178 |
+
assert result.equals(first[:0])
|
179 |
+
|
180 |
+
# name from empty array
|
181 |
+
result = first.difference([], sort=sort)
|
182 |
+
assert first.equals(result)
|
183 |
+
assert first.names == result.names
|
184 |
+
|
185 |
+
# name from non-empty array
|
186 |
+
result = first.difference([("foo", "one")], sort=sort)
|
187 |
+
expected = MultiIndex.from_tuples(
|
188 |
+
[("bar", "one"), ("baz", "two"), ("foo", "two"), ("qux", "one"), ("qux", "two")]
|
189 |
+
)
|
190 |
+
expected.names = first.names
|
191 |
+
assert first.names == result.names
|
192 |
+
|
193 |
+
msg = "other must be a MultiIndex or a list of tuples"
|
194 |
+
with pytest.raises(TypeError, match=msg):
|
195 |
+
first.difference([1, 2, 3, 4, 5], sort=sort)
|
196 |
+
|
197 |
+
|
198 |
+
def test_difference_sort_special():
|
199 |
+
# GH-24959
|
200 |
+
idx = MultiIndex.from_product([[1, 0], ["a", "b"]])
|
201 |
+
# sort=None, the default
|
202 |
+
result = idx.difference([])
|
203 |
+
tm.assert_index_equal(result, idx)
|
204 |
+
|
205 |
+
|
206 |
+
def test_difference_sort_special_true():
|
207 |
+
idx = MultiIndex.from_product([[1, 0], ["a", "b"]])
|
208 |
+
result = idx.difference([], sort=True)
|
209 |
+
expected = MultiIndex.from_product([[0, 1], ["a", "b"]])
|
210 |
+
tm.assert_index_equal(result, expected)
|
211 |
+
|
212 |
+
|
213 |
+
def test_difference_sort_incomparable():
|
214 |
+
# GH-24959
|
215 |
+
idx = MultiIndex.from_product([[1, pd.Timestamp("2000"), 2], ["a", "b"]])
|
216 |
+
|
217 |
+
other = MultiIndex.from_product([[3, pd.Timestamp("2000"), 4], ["c", "d"]])
|
218 |
+
# sort=None, the default
|
219 |
+
msg = "sort order is undefined for incomparable objects"
|
220 |
+
with tm.assert_produces_warning(RuntimeWarning, match=msg):
|
221 |
+
result = idx.difference(other)
|
222 |
+
tm.assert_index_equal(result, idx)
|
223 |
+
|
224 |
+
# sort=False
|
225 |
+
result = idx.difference(other, sort=False)
|
226 |
+
tm.assert_index_equal(result, idx)
|
227 |
+
|
228 |
+
|
229 |
+
def test_difference_sort_incomparable_true():
|
230 |
+
idx = MultiIndex.from_product([[1, pd.Timestamp("2000"), 2], ["a", "b"]])
|
231 |
+
other = MultiIndex.from_product([[3, pd.Timestamp("2000"), 4], ["c", "d"]])
|
232 |
+
|
233 |
+
# TODO: this is raising in constructing a Categorical when calling
|
234 |
+
# algos.safe_sort. Should we catch and re-raise with a better message?
|
235 |
+
msg = "'values' is not ordered, please explicitly specify the categories order "
|
236 |
+
with pytest.raises(TypeError, match=msg):
|
237 |
+
idx.difference(other, sort=True)
|
238 |
+
|
239 |
+
|
240 |
+
def test_union(idx, sort):
|
241 |
+
piece1 = idx[:5][::-1]
|
242 |
+
piece2 = idx[3:]
|
243 |
+
|
244 |
+
the_union = piece1.union(piece2, sort=sort)
|
245 |
+
|
246 |
+
if sort in (None, False):
|
247 |
+
tm.assert_index_equal(the_union.sort_values(), idx.sort_values())
|
248 |
+
else:
|
249 |
+
tm.assert_index_equal(the_union, idx)
|
250 |
+
|
251 |
+
# corner case, pass self or empty thing:
|
252 |
+
the_union = idx.union(idx, sort=sort)
|
253 |
+
tm.assert_index_equal(the_union, idx)
|
254 |
+
|
255 |
+
the_union = idx.union(idx[:0], sort=sort)
|
256 |
+
tm.assert_index_equal(the_union, idx)
|
257 |
+
|
258 |
+
tuples = idx.values
|
259 |
+
result = idx[:4].union(tuples[4:], sort=sort)
|
260 |
+
if sort is None:
|
261 |
+
tm.assert_index_equal(result.sort_values(), idx.sort_values())
|
262 |
+
else:
|
263 |
+
assert result.equals(idx)
|
264 |
+
|
265 |
+
|
266 |
+
def test_union_with_regular_index(idx, using_infer_string):
|
267 |
+
other = Index(["A", "B", "C"])
|
268 |
+
|
269 |
+
result = other.union(idx)
|
270 |
+
assert ("foo", "one") in result
|
271 |
+
assert "B" in result
|
272 |
+
|
273 |
+
if using_infer_string:
|
274 |
+
with pytest.raises(NotImplementedError, match="Can only union"):
|
275 |
+
idx.union(other)
|
276 |
+
else:
|
277 |
+
msg = "The values in the array are unorderable"
|
278 |
+
with tm.assert_produces_warning(RuntimeWarning, match=msg):
|
279 |
+
result2 = idx.union(other)
|
280 |
+
# This is more consistent now, if sorting fails then we don't sort at all
|
281 |
+
# in the MultiIndex case.
|
282 |
+
assert not result.equals(result2)
|
283 |
+
|
284 |
+
|
285 |
+
def test_intersection(idx, sort):
|
286 |
+
piece1 = idx[:5][::-1]
|
287 |
+
piece2 = idx[3:]
|
288 |
+
|
289 |
+
the_int = piece1.intersection(piece2, sort=sort)
|
290 |
+
|
291 |
+
if sort in (None, True):
|
292 |
+
tm.assert_index_equal(the_int, idx[3:5])
|
293 |
+
else:
|
294 |
+
tm.assert_index_equal(the_int.sort_values(), idx[3:5])
|
295 |
+
|
296 |
+
# corner case, pass self
|
297 |
+
the_int = idx.intersection(idx, sort=sort)
|
298 |
+
tm.assert_index_equal(the_int, idx)
|
299 |
+
|
300 |
+
# empty intersection: disjoint
|
301 |
+
empty = idx[:2].intersection(idx[2:], sort=sort)
|
302 |
+
expected = idx[:0]
|
303 |
+
assert empty.equals(expected)
|
304 |
+
|
305 |
+
tuples = idx.values
|
306 |
+
result = idx.intersection(tuples)
|
307 |
+
assert result.equals(idx)
|
308 |
+
|
309 |
+
|
310 |
+
@pytest.mark.parametrize(
|
311 |
+
"method", ["intersection", "union", "difference", "symmetric_difference"]
|
312 |
+
)
|
313 |
+
def test_setop_with_categorical(idx, sort, method):
|
314 |
+
other = idx.to_flat_index().astype("category")
|
315 |
+
res_names = [None] * idx.nlevels
|
316 |
+
|
317 |
+
result = getattr(idx, method)(other, sort=sort)
|
318 |
+
expected = getattr(idx, method)(idx, sort=sort).rename(res_names)
|
319 |
+
tm.assert_index_equal(result, expected)
|
320 |
+
|
321 |
+
result = getattr(idx, method)(other[:5], sort=sort)
|
322 |
+
expected = getattr(idx, method)(idx[:5], sort=sort).rename(res_names)
|
323 |
+
tm.assert_index_equal(result, expected)
|
324 |
+
|
325 |
+
|
326 |
+
def test_intersection_non_object(idx, sort):
|
327 |
+
other = Index(range(3), name="foo")
|
328 |
+
|
329 |
+
result = idx.intersection(other, sort=sort)
|
330 |
+
expected = MultiIndex(levels=idx.levels, codes=[[]] * idx.nlevels, names=None)
|
331 |
+
tm.assert_index_equal(result, expected, exact=True)
|
332 |
+
|
333 |
+
# if we pass a length-0 ndarray (i.e. no name, we retain our idx.name)
|
334 |
+
result = idx.intersection(np.asarray(other)[:0], sort=sort)
|
335 |
+
expected = MultiIndex(levels=idx.levels, codes=[[]] * idx.nlevels, names=idx.names)
|
336 |
+
tm.assert_index_equal(result, expected, exact=True)
|
337 |
+
|
338 |
+
msg = "other must be a MultiIndex or a list of tuples"
|
339 |
+
with pytest.raises(TypeError, match=msg):
|
340 |
+
# With non-zero length non-index, we try and fail to convert to tuples
|
341 |
+
idx.intersection(np.asarray(other), sort=sort)
|
342 |
+
|
343 |
+
|
344 |
+
def test_intersect_equal_sort():
|
345 |
+
# GH-24959
|
346 |
+
idx = MultiIndex.from_product([[1, 0], ["a", "b"]])
|
347 |
+
tm.assert_index_equal(idx.intersection(idx, sort=False), idx)
|
348 |
+
tm.assert_index_equal(idx.intersection(idx, sort=None), idx)
|
349 |
+
|
350 |
+
|
351 |
+
def test_intersect_equal_sort_true():
|
352 |
+
idx = MultiIndex.from_product([[1, 0], ["a", "b"]])
|
353 |
+
expected = MultiIndex.from_product([[0, 1], ["a", "b"]])
|
354 |
+
result = idx.intersection(idx, sort=True)
|
355 |
+
tm.assert_index_equal(result, expected)
|
356 |
+
|
357 |
+
|
358 |
+
@pytest.mark.parametrize("slice_", [slice(None), slice(0)])
|
359 |
+
def test_union_sort_other_empty(slice_):
|
360 |
+
# https://github.com/pandas-dev/pandas/issues/24959
|
361 |
+
idx = MultiIndex.from_product([[1, 0], ["a", "b"]])
|
362 |
+
|
363 |
+
# default, sort=None
|
364 |
+
other = idx[slice_]
|
365 |
+
tm.assert_index_equal(idx.union(other), idx)
|
366 |
+
tm.assert_index_equal(other.union(idx), idx)
|
367 |
+
|
368 |
+
# sort=False
|
369 |
+
tm.assert_index_equal(idx.union(other, sort=False), idx)
|
370 |
+
|
371 |
+
|
372 |
+
def test_union_sort_other_empty_sort():
|
373 |
+
idx = MultiIndex.from_product([[1, 0], ["a", "b"]])
|
374 |
+
other = idx[:0]
|
375 |
+
result = idx.union(other, sort=True)
|
376 |
+
expected = MultiIndex.from_product([[0, 1], ["a", "b"]])
|
377 |
+
tm.assert_index_equal(result, expected)
|
378 |
+
|
379 |
+
|
380 |
+
def test_union_sort_other_incomparable():
|
381 |
+
# https://github.com/pandas-dev/pandas/issues/24959
|
382 |
+
idx = MultiIndex.from_product([[1, pd.Timestamp("2000")], ["a", "b"]])
|
383 |
+
|
384 |
+
# default, sort=None
|
385 |
+
with tm.assert_produces_warning(RuntimeWarning):
|
386 |
+
result = idx.union(idx[:1])
|
387 |
+
tm.assert_index_equal(result, idx)
|
388 |
+
|
389 |
+
# sort=False
|
390 |
+
result = idx.union(idx[:1], sort=False)
|
391 |
+
tm.assert_index_equal(result, idx)
|
392 |
+
|
393 |
+
|
394 |
+
def test_union_sort_other_incomparable_sort():
|
395 |
+
idx = MultiIndex.from_product([[1, pd.Timestamp("2000")], ["a", "b"]])
|
396 |
+
msg = "'<' not supported between instances of 'Timestamp' and 'int'"
|
397 |
+
with pytest.raises(TypeError, match=msg):
|
398 |
+
idx.union(idx[:1], sort=True)
|
399 |
+
|
400 |
+
|
401 |
+
def test_union_non_object_dtype_raises():
|
402 |
+
# GH#32646 raise NotImplementedError instead of less-informative error
|
403 |
+
mi = MultiIndex.from_product([["a", "b"], [1, 2]])
|
404 |
+
|
405 |
+
idx = mi.levels[1]
|
406 |
+
|
407 |
+
msg = "Can only union MultiIndex with MultiIndex or Index of tuples"
|
408 |
+
with pytest.raises(NotImplementedError, match=msg):
|
409 |
+
mi.union(idx)
|
410 |
+
|
411 |
+
|
412 |
+
def test_union_empty_self_different_names():
|
413 |
+
# GH#38423
|
414 |
+
mi = MultiIndex.from_arrays([[]])
|
415 |
+
mi2 = MultiIndex.from_arrays([[1, 2], [3, 4]], names=["a", "b"])
|
416 |
+
result = mi.union(mi2)
|
417 |
+
expected = MultiIndex.from_arrays([[1, 2], [3, 4]])
|
418 |
+
tm.assert_index_equal(result, expected)
|
419 |
+
|
420 |
+
|
421 |
+
def test_union_multiindex_empty_rangeindex():
|
422 |
+
# GH#41234
|
423 |
+
mi = MultiIndex.from_arrays([[1, 2], [3, 4]], names=["a", "b"])
|
424 |
+
ri = pd.RangeIndex(0)
|
425 |
+
|
426 |
+
result_left = mi.union(ri)
|
427 |
+
tm.assert_index_equal(mi, result_left, check_names=False)
|
428 |
+
|
429 |
+
result_right = ri.union(mi)
|
430 |
+
tm.assert_index_equal(mi, result_right, check_names=False)
|
431 |
+
|
432 |
+
|
433 |
+
@pytest.mark.parametrize(
|
434 |
+
"method", ["union", "intersection", "difference", "symmetric_difference"]
|
435 |
+
)
|
436 |
+
def test_setops_sort_validation(method):
|
437 |
+
idx1 = MultiIndex.from_product([["a", "b"], [1, 2]])
|
438 |
+
idx2 = MultiIndex.from_product([["b", "c"], [1, 2]])
|
439 |
+
|
440 |
+
with pytest.raises(ValueError, match="The 'sort' keyword only takes"):
|
441 |
+
getattr(idx1, method)(idx2, sort=2)
|
442 |
+
|
443 |
+
# sort=True is supported as of GH#?
|
444 |
+
getattr(idx1, method)(idx2, sort=True)
|
445 |
+
|
446 |
+
|
447 |
+
@pytest.mark.parametrize("val", [pd.NA, 100])
|
448 |
+
def test_difference_keep_ea_dtypes(any_numeric_ea_dtype, val):
|
449 |
+
# GH#48606
|
450 |
+
midx = MultiIndex.from_arrays(
|
451 |
+
[Series([1, 2], dtype=any_numeric_ea_dtype), [2, 1]], names=["a", None]
|
452 |
+
)
|
453 |
+
midx2 = MultiIndex.from_arrays(
|
454 |
+
[Series([1, 2, val], dtype=any_numeric_ea_dtype), [1, 1, 3]]
|
455 |
+
)
|
456 |
+
result = midx.difference(midx2)
|
457 |
+
expected = MultiIndex.from_arrays([Series([1], dtype=any_numeric_ea_dtype), [2]])
|
458 |
+
tm.assert_index_equal(result, expected)
|
459 |
+
|
460 |
+
result = midx.difference(midx.sort_values(ascending=False))
|
461 |
+
expected = MultiIndex.from_arrays(
|
462 |
+
[Series([], dtype=any_numeric_ea_dtype), Series([], dtype=np.int64)],
|
463 |
+
names=["a", None],
|
464 |
+
)
|
465 |
+
tm.assert_index_equal(result, expected)
|
466 |
+
|
467 |
+
|
468 |
+
@pytest.mark.parametrize("val", [pd.NA, 5])
|
469 |
+
def test_symmetric_difference_keeping_ea_dtype(any_numeric_ea_dtype, val):
|
470 |
+
# GH#48607
|
471 |
+
midx = MultiIndex.from_arrays(
|
472 |
+
[Series([1, 2], dtype=any_numeric_ea_dtype), [2, 1]], names=["a", None]
|
473 |
+
)
|
474 |
+
midx2 = MultiIndex.from_arrays(
|
475 |
+
[Series([1, 2, val], dtype=any_numeric_ea_dtype), [1, 1, 3]]
|
476 |
+
)
|
477 |
+
result = midx.symmetric_difference(midx2)
|
478 |
+
expected = MultiIndex.from_arrays(
|
479 |
+
[Series([1, 1, val], dtype=any_numeric_ea_dtype), [1, 2, 3]]
|
480 |
+
)
|
481 |
+
tm.assert_index_equal(result, expected)
|
482 |
+
|
483 |
+
|
484 |
+
@pytest.mark.parametrize(
|
485 |
+
("tuples", "exp_tuples"),
|
486 |
+
[
|
487 |
+
([("val1", "test1")], [("val1", "test1")]),
|
488 |
+
([("val1", "test1"), ("val1", "test1")], [("val1", "test1")]),
|
489 |
+
(
|
490 |
+
[("val2", "test2"), ("val1", "test1")],
|
491 |
+
[("val2", "test2"), ("val1", "test1")],
|
492 |
+
),
|
493 |
+
],
|
494 |
+
)
|
495 |
+
def test_intersect_with_duplicates(tuples, exp_tuples):
|
496 |
+
# GH#36915
|
497 |
+
left = MultiIndex.from_tuples(tuples, names=["first", "second"])
|
498 |
+
right = MultiIndex.from_tuples(
|
499 |
+
[("val1", "test1"), ("val1", "test1"), ("val2", "test2")],
|
500 |
+
names=["first", "second"],
|
501 |
+
)
|
502 |
+
result = left.intersection(right)
|
503 |
+
expected = MultiIndex.from_tuples(exp_tuples, names=["first", "second"])
|
504 |
+
tm.assert_index_equal(result, expected)
|
505 |
+
|
506 |
+
|
507 |
+
@pytest.mark.parametrize(
|
508 |
+
"data, names, expected",
|
509 |
+
[
|
510 |
+
((1,), None, [None, None]),
|
511 |
+
((1,), ["a"], [None, None]),
|
512 |
+
((1,), ["b"], [None, None]),
|
513 |
+
((1, 2), ["c", "d"], [None, None]),
|
514 |
+
((1, 2), ["b", "a"], [None, None]),
|
515 |
+
((1, 2, 3), ["a", "b", "c"], [None, None]),
|
516 |
+
((1, 2), ["a", "c"], ["a", None]),
|
517 |
+
((1, 2), ["c", "b"], [None, "b"]),
|
518 |
+
((1, 2), ["a", "b"], ["a", "b"]),
|
519 |
+
((1, 2), [None, "b"], [None, "b"]),
|
520 |
+
],
|
521 |
+
)
|
522 |
+
def test_maybe_match_names(data, names, expected):
|
523 |
+
# GH#38323
|
524 |
+
mi = MultiIndex.from_tuples([], names=["a", "b"])
|
525 |
+
mi2 = MultiIndex.from_tuples([data], names=names)
|
526 |
+
result = mi._maybe_match_names(mi2)
|
527 |
+
assert result == expected
|
528 |
+
|
529 |
+
|
530 |
+
def test_intersection_equal_different_names():
|
531 |
+
# GH#30302
|
532 |
+
mi1 = MultiIndex.from_arrays([[1, 2], [3, 4]], names=["c", "b"])
|
533 |
+
mi2 = MultiIndex.from_arrays([[1, 2], [3, 4]], names=["a", "b"])
|
534 |
+
|
535 |
+
result = mi1.intersection(mi2)
|
536 |
+
expected = MultiIndex.from_arrays([[1, 2], [3, 4]], names=[None, "b"])
|
537 |
+
tm.assert_index_equal(result, expected)
|
538 |
+
|
539 |
+
|
540 |
+
def test_intersection_different_names():
|
541 |
+
# GH#38323
|
542 |
+
mi = MultiIndex.from_arrays([[1], [3]], names=["c", "b"])
|
543 |
+
mi2 = MultiIndex.from_arrays([[1], [3]])
|
544 |
+
result = mi.intersection(mi2)
|
545 |
+
tm.assert_index_equal(result, mi2)
|
546 |
+
|
547 |
+
|
548 |
+
def test_intersection_with_missing_values_on_both_sides(nulls_fixture):
|
549 |
+
# GH#38623
|
550 |
+
mi1 = MultiIndex.from_arrays([[3, nulls_fixture, 4, nulls_fixture], [1, 2, 4, 2]])
|
551 |
+
mi2 = MultiIndex.from_arrays([[3, nulls_fixture, 3], [1, 2, 4]])
|
552 |
+
result = mi1.intersection(mi2)
|
553 |
+
expected = MultiIndex.from_arrays([[3, nulls_fixture], [1, 2]])
|
554 |
+
tm.assert_index_equal(result, expected)
|
555 |
+
|
556 |
+
|
557 |
+
def test_union_with_missing_values_on_both_sides(nulls_fixture):
|
558 |
+
# GH#38623
|
559 |
+
mi1 = MultiIndex.from_arrays([[1, nulls_fixture]])
|
560 |
+
mi2 = MultiIndex.from_arrays([[1, nulls_fixture, 3]])
|
561 |
+
result = mi1.union(mi2)
|
562 |
+
expected = MultiIndex.from_arrays([[1, 3, nulls_fixture]])
|
563 |
+
tm.assert_index_equal(result, expected)
|
564 |
+
|
565 |
+
|
566 |
+
@pytest.mark.parametrize("dtype", ["float64", "Float64"])
|
567 |
+
@pytest.mark.parametrize("sort", [None, False])
|
568 |
+
def test_union_nan_got_duplicated(dtype, sort):
|
569 |
+
# GH#38977, GH#49010
|
570 |
+
mi1 = MultiIndex.from_arrays([pd.array([1.0, np.nan], dtype=dtype), [2, 3]])
|
571 |
+
mi2 = MultiIndex.from_arrays([pd.array([1.0, np.nan, 3.0], dtype=dtype), [2, 3, 4]])
|
572 |
+
result = mi1.union(mi2, sort=sort)
|
573 |
+
if sort is None:
|
574 |
+
expected = MultiIndex.from_arrays(
|
575 |
+
[pd.array([1.0, 3.0, np.nan], dtype=dtype), [2, 4, 3]]
|
576 |
+
)
|
577 |
+
else:
|
578 |
+
expected = mi2
|
579 |
+
tm.assert_index_equal(result, expected)
|
580 |
+
|
581 |
+
|
582 |
+
@pytest.mark.parametrize("val", [4, 1])
|
583 |
+
def test_union_keep_ea_dtype(any_numeric_ea_dtype, val):
|
584 |
+
# GH#48505
|
585 |
+
|
586 |
+
arr1 = Series([val, 2], dtype=any_numeric_ea_dtype)
|
587 |
+
arr2 = Series([2, 1], dtype=any_numeric_ea_dtype)
|
588 |
+
midx = MultiIndex.from_arrays([arr1, [1, 2]], names=["a", None])
|
589 |
+
midx2 = MultiIndex.from_arrays([arr2, [2, 1]])
|
590 |
+
result = midx.union(midx2)
|
591 |
+
if val == 4:
|
592 |
+
expected = MultiIndex.from_arrays(
|
593 |
+
[Series([1, 2, 4], dtype=any_numeric_ea_dtype), [1, 2, 1]]
|
594 |
+
)
|
595 |
+
else:
|
596 |
+
expected = MultiIndex.from_arrays(
|
597 |
+
[Series([1, 2], dtype=any_numeric_ea_dtype), [1, 2]]
|
598 |
+
)
|
599 |
+
tm.assert_index_equal(result, expected)
|
600 |
+
|
601 |
+
|
602 |
+
@pytest.mark.parametrize("dupe_val", [3, pd.NA])
|
603 |
+
def test_union_with_duplicates_keep_ea_dtype(dupe_val, any_numeric_ea_dtype):
|
604 |
+
# GH48900
|
605 |
+
mi1 = MultiIndex.from_arrays(
|
606 |
+
[
|
607 |
+
Series([1, dupe_val, 2], dtype=any_numeric_ea_dtype),
|
608 |
+
Series([1, dupe_val, 2], dtype=any_numeric_ea_dtype),
|
609 |
+
]
|
610 |
+
)
|
611 |
+
mi2 = MultiIndex.from_arrays(
|
612 |
+
[
|
613 |
+
Series([2, dupe_val, dupe_val], dtype=any_numeric_ea_dtype),
|
614 |
+
Series([2, dupe_val, dupe_val], dtype=any_numeric_ea_dtype),
|
615 |
+
]
|
616 |
+
)
|
617 |
+
result = mi1.union(mi2)
|
618 |
+
expected = MultiIndex.from_arrays(
|
619 |
+
[
|
620 |
+
Series([1, 2, dupe_val, dupe_val], dtype=any_numeric_ea_dtype),
|
621 |
+
Series([1, 2, dupe_val, dupe_val], dtype=any_numeric_ea_dtype),
|
622 |
+
]
|
623 |
+
)
|
624 |
+
tm.assert_index_equal(result, expected)
|
625 |
+
|
626 |
+
|
627 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
628 |
+
def test_union_duplicates(index, request):
|
629 |
+
# GH#38977
|
630 |
+
if index.empty or isinstance(index, (IntervalIndex, CategoricalIndex)):
|
631 |
+
pytest.skip(f"No duplicates in an empty {type(index).__name__}")
|
632 |
+
|
633 |
+
values = index.unique().values.tolist()
|
634 |
+
mi1 = MultiIndex.from_arrays([values, [1] * len(values)])
|
635 |
+
mi2 = MultiIndex.from_arrays([[values[0]] + values, [1] * (len(values) + 1)])
|
636 |
+
result = mi2.union(mi1)
|
637 |
+
expected = mi2.sort_values()
|
638 |
+
tm.assert_index_equal(result, expected)
|
639 |
+
|
640 |
+
if (
|
641 |
+
is_unsigned_integer_dtype(mi2.levels[0])
|
642 |
+
and (mi2.get_level_values(0) < 2**63).all()
|
643 |
+
):
|
644 |
+
# GH#47294 - union uses lib.fast_zip, converting data to Python integers
|
645 |
+
# and loses type information. Result is then unsigned only when values are
|
646 |
+
# sufficiently large to require unsigned dtype. This happens only if other
|
647 |
+
# has dups or one of both have missing values
|
648 |
+
expected = expected.set_levels(
|
649 |
+
[expected.levels[0].astype(np.int64), expected.levels[1]]
|
650 |
+
)
|
651 |
+
elif is_float_dtype(mi2.levels[0]):
|
652 |
+
# mi2 has duplicates witch is a different path than above, Fix that path
|
653 |
+
# to use correct float dtype?
|
654 |
+
expected = expected.set_levels(
|
655 |
+
[expected.levels[0].astype(float), expected.levels[1]]
|
656 |
+
)
|
657 |
+
|
658 |
+
result = mi1.union(mi2)
|
659 |
+
tm.assert_index_equal(result, expected)
|
660 |
+
|
661 |
+
|
662 |
+
def test_union_keep_dtype_precision(any_real_numeric_dtype):
|
663 |
+
# GH#48498
|
664 |
+
arr1 = Series([4, 1, 1], dtype=any_real_numeric_dtype)
|
665 |
+
arr2 = Series([1, 4], dtype=any_real_numeric_dtype)
|
666 |
+
midx = MultiIndex.from_arrays([arr1, [2, 1, 1]], names=["a", None])
|
667 |
+
midx2 = MultiIndex.from_arrays([arr2, [1, 2]], names=["a", None])
|
668 |
+
|
669 |
+
result = midx.union(midx2)
|
670 |
+
expected = MultiIndex.from_arrays(
|
671 |
+
([Series([1, 1, 4], dtype=any_real_numeric_dtype), [1, 1, 2]]),
|
672 |
+
names=["a", None],
|
673 |
+
)
|
674 |
+
tm.assert_index_equal(result, expected)
|
675 |
+
|
676 |
+
|
677 |
+
def test_union_keep_ea_dtype_with_na(any_numeric_ea_dtype):
|
678 |
+
# GH#48498
|
679 |
+
arr1 = Series([4, pd.NA], dtype=any_numeric_ea_dtype)
|
680 |
+
arr2 = Series([1, pd.NA], dtype=any_numeric_ea_dtype)
|
681 |
+
midx = MultiIndex.from_arrays([arr1, [2, 1]], names=["a", None])
|
682 |
+
midx2 = MultiIndex.from_arrays([arr2, [1, 2]])
|
683 |
+
result = midx.union(midx2)
|
684 |
+
expected = MultiIndex.from_arrays(
|
685 |
+
[Series([1, 4, pd.NA, pd.NA], dtype=any_numeric_ea_dtype), [1, 2, 1, 2]]
|
686 |
+
)
|
687 |
+
tm.assert_index_equal(result, expected)
|
688 |
+
|
689 |
+
|
690 |
+
@pytest.mark.parametrize(
|
691 |
+
"levels1, levels2, codes1, codes2, names",
|
692 |
+
[
|
693 |
+
(
|
694 |
+
[["a", "b", "c"], [0, ""]],
|
695 |
+
[["c", "d", "b"], [""]],
|
696 |
+
[[0, 1, 2], [1, 1, 1]],
|
697 |
+
[[0, 1, 2], [0, 0, 0]],
|
698 |
+
["name1", "name2"],
|
699 |
+
),
|
700 |
+
],
|
701 |
+
)
|
702 |
+
def test_intersection_lexsort_depth(levels1, levels2, codes1, codes2, names):
|
703 |
+
# GH#25169
|
704 |
+
mi1 = MultiIndex(levels=levels1, codes=codes1, names=names)
|
705 |
+
mi2 = MultiIndex(levels=levels2, codes=codes2, names=names)
|
706 |
+
mi_int = mi1.intersection(mi2)
|
707 |
+
assert mi_int._lexsort_depth == 2
|
708 |
+
|
709 |
+
|
710 |
+
@pytest.mark.parametrize(
|
711 |
+
"a",
|
712 |
+
[pd.Categorical(["a", "b"], categories=["a", "b"]), ["a", "b"]],
|
713 |
+
)
|
714 |
+
@pytest.mark.parametrize(
|
715 |
+
"b",
|
716 |
+
[
|
717 |
+
pd.Categorical(["a", "b"], categories=["b", "a"], ordered=True),
|
718 |
+
pd.Categorical(["a", "b"], categories=["b", "a"]),
|
719 |
+
],
|
720 |
+
)
|
721 |
+
def test_intersection_with_non_lex_sorted_categories(a, b):
|
722 |
+
# GH#49974
|
723 |
+
other = ["1", "2"]
|
724 |
+
|
725 |
+
df1 = DataFrame({"x": a, "y": other})
|
726 |
+
df2 = DataFrame({"x": b, "y": other})
|
727 |
+
|
728 |
+
expected = MultiIndex.from_arrays([a, other], names=["x", "y"])
|
729 |
+
|
730 |
+
res1 = MultiIndex.from_frame(df1).intersection(
|
731 |
+
MultiIndex.from_frame(df2.sort_values(["x", "y"]))
|
732 |
+
)
|
733 |
+
res2 = MultiIndex.from_frame(df1).intersection(MultiIndex.from_frame(df2))
|
734 |
+
res3 = MultiIndex.from_frame(df1.sort_values(["x", "y"])).intersection(
|
735 |
+
MultiIndex.from_frame(df2)
|
736 |
+
)
|
737 |
+
res4 = MultiIndex.from_frame(df1.sort_values(["x", "y"])).intersection(
|
738 |
+
MultiIndex.from_frame(df2.sort_values(["x", "y"]))
|
739 |
+
)
|
740 |
+
|
741 |
+
tm.assert_index_equal(res1, expected)
|
742 |
+
tm.assert_index_equal(res2, expected)
|
743 |
+
tm.assert_index_equal(res3, expected)
|
744 |
+
tm.assert_index_equal(res4, expected)
|
745 |
+
|
746 |
+
|
747 |
+
@pytest.mark.parametrize("val", [pd.NA, 100])
|
748 |
+
def test_intersection_keep_ea_dtypes(val, any_numeric_ea_dtype):
|
749 |
+
# GH#48604
|
750 |
+
midx = MultiIndex.from_arrays(
|
751 |
+
[Series([1, 2], dtype=any_numeric_ea_dtype), [2, 1]], names=["a", None]
|
752 |
+
)
|
753 |
+
midx2 = MultiIndex.from_arrays(
|
754 |
+
[Series([1, 2, val], dtype=any_numeric_ea_dtype), [1, 1, 3]]
|
755 |
+
)
|
756 |
+
result = midx.intersection(midx2)
|
757 |
+
expected = MultiIndex.from_arrays([Series([2], dtype=any_numeric_ea_dtype), [1]])
|
758 |
+
tm.assert_index_equal(result, expected)
|
759 |
+
|
760 |
+
|
761 |
+
def test_union_with_na_when_constructing_dataframe():
|
762 |
+
# GH43222
|
763 |
+
series1 = Series(
|
764 |
+
(1,),
|
765 |
+
index=MultiIndex.from_arrays(
|
766 |
+
[Series([None], dtype="string"), Series([None], dtype="string")]
|
767 |
+
),
|
768 |
+
)
|
769 |
+
series2 = Series((10, 20), index=MultiIndex.from_tuples(((None, None), ("a", "b"))))
|
770 |
+
result = DataFrame([series1, series2])
|
771 |
+
expected = DataFrame({(np.nan, np.nan): [1.0, 10.0], ("a", "b"): [np.nan, 20.0]})
|
772 |
+
tm.assert_frame_equal(result, expected)
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/test_sorting.py
ADDED
@@ -0,0 +1,349 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas.errors import (
|
5 |
+
PerformanceWarning,
|
6 |
+
UnsortedIndexError,
|
7 |
+
)
|
8 |
+
|
9 |
+
from pandas import (
|
10 |
+
CategoricalIndex,
|
11 |
+
DataFrame,
|
12 |
+
Index,
|
13 |
+
MultiIndex,
|
14 |
+
RangeIndex,
|
15 |
+
Series,
|
16 |
+
Timestamp,
|
17 |
+
)
|
18 |
+
import pandas._testing as tm
|
19 |
+
from pandas.core.indexes.frozen import FrozenList
|
20 |
+
|
21 |
+
|
22 |
+
def test_sortlevel(idx):
|
23 |
+
tuples = list(idx)
|
24 |
+
np.random.default_rng(2).shuffle(tuples)
|
25 |
+
|
26 |
+
index = MultiIndex.from_tuples(tuples)
|
27 |
+
|
28 |
+
sorted_idx, _ = index.sortlevel(0)
|
29 |
+
expected = MultiIndex.from_tuples(sorted(tuples))
|
30 |
+
assert sorted_idx.equals(expected)
|
31 |
+
|
32 |
+
sorted_idx, _ = index.sortlevel(0, ascending=False)
|
33 |
+
assert sorted_idx.equals(expected[::-1])
|
34 |
+
|
35 |
+
sorted_idx, _ = index.sortlevel(1)
|
36 |
+
by1 = sorted(tuples, key=lambda x: (x[1], x[0]))
|
37 |
+
expected = MultiIndex.from_tuples(by1)
|
38 |
+
assert sorted_idx.equals(expected)
|
39 |
+
|
40 |
+
sorted_idx, _ = index.sortlevel(1, ascending=False)
|
41 |
+
assert sorted_idx.equals(expected[::-1])
|
42 |
+
|
43 |
+
|
44 |
+
def test_sortlevel_not_sort_remaining():
|
45 |
+
mi = MultiIndex.from_tuples([[1, 1, 3], [1, 1, 1]], names=list("ABC"))
|
46 |
+
sorted_idx, _ = mi.sortlevel("A", sort_remaining=False)
|
47 |
+
assert sorted_idx.equals(mi)
|
48 |
+
|
49 |
+
|
50 |
+
def test_sortlevel_deterministic():
|
51 |
+
tuples = [
|
52 |
+
("bar", "one"),
|
53 |
+
("foo", "two"),
|
54 |
+
("qux", "two"),
|
55 |
+
("foo", "one"),
|
56 |
+
("baz", "two"),
|
57 |
+
("qux", "one"),
|
58 |
+
]
|
59 |
+
|
60 |
+
index = MultiIndex.from_tuples(tuples)
|
61 |
+
|
62 |
+
sorted_idx, _ = index.sortlevel(0)
|
63 |
+
expected = MultiIndex.from_tuples(sorted(tuples))
|
64 |
+
assert sorted_idx.equals(expected)
|
65 |
+
|
66 |
+
sorted_idx, _ = index.sortlevel(0, ascending=False)
|
67 |
+
assert sorted_idx.equals(expected[::-1])
|
68 |
+
|
69 |
+
sorted_idx, _ = index.sortlevel(1)
|
70 |
+
by1 = sorted(tuples, key=lambda x: (x[1], x[0]))
|
71 |
+
expected = MultiIndex.from_tuples(by1)
|
72 |
+
assert sorted_idx.equals(expected)
|
73 |
+
|
74 |
+
sorted_idx, _ = index.sortlevel(1, ascending=False)
|
75 |
+
assert sorted_idx.equals(expected[::-1])
|
76 |
+
|
77 |
+
|
78 |
+
def test_sortlevel_na_position():
|
79 |
+
# GH#51612
|
80 |
+
midx = MultiIndex.from_tuples([(1, np.nan), (1, 1)])
|
81 |
+
result = midx.sortlevel(level=[0, 1], na_position="last")[0]
|
82 |
+
expected = MultiIndex.from_tuples([(1, 1), (1, np.nan)])
|
83 |
+
tm.assert_index_equal(result, expected)
|
84 |
+
|
85 |
+
|
86 |
+
def test_numpy_argsort(idx):
|
87 |
+
result = np.argsort(idx)
|
88 |
+
expected = idx.argsort()
|
89 |
+
tm.assert_numpy_array_equal(result, expected)
|
90 |
+
|
91 |
+
# these are the only two types that perform
|
92 |
+
# pandas compatibility input validation - the
|
93 |
+
# rest already perform separate (or no) such
|
94 |
+
# validation via their 'values' attribute as
|
95 |
+
# defined in pandas.core.indexes/base.py - they
|
96 |
+
# cannot be changed at the moment due to
|
97 |
+
# backwards compatibility concerns
|
98 |
+
if isinstance(type(idx), (CategoricalIndex, RangeIndex)):
|
99 |
+
msg = "the 'axis' parameter is not supported"
|
100 |
+
with pytest.raises(ValueError, match=msg):
|
101 |
+
np.argsort(idx, axis=1)
|
102 |
+
|
103 |
+
msg = "the 'kind' parameter is not supported"
|
104 |
+
with pytest.raises(ValueError, match=msg):
|
105 |
+
np.argsort(idx, kind="mergesort")
|
106 |
+
|
107 |
+
msg = "the 'order' parameter is not supported"
|
108 |
+
with pytest.raises(ValueError, match=msg):
|
109 |
+
np.argsort(idx, order=("a", "b"))
|
110 |
+
|
111 |
+
|
112 |
+
def test_unsortedindex():
|
113 |
+
# GH 11897
|
114 |
+
mi = MultiIndex.from_tuples(
|
115 |
+
[("z", "a"), ("x", "a"), ("y", "b"), ("x", "b"), ("y", "a"), ("z", "b")],
|
116 |
+
names=["one", "two"],
|
117 |
+
)
|
118 |
+
df = DataFrame([[i, 10 * i] for i in range(6)], index=mi, columns=["one", "two"])
|
119 |
+
|
120 |
+
# GH 16734: not sorted, but no real slicing
|
121 |
+
result = df.loc(axis=0)["z", "a"]
|
122 |
+
expected = df.iloc[0]
|
123 |
+
tm.assert_series_equal(result, expected)
|
124 |
+
|
125 |
+
msg = (
|
126 |
+
"MultiIndex slicing requires the index to be lexsorted: "
|
127 |
+
r"slicing on levels \[1\], lexsort depth 0"
|
128 |
+
)
|
129 |
+
with pytest.raises(UnsortedIndexError, match=msg):
|
130 |
+
df.loc(axis=0)["z", slice("a")]
|
131 |
+
df.sort_index(inplace=True)
|
132 |
+
assert len(df.loc(axis=0)["z", :]) == 2
|
133 |
+
|
134 |
+
with pytest.raises(KeyError, match="'q'"):
|
135 |
+
df.loc(axis=0)["q", :]
|
136 |
+
|
137 |
+
|
138 |
+
def test_unsortedindex_doc_examples():
|
139 |
+
# https://pandas.pydata.org/pandas-docs/stable/advanced.html#sorting-a-multiindex
|
140 |
+
dfm = DataFrame(
|
141 |
+
{
|
142 |
+
"jim": [0, 0, 1, 1],
|
143 |
+
"joe": ["x", "x", "z", "y"],
|
144 |
+
"jolie": np.random.default_rng(2).random(4),
|
145 |
+
}
|
146 |
+
)
|
147 |
+
|
148 |
+
dfm = dfm.set_index(["jim", "joe"])
|
149 |
+
with tm.assert_produces_warning(PerformanceWarning):
|
150 |
+
dfm.loc[(1, "z")]
|
151 |
+
|
152 |
+
msg = r"Key length \(2\) was greater than MultiIndex lexsort depth \(1\)"
|
153 |
+
with pytest.raises(UnsortedIndexError, match=msg):
|
154 |
+
dfm.loc[(0, "y"):(1, "z")]
|
155 |
+
|
156 |
+
assert not dfm.index._is_lexsorted()
|
157 |
+
assert dfm.index._lexsort_depth == 1
|
158 |
+
|
159 |
+
# sort it
|
160 |
+
dfm = dfm.sort_index()
|
161 |
+
dfm.loc[(1, "z")]
|
162 |
+
dfm.loc[(0, "y"):(1, "z")]
|
163 |
+
|
164 |
+
assert dfm.index._is_lexsorted()
|
165 |
+
assert dfm.index._lexsort_depth == 2
|
166 |
+
|
167 |
+
|
168 |
+
def test_reconstruct_sort():
|
169 |
+
# starts off lexsorted & monotonic
|
170 |
+
mi = MultiIndex.from_arrays([["A", "A", "B", "B", "B"], [1, 2, 1, 2, 3]])
|
171 |
+
assert mi.is_monotonic_increasing
|
172 |
+
recons = mi._sort_levels_monotonic()
|
173 |
+
assert recons.is_monotonic_increasing
|
174 |
+
assert mi is recons
|
175 |
+
|
176 |
+
assert mi.equals(recons)
|
177 |
+
assert Index(mi.values).equals(Index(recons.values))
|
178 |
+
|
179 |
+
# cannot convert to lexsorted
|
180 |
+
mi = MultiIndex.from_tuples(
|
181 |
+
[("z", "a"), ("x", "a"), ("y", "b"), ("x", "b"), ("y", "a"), ("z", "b")],
|
182 |
+
names=["one", "two"],
|
183 |
+
)
|
184 |
+
assert not mi.is_monotonic_increasing
|
185 |
+
recons = mi._sort_levels_monotonic()
|
186 |
+
assert not recons.is_monotonic_increasing
|
187 |
+
assert mi.equals(recons)
|
188 |
+
assert Index(mi.values).equals(Index(recons.values))
|
189 |
+
|
190 |
+
# cannot convert to lexsorted
|
191 |
+
mi = MultiIndex(
|
192 |
+
levels=[["b", "d", "a"], [1, 2, 3]],
|
193 |
+
codes=[[0, 1, 0, 2], [2, 0, 0, 1]],
|
194 |
+
names=["col1", "col2"],
|
195 |
+
)
|
196 |
+
assert not mi.is_monotonic_increasing
|
197 |
+
recons = mi._sort_levels_monotonic()
|
198 |
+
assert not recons.is_monotonic_increasing
|
199 |
+
assert mi.equals(recons)
|
200 |
+
assert Index(mi.values).equals(Index(recons.values))
|
201 |
+
|
202 |
+
|
203 |
+
def test_reconstruct_remove_unused():
|
204 |
+
# xref to GH 2770
|
205 |
+
df = DataFrame(
|
206 |
+
[["deleteMe", 1, 9], ["keepMe", 2, 9], ["keepMeToo", 3, 9]],
|
207 |
+
columns=["first", "second", "third"],
|
208 |
+
)
|
209 |
+
df2 = df.set_index(["first", "second"], drop=False)
|
210 |
+
df2 = df2[df2["first"] != "deleteMe"]
|
211 |
+
|
212 |
+
# removed levels are there
|
213 |
+
expected = MultiIndex(
|
214 |
+
levels=[["deleteMe", "keepMe", "keepMeToo"], [1, 2, 3]],
|
215 |
+
codes=[[1, 2], [1, 2]],
|
216 |
+
names=["first", "second"],
|
217 |
+
)
|
218 |
+
result = df2.index
|
219 |
+
tm.assert_index_equal(result, expected)
|
220 |
+
|
221 |
+
expected = MultiIndex(
|
222 |
+
levels=[["keepMe", "keepMeToo"], [2, 3]],
|
223 |
+
codes=[[0, 1], [0, 1]],
|
224 |
+
names=["first", "second"],
|
225 |
+
)
|
226 |
+
result = df2.index.remove_unused_levels()
|
227 |
+
tm.assert_index_equal(result, expected)
|
228 |
+
|
229 |
+
# idempotent
|
230 |
+
result2 = result.remove_unused_levels()
|
231 |
+
tm.assert_index_equal(result2, expected)
|
232 |
+
assert result2.is_(result)
|
233 |
+
|
234 |
+
|
235 |
+
@pytest.mark.parametrize(
|
236 |
+
"first_type,second_type", [("int64", "int64"), ("datetime64[D]", "str")]
|
237 |
+
)
|
238 |
+
def test_remove_unused_levels_large(first_type, second_type):
|
239 |
+
# GH16556
|
240 |
+
|
241 |
+
# because tests should be deterministic (and this test in particular
|
242 |
+
# checks that levels are removed, which is not the case for every
|
243 |
+
# random input):
|
244 |
+
rng = np.random.default_rng(10) # seed is arbitrary value that works
|
245 |
+
|
246 |
+
size = 1 << 16
|
247 |
+
df = DataFrame(
|
248 |
+
{
|
249 |
+
"first": rng.integers(0, 1 << 13, size).astype(first_type),
|
250 |
+
"second": rng.integers(0, 1 << 10, size).astype(second_type),
|
251 |
+
"third": rng.random(size),
|
252 |
+
}
|
253 |
+
)
|
254 |
+
df = df.groupby(["first", "second"]).sum()
|
255 |
+
df = df[df.third < 0.1]
|
256 |
+
|
257 |
+
result = df.index.remove_unused_levels()
|
258 |
+
assert len(result.levels[0]) < len(df.index.levels[0])
|
259 |
+
assert len(result.levels[1]) < len(df.index.levels[1])
|
260 |
+
assert result.equals(df.index)
|
261 |
+
|
262 |
+
expected = df.reset_index().set_index(["first", "second"]).index
|
263 |
+
tm.assert_index_equal(result, expected)
|
264 |
+
|
265 |
+
|
266 |
+
@pytest.mark.parametrize("level0", [["a", "d", "b"], ["a", "d", "b", "unused"]])
|
267 |
+
@pytest.mark.parametrize(
|
268 |
+
"level1", [["w", "x", "y", "z"], ["w", "x", "y", "z", "unused"]]
|
269 |
+
)
|
270 |
+
def test_remove_unused_nan(level0, level1):
|
271 |
+
# GH 18417
|
272 |
+
mi = MultiIndex(levels=[level0, level1], codes=[[0, 2, -1, 1, -1], [0, 1, 2, 3, 2]])
|
273 |
+
|
274 |
+
result = mi.remove_unused_levels()
|
275 |
+
tm.assert_index_equal(result, mi)
|
276 |
+
for level in 0, 1:
|
277 |
+
assert "unused" not in result.levels[level]
|
278 |
+
|
279 |
+
|
280 |
+
def test_argsort(idx):
|
281 |
+
result = idx.argsort()
|
282 |
+
expected = idx.values.argsort()
|
283 |
+
tm.assert_numpy_array_equal(result, expected)
|
284 |
+
|
285 |
+
|
286 |
+
def test_remove_unused_levels_with_nan():
|
287 |
+
# GH 37510
|
288 |
+
idx = Index([(1, np.nan), (3, 4)]).rename(["id1", "id2"])
|
289 |
+
idx = idx.set_levels(["a", np.nan], level="id1")
|
290 |
+
idx = idx.remove_unused_levels()
|
291 |
+
result = idx.levels
|
292 |
+
expected = FrozenList([["a", np.nan], [4]])
|
293 |
+
assert str(result) == str(expected)
|
294 |
+
|
295 |
+
|
296 |
+
def test_sort_values_nan():
|
297 |
+
# GH48495, GH48626
|
298 |
+
midx = MultiIndex(levels=[["A", "B", "C"], ["D"]], codes=[[1, 0, 2], [-1, -1, 0]])
|
299 |
+
result = midx.sort_values()
|
300 |
+
expected = MultiIndex(
|
301 |
+
levels=[["A", "B", "C"], ["D"]], codes=[[0, 1, 2], [-1, -1, 0]]
|
302 |
+
)
|
303 |
+
tm.assert_index_equal(result, expected)
|
304 |
+
|
305 |
+
|
306 |
+
def test_sort_values_incomparable():
|
307 |
+
# GH48495
|
308 |
+
mi = MultiIndex.from_arrays(
|
309 |
+
[
|
310 |
+
[1, Timestamp("2000-01-01")],
|
311 |
+
[3, 4],
|
312 |
+
]
|
313 |
+
)
|
314 |
+
match = "'<' not supported between instances of 'Timestamp' and 'int'"
|
315 |
+
with pytest.raises(TypeError, match=match):
|
316 |
+
mi.sort_values()
|
317 |
+
|
318 |
+
|
319 |
+
@pytest.mark.parametrize("na_position", ["first", "last"])
|
320 |
+
@pytest.mark.parametrize("dtype", ["float64", "Int64", "Float64"])
|
321 |
+
def test_sort_values_with_na_na_position(dtype, na_position):
|
322 |
+
# 51612
|
323 |
+
arrays = [
|
324 |
+
Series([1, 1, 2], dtype=dtype),
|
325 |
+
Series([1, None, 3], dtype=dtype),
|
326 |
+
]
|
327 |
+
index = MultiIndex.from_arrays(arrays)
|
328 |
+
result = index.sort_values(na_position=na_position)
|
329 |
+
if na_position == "first":
|
330 |
+
arrays = [
|
331 |
+
Series([1, 1, 2], dtype=dtype),
|
332 |
+
Series([None, 1, 3], dtype=dtype),
|
333 |
+
]
|
334 |
+
else:
|
335 |
+
arrays = [
|
336 |
+
Series([1, 1, 2], dtype=dtype),
|
337 |
+
Series([1, None, 3], dtype=dtype),
|
338 |
+
]
|
339 |
+
expected = MultiIndex.from_arrays(arrays)
|
340 |
+
tm.assert_index_equal(result, expected)
|
341 |
+
|
342 |
+
|
343 |
+
def test_sort_unnecessary_warning():
|
344 |
+
# GH#55386
|
345 |
+
midx = MultiIndex.from_tuples([(1.5, 2), (3.5, 3), (0, 1)])
|
346 |
+
midx = midx.set_levels([2.5, np.nan, 1], level=0)
|
347 |
+
result = midx.sort_values()
|
348 |
+
expected = MultiIndex.from_tuples([(1, 3), (2.5, 1), (np.nan, 2)])
|
349 |
+
tm.assert_index_equal(result, expected)
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/multi/test_take.py
ADDED
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
import pandas as pd
|
5 |
+
import pandas._testing as tm
|
6 |
+
|
7 |
+
|
8 |
+
def test_take(idx):
|
9 |
+
indexer = [4, 3, 0, 2]
|
10 |
+
result = idx.take(indexer)
|
11 |
+
expected = idx[indexer]
|
12 |
+
assert result.equals(expected)
|
13 |
+
|
14 |
+
# GH 10791
|
15 |
+
msg = "'MultiIndex' object has no attribute 'freq'"
|
16 |
+
with pytest.raises(AttributeError, match=msg):
|
17 |
+
idx.freq
|
18 |
+
|
19 |
+
|
20 |
+
def test_take_invalid_kwargs(idx):
|
21 |
+
indices = [1, 2]
|
22 |
+
|
23 |
+
msg = r"take\(\) got an unexpected keyword argument 'foo'"
|
24 |
+
with pytest.raises(TypeError, match=msg):
|
25 |
+
idx.take(indices, foo=2)
|
26 |
+
|
27 |
+
msg = "the 'out' parameter is not supported"
|
28 |
+
with pytest.raises(ValueError, match=msg):
|
29 |
+
idx.take(indices, out=indices)
|
30 |
+
|
31 |
+
msg = "the 'mode' parameter is not supported"
|
32 |
+
with pytest.raises(ValueError, match=msg):
|
33 |
+
idx.take(indices, mode="clip")
|
34 |
+
|
35 |
+
|
36 |
+
def test_take_fill_value():
|
37 |
+
# GH 12631
|
38 |
+
vals = [["A", "B"], [pd.Timestamp("2011-01-01"), pd.Timestamp("2011-01-02")]]
|
39 |
+
idx = pd.MultiIndex.from_product(vals, names=["str", "dt"])
|
40 |
+
|
41 |
+
result = idx.take(np.array([1, 0, -1]))
|
42 |
+
exp_vals = [
|
43 |
+
("A", pd.Timestamp("2011-01-02")),
|
44 |
+
("A", pd.Timestamp("2011-01-01")),
|
45 |
+
("B", pd.Timestamp("2011-01-02")),
|
46 |
+
]
|
47 |
+
expected = pd.MultiIndex.from_tuples(exp_vals, names=["str", "dt"])
|
48 |
+
tm.assert_index_equal(result, expected)
|
49 |
+
|
50 |
+
# fill_value
|
51 |
+
result = idx.take(np.array([1, 0, -1]), fill_value=True)
|
52 |
+
exp_vals = [
|
53 |
+
("A", pd.Timestamp("2011-01-02")),
|
54 |
+
("A", pd.Timestamp("2011-01-01")),
|
55 |
+
(np.nan, pd.NaT),
|
56 |
+
]
|
57 |
+
expected = pd.MultiIndex.from_tuples(exp_vals, names=["str", "dt"])
|
58 |
+
tm.assert_index_equal(result, expected)
|
59 |
+
|
60 |
+
# allow_fill=False
|
61 |
+
result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True)
|
62 |
+
exp_vals = [
|
63 |
+
("A", pd.Timestamp("2011-01-02")),
|
64 |
+
("A", pd.Timestamp("2011-01-01")),
|
65 |
+
("B", pd.Timestamp("2011-01-02")),
|
66 |
+
]
|
67 |
+
expected = pd.MultiIndex.from_tuples(exp_vals, names=["str", "dt"])
|
68 |
+
tm.assert_index_equal(result, expected)
|
69 |
+
|
70 |
+
msg = "When allow_fill=True and fill_value is not None, all indices must be >= -1"
|
71 |
+
with pytest.raises(ValueError, match=msg):
|
72 |
+
idx.take(np.array([1, 0, -2]), fill_value=True)
|
73 |
+
with pytest.raises(ValueError, match=msg):
|
74 |
+
idx.take(np.array([1, 0, -5]), fill_value=True)
|
75 |
+
|
76 |
+
msg = "index -5 is out of bounds for( axis 0 with)? size 4"
|
77 |
+
with pytest.raises(IndexError, match=msg):
|
78 |
+
idx.take(np.array([1, -5]))
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/object/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/object/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (200 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/object/__pycache__/test_astype.cpython-310.pyc
ADDED
Binary file (1.05 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/object/__pycache__/test_indexing.cpython-310.pyc
ADDED
Binary file (6.52 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/object/test_astype.py
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
from pandas import (
|
4 |
+
Index,
|
5 |
+
NaT,
|
6 |
+
Series,
|
7 |
+
)
|
8 |
+
import pandas._testing as tm
|
9 |
+
|
10 |
+
|
11 |
+
def test_astype_str_from_bytes():
|
12 |
+
# https://github.com/pandas-dev/pandas/issues/38607
|
13 |
+
# GH#49658 pre-2.0 Index called .values.astype(str) here, which effectively
|
14 |
+
# did a .decode() on the bytes object. In 2.0 we go through
|
15 |
+
# ensure_string_array which does f"{val}"
|
16 |
+
idx = Index(["あ", b"a"], dtype="object")
|
17 |
+
result = idx.astype(str)
|
18 |
+
expected = Index(["あ", "a"], dtype="object")
|
19 |
+
tm.assert_index_equal(result, expected)
|
20 |
+
|
21 |
+
# while we're here, check that Series.astype behaves the same
|
22 |
+
result = Series(idx).astype(str)
|
23 |
+
expected = Series(expected, dtype=object)
|
24 |
+
tm.assert_series_equal(result, expected)
|
25 |
+
|
26 |
+
|
27 |
+
def test_astype_invalid_nas_to_tdt64_raises():
|
28 |
+
# GH#45722 don't cast np.datetime64 NaTs to timedelta64 NaT
|
29 |
+
idx = Index([NaT.asm8] * 2, dtype=object)
|
30 |
+
|
31 |
+
msg = r"Invalid type for timedelta scalar: <class 'numpy.datetime64'>"
|
32 |
+
with pytest.raises(TypeError, match=msg):
|
33 |
+
idx.astype("m8[ns]")
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/object/test_indexing.py
ADDED
@@ -0,0 +1,243 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from decimal import Decimal
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
import pytest
|
5 |
+
|
6 |
+
from pandas._libs.missing import (
|
7 |
+
NA,
|
8 |
+
is_matching_na,
|
9 |
+
)
|
10 |
+
from pandas.compat import pa_version_under16p0
|
11 |
+
import pandas.util._test_decorators as td
|
12 |
+
|
13 |
+
import pandas as pd
|
14 |
+
from pandas import Index
|
15 |
+
import pandas._testing as tm
|
16 |
+
|
17 |
+
|
18 |
+
class TestGetIndexer:
|
19 |
+
@pytest.mark.parametrize(
|
20 |
+
"method,expected",
|
21 |
+
[
|
22 |
+
("pad", np.array([-1, 0, 1, 1], dtype=np.intp)),
|
23 |
+
("backfill", np.array([0, 0, 1, -1], dtype=np.intp)),
|
24 |
+
],
|
25 |
+
)
|
26 |
+
def test_get_indexer_strings(self, method, expected):
|
27 |
+
index = Index(["b", "c"])
|
28 |
+
actual = index.get_indexer(["a", "b", "c", "d"], method=method)
|
29 |
+
|
30 |
+
tm.assert_numpy_array_equal(actual, expected)
|
31 |
+
|
32 |
+
def test_get_indexer_strings_raises(self, using_infer_string):
|
33 |
+
index = Index(["b", "c"])
|
34 |
+
|
35 |
+
if using_infer_string:
|
36 |
+
import pyarrow as pa
|
37 |
+
|
38 |
+
msg = "has no kernel"
|
39 |
+
with pytest.raises(pa.lib.ArrowNotImplementedError, match=msg):
|
40 |
+
index.get_indexer(["a", "b", "c", "d"], method="nearest")
|
41 |
+
|
42 |
+
with pytest.raises(pa.lib.ArrowNotImplementedError, match=msg):
|
43 |
+
index.get_indexer(["a", "b", "c", "d"], method="pad", tolerance=2)
|
44 |
+
|
45 |
+
with pytest.raises(pa.lib.ArrowNotImplementedError, match=msg):
|
46 |
+
index.get_indexer(
|
47 |
+
["a", "b", "c", "d"], method="pad", tolerance=[2, 2, 2, 2]
|
48 |
+
)
|
49 |
+
|
50 |
+
else:
|
51 |
+
msg = r"unsupported operand type\(s\) for -: 'str' and 'str'"
|
52 |
+
with pytest.raises(TypeError, match=msg):
|
53 |
+
index.get_indexer(["a", "b", "c", "d"], method="nearest")
|
54 |
+
|
55 |
+
with pytest.raises(TypeError, match=msg):
|
56 |
+
index.get_indexer(["a", "b", "c", "d"], method="pad", tolerance=2)
|
57 |
+
|
58 |
+
with pytest.raises(TypeError, match=msg):
|
59 |
+
index.get_indexer(
|
60 |
+
["a", "b", "c", "d"], method="pad", tolerance=[2, 2, 2, 2]
|
61 |
+
)
|
62 |
+
|
63 |
+
def test_get_indexer_with_NA_values(
|
64 |
+
self, unique_nulls_fixture, unique_nulls_fixture2
|
65 |
+
):
|
66 |
+
# GH#22332
|
67 |
+
# check pairwise, that no pair of na values
|
68 |
+
# is mangled
|
69 |
+
if unique_nulls_fixture is unique_nulls_fixture2:
|
70 |
+
return # skip it, values are not unique
|
71 |
+
arr = np.array([unique_nulls_fixture, unique_nulls_fixture2], dtype=object)
|
72 |
+
index = Index(arr, dtype=object)
|
73 |
+
result = index.get_indexer(
|
74 |
+
Index(
|
75 |
+
[unique_nulls_fixture, unique_nulls_fixture2, "Unknown"], dtype=object
|
76 |
+
)
|
77 |
+
)
|
78 |
+
expected = np.array([0, 1, -1], dtype=np.intp)
|
79 |
+
tm.assert_numpy_array_equal(result, expected)
|
80 |
+
|
81 |
+
|
82 |
+
class TestGetIndexerNonUnique:
|
83 |
+
def test_get_indexer_non_unique_nas(
|
84 |
+
self, nulls_fixture, request, using_infer_string
|
85 |
+
):
|
86 |
+
# even though this isn't non-unique, this should still work
|
87 |
+
if using_infer_string and (nulls_fixture is None or nulls_fixture is NA):
|
88 |
+
request.applymarker(pytest.mark.xfail(reason="NAs are cast to NaN"))
|
89 |
+
index = Index(["a", "b", nulls_fixture])
|
90 |
+
indexer, missing = index.get_indexer_non_unique([nulls_fixture])
|
91 |
+
|
92 |
+
expected_indexer = np.array([2], dtype=np.intp)
|
93 |
+
expected_missing = np.array([], dtype=np.intp)
|
94 |
+
tm.assert_numpy_array_equal(indexer, expected_indexer)
|
95 |
+
tm.assert_numpy_array_equal(missing, expected_missing)
|
96 |
+
|
97 |
+
# actually non-unique
|
98 |
+
index = Index(["a", nulls_fixture, "b", nulls_fixture])
|
99 |
+
indexer, missing = index.get_indexer_non_unique([nulls_fixture])
|
100 |
+
|
101 |
+
expected_indexer = np.array([1, 3], dtype=np.intp)
|
102 |
+
tm.assert_numpy_array_equal(indexer, expected_indexer)
|
103 |
+
tm.assert_numpy_array_equal(missing, expected_missing)
|
104 |
+
|
105 |
+
# matching-but-not-identical nans
|
106 |
+
if is_matching_na(nulls_fixture, float("NaN")):
|
107 |
+
index = Index(["a", float("NaN"), "b", float("NaN")])
|
108 |
+
match_but_not_identical = True
|
109 |
+
elif is_matching_na(nulls_fixture, Decimal("NaN")):
|
110 |
+
index = Index(["a", Decimal("NaN"), "b", Decimal("NaN")])
|
111 |
+
match_but_not_identical = True
|
112 |
+
else:
|
113 |
+
match_but_not_identical = False
|
114 |
+
|
115 |
+
if match_but_not_identical:
|
116 |
+
indexer, missing = index.get_indexer_non_unique([nulls_fixture])
|
117 |
+
|
118 |
+
expected_indexer = np.array([1, 3], dtype=np.intp)
|
119 |
+
tm.assert_numpy_array_equal(indexer, expected_indexer)
|
120 |
+
tm.assert_numpy_array_equal(missing, expected_missing)
|
121 |
+
|
122 |
+
@pytest.mark.filterwarnings("ignore:elementwise comp:DeprecationWarning")
|
123 |
+
def test_get_indexer_non_unique_np_nats(self, np_nat_fixture, np_nat_fixture2):
|
124 |
+
expected_missing = np.array([], dtype=np.intp)
|
125 |
+
# matching-but-not-identical nats
|
126 |
+
if is_matching_na(np_nat_fixture, np_nat_fixture2):
|
127 |
+
# ensure nats are different objects
|
128 |
+
index = Index(
|
129 |
+
np.array(
|
130 |
+
["2021-10-02", np_nat_fixture.copy(), np_nat_fixture2.copy()],
|
131 |
+
dtype=object,
|
132 |
+
),
|
133 |
+
dtype=object,
|
134 |
+
)
|
135 |
+
# pass as index to prevent target from being casted to DatetimeIndex
|
136 |
+
indexer, missing = index.get_indexer_non_unique(
|
137 |
+
Index([np_nat_fixture], dtype=object)
|
138 |
+
)
|
139 |
+
expected_indexer = np.array([1, 2], dtype=np.intp)
|
140 |
+
tm.assert_numpy_array_equal(indexer, expected_indexer)
|
141 |
+
tm.assert_numpy_array_equal(missing, expected_missing)
|
142 |
+
# dt64nat vs td64nat
|
143 |
+
else:
|
144 |
+
try:
|
145 |
+
np_nat_fixture == np_nat_fixture2
|
146 |
+
except (TypeError, OverflowError):
|
147 |
+
# Numpy will raise on uncomparable types, like
|
148 |
+
# np.datetime64('NaT', 'Y') and np.datetime64('NaT', 'ps')
|
149 |
+
# https://github.com/numpy/numpy/issues/22762
|
150 |
+
return
|
151 |
+
index = Index(
|
152 |
+
np.array(
|
153 |
+
[
|
154 |
+
"2021-10-02",
|
155 |
+
np_nat_fixture,
|
156 |
+
np_nat_fixture2,
|
157 |
+
np_nat_fixture,
|
158 |
+
np_nat_fixture2,
|
159 |
+
],
|
160 |
+
dtype=object,
|
161 |
+
),
|
162 |
+
dtype=object,
|
163 |
+
)
|
164 |
+
# pass as index to prevent target from being casted to DatetimeIndex
|
165 |
+
indexer, missing = index.get_indexer_non_unique(
|
166 |
+
Index([np_nat_fixture], dtype=object)
|
167 |
+
)
|
168 |
+
expected_indexer = np.array([1, 3], dtype=np.intp)
|
169 |
+
tm.assert_numpy_array_equal(indexer, expected_indexer)
|
170 |
+
tm.assert_numpy_array_equal(missing, expected_missing)
|
171 |
+
|
172 |
+
|
173 |
+
class TestSliceLocs:
|
174 |
+
@pytest.mark.parametrize(
|
175 |
+
"dtype",
|
176 |
+
[
|
177 |
+
"object",
|
178 |
+
pytest.param("string[pyarrow_numpy]", marks=td.skip_if_no("pyarrow")),
|
179 |
+
],
|
180 |
+
)
|
181 |
+
@pytest.mark.parametrize(
|
182 |
+
"in_slice,expected",
|
183 |
+
[
|
184 |
+
# error: Slice index must be an integer or None
|
185 |
+
(pd.IndexSlice[::-1], "yxdcb"),
|
186 |
+
(pd.IndexSlice["b":"y":-1], ""), # type: ignore[misc]
|
187 |
+
(pd.IndexSlice["b"::-1], "b"), # type: ignore[misc]
|
188 |
+
(pd.IndexSlice[:"b":-1], "yxdcb"), # type: ignore[misc]
|
189 |
+
(pd.IndexSlice[:"y":-1], "y"), # type: ignore[misc]
|
190 |
+
(pd.IndexSlice["y"::-1], "yxdcb"), # type: ignore[misc]
|
191 |
+
(pd.IndexSlice["y"::-4], "yb"), # type: ignore[misc]
|
192 |
+
# absent labels
|
193 |
+
(pd.IndexSlice[:"a":-1], "yxdcb"), # type: ignore[misc]
|
194 |
+
(pd.IndexSlice[:"a":-2], "ydb"), # type: ignore[misc]
|
195 |
+
(pd.IndexSlice["z"::-1], "yxdcb"), # type: ignore[misc]
|
196 |
+
(pd.IndexSlice["z"::-3], "yc"), # type: ignore[misc]
|
197 |
+
(pd.IndexSlice["m"::-1], "dcb"), # type: ignore[misc]
|
198 |
+
(pd.IndexSlice[:"m":-1], "yx"), # type: ignore[misc]
|
199 |
+
(pd.IndexSlice["a":"a":-1], ""), # type: ignore[misc]
|
200 |
+
(pd.IndexSlice["z":"z":-1], ""), # type: ignore[misc]
|
201 |
+
(pd.IndexSlice["m":"m":-1], ""), # type: ignore[misc]
|
202 |
+
],
|
203 |
+
)
|
204 |
+
def test_slice_locs_negative_step(self, in_slice, expected, dtype, request):
|
205 |
+
if (
|
206 |
+
not pa_version_under16p0
|
207 |
+
and dtype == "string[pyarrow_numpy]"
|
208 |
+
and in_slice == slice("a", "a", -1)
|
209 |
+
):
|
210 |
+
request.applymarker(
|
211 |
+
pytest.mark.xfail(reason="https://github.com/apache/arrow/issues/40642")
|
212 |
+
)
|
213 |
+
|
214 |
+
index = Index(list("bcdxy"), dtype=dtype)
|
215 |
+
|
216 |
+
s_start, s_stop = index.slice_locs(in_slice.start, in_slice.stop, in_slice.step)
|
217 |
+
result = index[s_start : s_stop : in_slice.step]
|
218 |
+
expected = Index(list(expected), dtype=dtype)
|
219 |
+
tm.assert_index_equal(result, expected)
|
220 |
+
|
221 |
+
@td.skip_if_no("pyarrow")
|
222 |
+
def test_slice_locs_negative_step_oob(self):
|
223 |
+
index = Index(list("bcdxy"), dtype="string[pyarrow_numpy]")
|
224 |
+
|
225 |
+
result = index[-10:5:1]
|
226 |
+
tm.assert_index_equal(result, index)
|
227 |
+
|
228 |
+
result = index[4:-10:-1]
|
229 |
+
expected = Index(list("yxdcb"), dtype="string[pyarrow_numpy]")
|
230 |
+
tm.assert_index_equal(result, expected)
|
231 |
+
|
232 |
+
def test_slice_locs_dup(self):
|
233 |
+
index = Index(["a", "a", "b", "c", "d", "d"])
|
234 |
+
assert index.slice_locs("a", "d") == (0, 6)
|
235 |
+
assert index.slice_locs(end="d") == (0, 6)
|
236 |
+
assert index.slice_locs("a", "c") == (0, 4)
|
237 |
+
assert index.slice_locs("b", "d") == (2, 6)
|
238 |
+
|
239 |
+
index2 = index[::-1]
|
240 |
+
assert index2.slice_locs("d", "a") == (0, 6)
|
241 |
+
assert index2.slice_locs(end="a") == (0, 6)
|
242 |
+
assert index2.slice_locs("d", "b") == (0, 4)
|
243 |
+
assert index2.slice_locs("c", "a") == (2, 6)
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/ranges/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/ranges/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (200 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/ranges/__pycache__/test_constructors.cpython-310.pyc
ADDED
Binary file (5.31 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/ranges/__pycache__/test_indexing.cpython-310.pyc
ADDED
Binary file (5.86 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/ranges/__pycache__/test_join.cpython-310.pyc
ADDED
Binary file (5.04 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/ranges/__pycache__/test_range.cpython-310.pyc
ADDED
Binary file (17.7 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/ranges/__pycache__/test_setops.cpython-310.pyc
ADDED
Binary file (11.2 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/ranges/test_constructors.py
ADDED
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from datetime import datetime
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
import pytest
|
5 |
+
|
6 |
+
from pandas import (
|
7 |
+
Index,
|
8 |
+
RangeIndex,
|
9 |
+
Series,
|
10 |
+
)
|
11 |
+
import pandas._testing as tm
|
12 |
+
|
13 |
+
|
14 |
+
class TestRangeIndexConstructors:
|
15 |
+
@pytest.mark.parametrize("name", [None, "foo"])
|
16 |
+
@pytest.mark.parametrize(
|
17 |
+
"args, kwargs, start, stop, step",
|
18 |
+
[
|
19 |
+
((5,), {}, 0, 5, 1),
|
20 |
+
((1, 5), {}, 1, 5, 1),
|
21 |
+
((1, 5, 2), {}, 1, 5, 2),
|
22 |
+
((0,), {}, 0, 0, 1),
|
23 |
+
((0, 0), {}, 0, 0, 1),
|
24 |
+
((), {"start": 0}, 0, 0, 1),
|
25 |
+
((), {"stop": 0}, 0, 0, 1),
|
26 |
+
],
|
27 |
+
)
|
28 |
+
def test_constructor(self, args, kwargs, start, stop, step, name):
|
29 |
+
result = RangeIndex(*args, name=name, **kwargs)
|
30 |
+
expected = Index(np.arange(start, stop, step, dtype=np.int64), name=name)
|
31 |
+
assert isinstance(result, RangeIndex)
|
32 |
+
assert result.name is name
|
33 |
+
assert result._range == range(start, stop, step)
|
34 |
+
tm.assert_index_equal(result, expected, exact="equiv")
|
35 |
+
|
36 |
+
def test_constructor_invalid_args(self):
|
37 |
+
msg = "RangeIndex\\(\\.\\.\\.\\) must be called with integers"
|
38 |
+
with pytest.raises(TypeError, match=msg):
|
39 |
+
RangeIndex()
|
40 |
+
|
41 |
+
with pytest.raises(TypeError, match=msg):
|
42 |
+
RangeIndex(name="Foo")
|
43 |
+
|
44 |
+
# we don't allow on a bare Index
|
45 |
+
msg = (
|
46 |
+
r"Index\(\.\.\.\) must be called with a collection of some "
|
47 |
+
r"kind, 0 was passed"
|
48 |
+
)
|
49 |
+
with pytest.raises(TypeError, match=msg):
|
50 |
+
Index(0)
|
51 |
+
|
52 |
+
@pytest.mark.parametrize(
|
53 |
+
"args",
|
54 |
+
[
|
55 |
+
Index(["a", "b"]),
|
56 |
+
Series(["a", "b"]),
|
57 |
+
np.array(["a", "b"]),
|
58 |
+
[],
|
59 |
+
np.arange(0, 10),
|
60 |
+
np.array([1]),
|
61 |
+
[1],
|
62 |
+
],
|
63 |
+
)
|
64 |
+
def test_constructor_additional_invalid_args(self, args):
|
65 |
+
msg = f"Value needs to be a scalar value, was type {type(args).__name__}"
|
66 |
+
with pytest.raises(TypeError, match=msg):
|
67 |
+
RangeIndex(args)
|
68 |
+
|
69 |
+
@pytest.mark.parametrize("args", ["foo", datetime(2000, 1, 1, 0, 0)])
|
70 |
+
def test_constructor_invalid_args_wrong_type(self, args):
|
71 |
+
msg = f"Wrong type {type(args)} for value {args}"
|
72 |
+
with pytest.raises(TypeError, match=msg):
|
73 |
+
RangeIndex(args)
|
74 |
+
|
75 |
+
def test_constructor_same(self):
|
76 |
+
# pass thru w and w/o copy
|
77 |
+
index = RangeIndex(1, 5, 2)
|
78 |
+
result = RangeIndex(index, copy=False)
|
79 |
+
assert result.identical(index)
|
80 |
+
|
81 |
+
result = RangeIndex(index, copy=True)
|
82 |
+
tm.assert_index_equal(result, index, exact=True)
|
83 |
+
|
84 |
+
result = RangeIndex(index)
|
85 |
+
tm.assert_index_equal(result, index, exact=True)
|
86 |
+
|
87 |
+
with pytest.raises(
|
88 |
+
ValueError,
|
89 |
+
match="Incorrect `dtype` passed: expected signed integer, received float64",
|
90 |
+
):
|
91 |
+
RangeIndex(index, dtype="float64")
|
92 |
+
|
93 |
+
def test_constructor_range_object(self):
|
94 |
+
result = RangeIndex(range(1, 5, 2))
|
95 |
+
expected = RangeIndex(1, 5, 2)
|
96 |
+
tm.assert_index_equal(result, expected, exact=True)
|
97 |
+
|
98 |
+
def test_constructor_range(self):
|
99 |
+
result = RangeIndex.from_range(range(1, 5, 2))
|
100 |
+
expected = RangeIndex(1, 5, 2)
|
101 |
+
tm.assert_index_equal(result, expected, exact=True)
|
102 |
+
|
103 |
+
result = RangeIndex.from_range(range(5, 6))
|
104 |
+
expected = RangeIndex(5, 6, 1)
|
105 |
+
tm.assert_index_equal(result, expected, exact=True)
|
106 |
+
|
107 |
+
# an invalid range
|
108 |
+
result = RangeIndex.from_range(range(5, 1))
|
109 |
+
expected = RangeIndex(0, 0, 1)
|
110 |
+
tm.assert_index_equal(result, expected, exact=True)
|
111 |
+
|
112 |
+
result = RangeIndex.from_range(range(5))
|
113 |
+
expected = RangeIndex(0, 5, 1)
|
114 |
+
tm.assert_index_equal(result, expected, exact=True)
|
115 |
+
|
116 |
+
result = Index(range(1, 5, 2))
|
117 |
+
expected = RangeIndex(1, 5, 2)
|
118 |
+
tm.assert_index_equal(result, expected, exact=True)
|
119 |
+
|
120 |
+
msg = (
|
121 |
+
r"(RangeIndex.)?from_range\(\) got an unexpected keyword argument( 'copy')?"
|
122 |
+
)
|
123 |
+
with pytest.raises(TypeError, match=msg):
|
124 |
+
RangeIndex.from_range(range(10), copy=True)
|
125 |
+
|
126 |
+
def test_constructor_name(self):
|
127 |
+
# GH#12288
|
128 |
+
orig = RangeIndex(10)
|
129 |
+
orig.name = "original"
|
130 |
+
|
131 |
+
copy = RangeIndex(orig)
|
132 |
+
copy.name = "copy"
|
133 |
+
|
134 |
+
assert orig.name == "original"
|
135 |
+
assert copy.name == "copy"
|
136 |
+
|
137 |
+
new = Index(copy)
|
138 |
+
assert new.name == "copy"
|
139 |
+
|
140 |
+
new.name = "new"
|
141 |
+
assert orig.name == "original"
|
142 |
+
assert copy.name == "copy"
|
143 |
+
assert new.name == "new"
|
144 |
+
|
145 |
+
def test_constructor_corner(self):
|
146 |
+
arr = np.array([1, 2, 3, 4], dtype=object)
|
147 |
+
index = RangeIndex(1, 5)
|
148 |
+
assert index.values.dtype == np.int64
|
149 |
+
expected = Index(arr).astype("int64")
|
150 |
+
|
151 |
+
tm.assert_index_equal(index, expected, exact="equiv")
|
152 |
+
|
153 |
+
# non-int raise Exception
|
154 |
+
with pytest.raises(TypeError, match=r"Wrong type \<class 'str'\>"):
|
155 |
+
RangeIndex("1", "10", "1")
|
156 |
+
with pytest.raises(TypeError, match=r"Wrong type \<class 'float'\>"):
|
157 |
+
RangeIndex(1.1, 10.2, 1.3)
|
158 |
+
|
159 |
+
# invalid passed type
|
160 |
+
with pytest.raises(
|
161 |
+
ValueError,
|
162 |
+
match="Incorrect `dtype` passed: expected signed integer, received float64",
|
163 |
+
):
|
164 |
+
RangeIndex(1, 5, dtype="float64")
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/ranges/test_indexing.py
ADDED
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas import (
|
5 |
+
Index,
|
6 |
+
RangeIndex,
|
7 |
+
)
|
8 |
+
import pandas._testing as tm
|
9 |
+
|
10 |
+
|
11 |
+
class TestGetIndexer:
|
12 |
+
def test_get_indexer(self):
|
13 |
+
index = RangeIndex(start=0, stop=20, step=2)
|
14 |
+
target = RangeIndex(10)
|
15 |
+
indexer = index.get_indexer(target)
|
16 |
+
expected = np.array([0, -1, 1, -1, 2, -1, 3, -1, 4, -1], dtype=np.intp)
|
17 |
+
tm.assert_numpy_array_equal(indexer, expected)
|
18 |
+
|
19 |
+
def test_get_indexer_pad(self):
|
20 |
+
index = RangeIndex(start=0, stop=20, step=2)
|
21 |
+
target = RangeIndex(10)
|
22 |
+
indexer = index.get_indexer(target, method="pad")
|
23 |
+
expected = np.array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4], dtype=np.intp)
|
24 |
+
tm.assert_numpy_array_equal(indexer, expected)
|
25 |
+
|
26 |
+
def test_get_indexer_backfill(self):
|
27 |
+
index = RangeIndex(start=0, stop=20, step=2)
|
28 |
+
target = RangeIndex(10)
|
29 |
+
indexer = index.get_indexer(target, method="backfill")
|
30 |
+
expected = np.array([0, 1, 1, 2, 2, 3, 3, 4, 4, 5], dtype=np.intp)
|
31 |
+
tm.assert_numpy_array_equal(indexer, expected)
|
32 |
+
|
33 |
+
def test_get_indexer_limit(self):
|
34 |
+
# GH#28631
|
35 |
+
idx = RangeIndex(4)
|
36 |
+
target = RangeIndex(6)
|
37 |
+
result = idx.get_indexer(target, method="pad", limit=1)
|
38 |
+
expected = np.array([0, 1, 2, 3, 3, -1], dtype=np.intp)
|
39 |
+
tm.assert_numpy_array_equal(result, expected)
|
40 |
+
|
41 |
+
@pytest.mark.parametrize("stop", [0, -1, -2])
|
42 |
+
def test_get_indexer_decreasing(self, stop):
|
43 |
+
# GH#28678
|
44 |
+
index = RangeIndex(7, stop, -3)
|
45 |
+
result = index.get_indexer(range(9))
|
46 |
+
expected = np.array([-1, 2, -1, -1, 1, -1, -1, 0, -1], dtype=np.intp)
|
47 |
+
tm.assert_numpy_array_equal(result, expected)
|
48 |
+
|
49 |
+
|
50 |
+
class TestTake:
|
51 |
+
def test_take_preserve_name(self):
|
52 |
+
index = RangeIndex(1, 5, name="foo")
|
53 |
+
taken = index.take([3, 0, 1])
|
54 |
+
assert index.name == taken.name
|
55 |
+
|
56 |
+
def test_take_fill_value(self):
|
57 |
+
# GH#12631
|
58 |
+
idx = RangeIndex(1, 4, name="xxx")
|
59 |
+
result = idx.take(np.array([1, 0, -1]))
|
60 |
+
expected = Index([2, 1, 3], dtype=np.int64, name="xxx")
|
61 |
+
tm.assert_index_equal(result, expected)
|
62 |
+
|
63 |
+
# fill_value
|
64 |
+
msg = "Unable to fill values because RangeIndex cannot contain NA"
|
65 |
+
with pytest.raises(ValueError, match=msg):
|
66 |
+
idx.take(np.array([1, 0, -1]), fill_value=True)
|
67 |
+
|
68 |
+
# allow_fill=False
|
69 |
+
result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True)
|
70 |
+
expected = Index([2, 1, 3], dtype=np.int64, name="xxx")
|
71 |
+
tm.assert_index_equal(result, expected)
|
72 |
+
|
73 |
+
msg = "Unable to fill values because RangeIndex cannot contain NA"
|
74 |
+
with pytest.raises(ValueError, match=msg):
|
75 |
+
idx.take(np.array([1, 0, -2]), fill_value=True)
|
76 |
+
with pytest.raises(ValueError, match=msg):
|
77 |
+
idx.take(np.array([1, 0, -5]), fill_value=True)
|
78 |
+
|
79 |
+
def test_take_raises_index_error(self):
|
80 |
+
idx = RangeIndex(1, 4, name="xxx")
|
81 |
+
|
82 |
+
msg = "index -5 is out of bounds for (axis 0 with )?size 3"
|
83 |
+
with pytest.raises(IndexError, match=msg):
|
84 |
+
idx.take(np.array([1, -5]))
|
85 |
+
|
86 |
+
msg = "index -4 is out of bounds for (axis 0 with )?size 3"
|
87 |
+
with pytest.raises(IndexError, match=msg):
|
88 |
+
idx.take(np.array([1, -4]))
|
89 |
+
|
90 |
+
# no errors
|
91 |
+
result = idx.take(np.array([1, -3]))
|
92 |
+
expected = Index([2, 1], dtype=np.int64, name="xxx")
|
93 |
+
tm.assert_index_equal(result, expected)
|
94 |
+
|
95 |
+
def test_take_accepts_empty_array(self):
|
96 |
+
idx = RangeIndex(1, 4, name="foo")
|
97 |
+
result = idx.take(np.array([]))
|
98 |
+
expected = Index([], dtype=np.int64, name="foo")
|
99 |
+
tm.assert_index_equal(result, expected)
|
100 |
+
|
101 |
+
# empty index
|
102 |
+
idx = RangeIndex(0, name="foo")
|
103 |
+
result = idx.take(np.array([]))
|
104 |
+
expected = Index([], dtype=np.int64, name="foo")
|
105 |
+
tm.assert_index_equal(result, expected)
|
106 |
+
|
107 |
+
def test_take_accepts_non_int64_array(self):
|
108 |
+
idx = RangeIndex(1, 4, name="foo")
|
109 |
+
result = idx.take(np.array([2, 1], dtype=np.uint32))
|
110 |
+
expected = Index([3, 2], dtype=np.int64, name="foo")
|
111 |
+
tm.assert_index_equal(result, expected)
|
112 |
+
|
113 |
+
def test_take_when_index_has_step(self):
|
114 |
+
idx = RangeIndex(1, 11, 3, name="foo") # [1, 4, 7, 10]
|
115 |
+
result = idx.take(np.array([1, 0, -1, -4]))
|
116 |
+
expected = Index([4, 1, 10, 1], dtype=np.int64, name="foo")
|
117 |
+
tm.assert_index_equal(result, expected)
|
118 |
+
|
119 |
+
def test_take_when_index_has_negative_step(self):
|
120 |
+
idx = RangeIndex(11, -4, -2, name="foo") # [11, 9, 7, 5, 3, 1, -1, -3]
|
121 |
+
result = idx.take(np.array([1, 0, -1, -8]))
|
122 |
+
expected = Index([9, 11, -3, 11], dtype=np.int64, name="foo")
|
123 |
+
tm.assert_index_equal(result, expected)
|
124 |
+
|
125 |
+
|
126 |
+
class TestWhere:
|
127 |
+
def test_where_putmask_range_cast(self):
|
128 |
+
# GH#43240
|
129 |
+
idx = RangeIndex(0, 5, name="test")
|
130 |
+
|
131 |
+
mask = np.array([True, True, False, False, False])
|
132 |
+
result = idx.putmask(mask, 10)
|
133 |
+
expected = Index([10, 10, 2, 3, 4], dtype=np.int64, name="test")
|
134 |
+
tm.assert_index_equal(result, expected)
|
135 |
+
|
136 |
+
result = idx.where(~mask, 10)
|
137 |
+
tm.assert_index_equal(result, expected)
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/ranges/test_join.py
ADDED
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
|
3 |
+
from pandas import (
|
4 |
+
Index,
|
5 |
+
RangeIndex,
|
6 |
+
)
|
7 |
+
import pandas._testing as tm
|
8 |
+
|
9 |
+
|
10 |
+
class TestJoin:
|
11 |
+
def test_join_outer(self):
|
12 |
+
# join with Index[int64]
|
13 |
+
index = RangeIndex(start=0, stop=20, step=2)
|
14 |
+
other = Index(np.arange(25, 14, -1, dtype=np.int64))
|
15 |
+
|
16 |
+
res, lidx, ridx = index.join(other, how="outer", return_indexers=True)
|
17 |
+
noidx_res = index.join(other, how="outer")
|
18 |
+
tm.assert_index_equal(res, noidx_res)
|
19 |
+
|
20 |
+
eres = Index(
|
21 |
+
[0, 2, 4, 6, 8, 10, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
|
22 |
+
)
|
23 |
+
elidx = np.array(
|
24 |
+
[0, 1, 2, 3, 4, 5, 6, 7, -1, 8, -1, 9, -1, -1, -1, -1, -1, -1, -1],
|
25 |
+
dtype=np.intp,
|
26 |
+
)
|
27 |
+
eridx = np.array(
|
28 |
+
[-1, -1, -1, -1, -1, -1, -1, -1, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0],
|
29 |
+
dtype=np.intp,
|
30 |
+
)
|
31 |
+
|
32 |
+
assert isinstance(res, Index) and res.dtype == np.dtype(np.int64)
|
33 |
+
assert not isinstance(res, RangeIndex)
|
34 |
+
tm.assert_index_equal(res, eres, exact=True)
|
35 |
+
tm.assert_numpy_array_equal(lidx, elidx)
|
36 |
+
tm.assert_numpy_array_equal(ridx, eridx)
|
37 |
+
|
38 |
+
# join with RangeIndex
|
39 |
+
other = RangeIndex(25, 14, -1)
|
40 |
+
|
41 |
+
res, lidx, ridx = index.join(other, how="outer", return_indexers=True)
|
42 |
+
noidx_res = index.join(other, how="outer")
|
43 |
+
tm.assert_index_equal(res, noidx_res)
|
44 |
+
|
45 |
+
assert isinstance(res, Index) and res.dtype == np.int64
|
46 |
+
assert not isinstance(res, RangeIndex)
|
47 |
+
tm.assert_index_equal(res, eres)
|
48 |
+
tm.assert_numpy_array_equal(lidx, elidx)
|
49 |
+
tm.assert_numpy_array_equal(ridx, eridx)
|
50 |
+
|
51 |
+
def test_join_inner(self):
|
52 |
+
# Join with non-RangeIndex
|
53 |
+
index = RangeIndex(start=0, stop=20, step=2)
|
54 |
+
other = Index(np.arange(25, 14, -1, dtype=np.int64))
|
55 |
+
|
56 |
+
res, lidx, ridx = index.join(other, how="inner", return_indexers=True)
|
57 |
+
|
58 |
+
# no guarantee of sortedness, so sort for comparison purposes
|
59 |
+
ind = res.argsort()
|
60 |
+
res = res.take(ind)
|
61 |
+
lidx = lidx.take(ind)
|
62 |
+
ridx = ridx.take(ind)
|
63 |
+
|
64 |
+
eres = Index([16, 18])
|
65 |
+
elidx = np.array([8, 9], dtype=np.intp)
|
66 |
+
eridx = np.array([9, 7], dtype=np.intp)
|
67 |
+
|
68 |
+
assert isinstance(res, Index) and res.dtype == np.int64
|
69 |
+
tm.assert_index_equal(res, eres)
|
70 |
+
tm.assert_numpy_array_equal(lidx, elidx)
|
71 |
+
tm.assert_numpy_array_equal(ridx, eridx)
|
72 |
+
|
73 |
+
# Join two RangeIndex
|
74 |
+
other = RangeIndex(25, 14, -1)
|
75 |
+
|
76 |
+
res, lidx, ridx = index.join(other, how="inner", return_indexers=True)
|
77 |
+
|
78 |
+
assert isinstance(res, RangeIndex)
|
79 |
+
tm.assert_index_equal(res, eres, exact="equiv")
|
80 |
+
tm.assert_numpy_array_equal(lidx, elidx)
|
81 |
+
tm.assert_numpy_array_equal(ridx, eridx)
|
82 |
+
|
83 |
+
def test_join_left(self):
|
84 |
+
# Join with Index[int64]
|
85 |
+
index = RangeIndex(start=0, stop=20, step=2)
|
86 |
+
other = Index(np.arange(25, 14, -1, dtype=np.int64))
|
87 |
+
|
88 |
+
res, lidx, ridx = index.join(other, how="left", return_indexers=True)
|
89 |
+
eres = index
|
90 |
+
eridx = np.array([-1, -1, -1, -1, -1, -1, -1, -1, 9, 7], dtype=np.intp)
|
91 |
+
|
92 |
+
assert isinstance(res, RangeIndex)
|
93 |
+
tm.assert_index_equal(res, eres)
|
94 |
+
assert lidx is None
|
95 |
+
tm.assert_numpy_array_equal(ridx, eridx)
|
96 |
+
|
97 |
+
# Join withRangeIndex
|
98 |
+
other = Index(np.arange(25, 14, -1, dtype=np.int64))
|
99 |
+
|
100 |
+
res, lidx, ridx = index.join(other, how="left", return_indexers=True)
|
101 |
+
|
102 |
+
assert isinstance(res, RangeIndex)
|
103 |
+
tm.assert_index_equal(res, eres)
|
104 |
+
assert lidx is None
|
105 |
+
tm.assert_numpy_array_equal(ridx, eridx)
|
106 |
+
|
107 |
+
def test_join_right(self):
|
108 |
+
# Join with Index[int64]
|
109 |
+
index = RangeIndex(start=0, stop=20, step=2)
|
110 |
+
other = Index(np.arange(25, 14, -1, dtype=np.int64))
|
111 |
+
|
112 |
+
res, lidx, ridx = index.join(other, how="right", return_indexers=True)
|
113 |
+
eres = other
|
114 |
+
elidx = np.array([-1, -1, -1, -1, -1, -1, -1, 9, -1, 8, -1], dtype=np.intp)
|
115 |
+
|
116 |
+
assert isinstance(other, Index) and other.dtype == np.int64
|
117 |
+
tm.assert_index_equal(res, eres)
|
118 |
+
tm.assert_numpy_array_equal(lidx, elidx)
|
119 |
+
assert ridx is None
|
120 |
+
|
121 |
+
# Join withRangeIndex
|
122 |
+
other = RangeIndex(25, 14, -1)
|
123 |
+
|
124 |
+
res, lidx, ridx = index.join(other, how="right", return_indexers=True)
|
125 |
+
eres = other
|
126 |
+
|
127 |
+
assert isinstance(other, RangeIndex)
|
128 |
+
tm.assert_index_equal(res, eres)
|
129 |
+
tm.assert_numpy_array_equal(lidx, elidx)
|
130 |
+
assert ridx is None
|
131 |
+
|
132 |
+
def test_join_non_int_index(self):
|
133 |
+
index = RangeIndex(start=0, stop=20, step=2)
|
134 |
+
other = Index([3, 6, 7, 8, 10], dtype=object)
|
135 |
+
|
136 |
+
outer = index.join(other, how="outer")
|
137 |
+
outer2 = other.join(index, how="outer")
|
138 |
+
expected = Index([0, 2, 3, 4, 6, 7, 8, 10, 12, 14, 16, 18])
|
139 |
+
tm.assert_index_equal(outer, outer2)
|
140 |
+
tm.assert_index_equal(outer, expected)
|
141 |
+
|
142 |
+
inner = index.join(other, how="inner")
|
143 |
+
inner2 = other.join(index, how="inner")
|
144 |
+
expected = Index([6, 8, 10])
|
145 |
+
tm.assert_index_equal(inner, inner2)
|
146 |
+
tm.assert_index_equal(inner, expected)
|
147 |
+
|
148 |
+
left = index.join(other, how="left")
|
149 |
+
tm.assert_index_equal(left, index.astype(object))
|
150 |
+
|
151 |
+
left2 = other.join(index, how="left")
|
152 |
+
tm.assert_index_equal(left2, other)
|
153 |
+
|
154 |
+
right = index.join(other, how="right")
|
155 |
+
tm.assert_index_equal(right, other)
|
156 |
+
|
157 |
+
right2 = other.join(index, how="right")
|
158 |
+
tm.assert_index_equal(right2, index.astype(object))
|
159 |
+
|
160 |
+
def test_join_non_unique(self):
|
161 |
+
index = RangeIndex(start=0, stop=20, step=2)
|
162 |
+
other = Index([4, 4, 3, 3])
|
163 |
+
|
164 |
+
res, lidx, ridx = index.join(other, return_indexers=True)
|
165 |
+
|
166 |
+
eres = Index([0, 2, 4, 4, 6, 8, 10, 12, 14, 16, 18])
|
167 |
+
elidx = np.array([0, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9], dtype=np.intp)
|
168 |
+
eridx = np.array([-1, -1, 0, 1, -1, -1, -1, -1, -1, -1, -1], dtype=np.intp)
|
169 |
+
|
170 |
+
tm.assert_index_equal(res, eres)
|
171 |
+
tm.assert_numpy_array_equal(lidx, elidx)
|
172 |
+
tm.assert_numpy_array_equal(ridx, eridx)
|
173 |
+
|
174 |
+
def test_join_self(self, join_type):
|
175 |
+
index = RangeIndex(start=0, stop=20, step=2)
|
176 |
+
joined = index.join(index, how=join_type)
|
177 |
+
assert index is joined
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/indexes/ranges/test_range.py
ADDED
@@ -0,0 +1,622 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas.core.dtypes.common import ensure_platform_int
|
5 |
+
|
6 |
+
import pandas as pd
|
7 |
+
from pandas import (
|
8 |
+
Index,
|
9 |
+
RangeIndex,
|
10 |
+
)
|
11 |
+
import pandas._testing as tm
|
12 |
+
|
13 |
+
|
14 |
+
class TestRangeIndex:
|
15 |
+
@pytest.fixture
|
16 |
+
def simple_index(self):
|
17 |
+
return RangeIndex(start=0, stop=20, step=2)
|
18 |
+
|
19 |
+
def test_constructor_unwraps_index(self):
|
20 |
+
result = RangeIndex(1, 3)
|
21 |
+
expected = np.array([1, 2], dtype=np.int64)
|
22 |
+
tm.assert_numpy_array_equal(result._data, expected)
|
23 |
+
|
24 |
+
def test_can_hold_identifiers(self, simple_index):
|
25 |
+
idx = simple_index
|
26 |
+
key = idx[0]
|
27 |
+
assert idx._can_hold_identifiers_and_holds_name(key) is False
|
28 |
+
|
29 |
+
def test_too_many_names(self, simple_index):
|
30 |
+
index = simple_index
|
31 |
+
with pytest.raises(ValueError, match="^Length"):
|
32 |
+
index.names = ["roger", "harold"]
|
33 |
+
|
34 |
+
@pytest.mark.parametrize(
|
35 |
+
"index, start, stop, step",
|
36 |
+
[
|
37 |
+
(RangeIndex(5), 0, 5, 1),
|
38 |
+
(RangeIndex(0, 5), 0, 5, 1),
|
39 |
+
(RangeIndex(5, step=2), 0, 5, 2),
|
40 |
+
(RangeIndex(1, 5, 2), 1, 5, 2),
|
41 |
+
],
|
42 |
+
)
|
43 |
+
def test_start_stop_step_attrs(self, index, start, stop, step):
|
44 |
+
# GH 25710
|
45 |
+
assert index.start == start
|
46 |
+
assert index.stop == stop
|
47 |
+
assert index.step == step
|
48 |
+
|
49 |
+
def test_copy(self):
|
50 |
+
i = RangeIndex(5, name="Foo")
|
51 |
+
i_copy = i.copy()
|
52 |
+
assert i_copy is not i
|
53 |
+
assert i_copy.identical(i)
|
54 |
+
assert i_copy._range == range(0, 5, 1)
|
55 |
+
assert i_copy.name == "Foo"
|
56 |
+
|
57 |
+
def test_repr(self):
|
58 |
+
i = RangeIndex(5, name="Foo")
|
59 |
+
result = repr(i)
|
60 |
+
expected = "RangeIndex(start=0, stop=5, step=1, name='Foo')"
|
61 |
+
assert result == expected
|
62 |
+
|
63 |
+
result = eval(result)
|
64 |
+
tm.assert_index_equal(result, i, exact=True)
|
65 |
+
|
66 |
+
i = RangeIndex(5, 0, -1)
|
67 |
+
result = repr(i)
|
68 |
+
expected = "RangeIndex(start=5, stop=0, step=-1)"
|
69 |
+
assert result == expected
|
70 |
+
|
71 |
+
result = eval(result)
|
72 |
+
tm.assert_index_equal(result, i, exact=True)
|
73 |
+
|
74 |
+
def test_insert(self):
|
75 |
+
idx = RangeIndex(5, name="Foo")
|
76 |
+
result = idx[1:4]
|
77 |
+
|
78 |
+
# test 0th element
|
79 |
+
tm.assert_index_equal(idx[0:4], result.insert(0, idx[0]), exact="equiv")
|
80 |
+
|
81 |
+
# GH 18295 (test missing)
|
82 |
+
expected = Index([0, np.nan, 1, 2, 3, 4], dtype=np.float64)
|
83 |
+
for na in [np.nan, None, pd.NA]:
|
84 |
+
result = RangeIndex(5).insert(1, na)
|
85 |
+
tm.assert_index_equal(result, expected)
|
86 |
+
|
87 |
+
result = RangeIndex(5).insert(1, pd.NaT)
|
88 |
+
expected = Index([0, pd.NaT, 1, 2, 3, 4], dtype=object)
|
89 |
+
tm.assert_index_equal(result, expected)
|
90 |
+
|
91 |
+
def test_insert_edges_preserves_rangeindex(self):
|
92 |
+
idx = Index(range(4, 9, 2))
|
93 |
+
|
94 |
+
result = idx.insert(0, 2)
|
95 |
+
expected = Index(range(2, 9, 2))
|
96 |
+
tm.assert_index_equal(result, expected, exact=True)
|
97 |
+
|
98 |
+
result = idx.insert(3, 10)
|
99 |
+
expected = Index(range(4, 11, 2))
|
100 |
+
tm.assert_index_equal(result, expected, exact=True)
|
101 |
+
|
102 |
+
def test_insert_middle_preserves_rangeindex(self):
|
103 |
+
# insert in the middle
|
104 |
+
idx = Index(range(0, 3, 2))
|
105 |
+
result = idx.insert(1, 1)
|
106 |
+
expected = Index(range(3))
|
107 |
+
tm.assert_index_equal(result, expected, exact=True)
|
108 |
+
|
109 |
+
idx = idx * 2
|
110 |
+
result = idx.insert(1, 2)
|
111 |
+
expected = expected * 2
|
112 |
+
tm.assert_index_equal(result, expected, exact=True)
|
113 |
+
|
114 |
+
def test_delete(self):
|
115 |
+
idx = RangeIndex(5, name="Foo")
|
116 |
+
expected = idx[1:]
|
117 |
+
result = idx.delete(0)
|
118 |
+
tm.assert_index_equal(result, expected, exact=True)
|
119 |
+
assert result.name == expected.name
|
120 |
+
|
121 |
+
expected = idx[:-1]
|
122 |
+
result = idx.delete(-1)
|
123 |
+
tm.assert_index_equal(result, expected, exact=True)
|
124 |
+
assert result.name == expected.name
|
125 |
+
|
126 |
+
msg = "index 5 is out of bounds for axis 0 with size 5"
|
127 |
+
with pytest.raises((IndexError, ValueError), match=msg):
|
128 |
+
# either depending on numpy version
|
129 |
+
result = idx.delete(len(idx))
|
130 |
+
|
131 |
+
def test_delete_preserves_rangeindex(self):
|
132 |
+
idx = Index(range(2), name="foo")
|
133 |
+
|
134 |
+
result = idx.delete([1])
|
135 |
+
expected = Index(range(1), name="foo")
|
136 |
+
tm.assert_index_equal(result, expected, exact=True)
|
137 |
+
|
138 |
+
result = idx.delete(1)
|
139 |
+
tm.assert_index_equal(result, expected, exact=True)
|
140 |
+
|
141 |
+
def test_delete_preserves_rangeindex_middle(self):
|
142 |
+
idx = Index(range(3), name="foo")
|
143 |
+
result = idx.delete(1)
|
144 |
+
expected = idx[::2]
|
145 |
+
tm.assert_index_equal(result, expected, exact=True)
|
146 |
+
|
147 |
+
result = idx.delete(-2)
|
148 |
+
tm.assert_index_equal(result, expected, exact=True)
|
149 |
+
|
150 |
+
def test_delete_preserves_rangeindex_list_at_end(self):
|
151 |
+
idx = RangeIndex(0, 6, 1)
|
152 |
+
|
153 |
+
loc = [2, 3, 4, 5]
|
154 |
+
result = idx.delete(loc)
|
155 |
+
expected = idx[:2]
|
156 |
+
tm.assert_index_equal(result, expected, exact=True)
|
157 |
+
|
158 |
+
result = idx.delete(loc[::-1])
|
159 |
+
tm.assert_index_equal(result, expected, exact=True)
|
160 |
+
|
161 |
+
def test_delete_preserves_rangeindex_list_middle(self):
|
162 |
+
idx = RangeIndex(0, 6, 1)
|
163 |
+
|
164 |
+
loc = [1, 2, 3, 4]
|
165 |
+
result = idx.delete(loc)
|
166 |
+
expected = RangeIndex(0, 6, 5)
|
167 |
+
tm.assert_index_equal(result, expected, exact=True)
|
168 |
+
|
169 |
+
result = idx.delete(loc[::-1])
|
170 |
+
tm.assert_index_equal(result, expected, exact=True)
|
171 |
+
|
172 |
+
def test_delete_all_preserves_rangeindex(self):
|
173 |
+
idx = RangeIndex(0, 6, 1)
|
174 |
+
|
175 |
+
loc = [0, 1, 2, 3, 4, 5]
|
176 |
+
result = idx.delete(loc)
|
177 |
+
expected = idx[:0]
|
178 |
+
tm.assert_index_equal(result, expected, exact=True)
|
179 |
+
|
180 |
+
result = idx.delete(loc[::-1])
|
181 |
+
tm.assert_index_equal(result, expected, exact=True)
|
182 |
+
|
183 |
+
def test_delete_not_preserving_rangeindex(self):
|
184 |
+
idx = RangeIndex(0, 6, 1)
|
185 |
+
|
186 |
+
loc = [0, 3, 5]
|
187 |
+
result = idx.delete(loc)
|
188 |
+
expected = Index([1, 2, 4])
|
189 |
+
tm.assert_index_equal(result, expected, exact=True)
|
190 |
+
|
191 |
+
result = idx.delete(loc[::-1])
|
192 |
+
tm.assert_index_equal(result, expected, exact=True)
|
193 |
+
|
194 |
+
def test_view(self):
|
195 |
+
i = RangeIndex(0, name="Foo")
|
196 |
+
i_view = i.view()
|
197 |
+
assert i_view.name == "Foo"
|
198 |
+
|
199 |
+
i_view = i.view("i8")
|
200 |
+
tm.assert_numpy_array_equal(i.values, i_view)
|
201 |
+
|
202 |
+
msg = "Passing a type in RangeIndex.view is deprecated"
|
203 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
204 |
+
i_view = i.view(RangeIndex)
|
205 |
+
tm.assert_index_equal(i, i_view)
|
206 |
+
|
207 |
+
def test_dtype(self, simple_index):
|
208 |
+
index = simple_index
|
209 |
+
assert index.dtype == np.int64
|
210 |
+
|
211 |
+
def test_cache(self):
|
212 |
+
# GH 26565, GH26617, GH35432, GH53387
|
213 |
+
# This test checks whether _cache has been set.
|
214 |
+
# Calling RangeIndex._cache["_data"] creates an int64 array of the same length
|
215 |
+
# as the RangeIndex and stores it in _cache.
|
216 |
+
idx = RangeIndex(0, 100, 10)
|
217 |
+
|
218 |
+
assert idx._cache == {}
|
219 |
+
|
220 |
+
repr(idx)
|
221 |
+
assert idx._cache == {}
|
222 |
+
|
223 |
+
str(idx)
|
224 |
+
assert idx._cache == {}
|
225 |
+
|
226 |
+
idx.get_loc(20)
|
227 |
+
assert idx._cache == {}
|
228 |
+
|
229 |
+
90 in idx # True
|
230 |
+
assert idx._cache == {}
|
231 |
+
|
232 |
+
91 in idx # False
|
233 |
+
assert idx._cache == {}
|
234 |
+
|
235 |
+
idx.all()
|
236 |
+
assert idx._cache == {}
|
237 |
+
|
238 |
+
idx.any()
|
239 |
+
assert idx._cache == {}
|
240 |
+
|
241 |
+
for _ in idx:
|
242 |
+
pass
|
243 |
+
assert idx._cache == {}
|
244 |
+
|
245 |
+
msg = "RangeIndex.format is deprecated"
|
246 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
247 |
+
idx.format()
|
248 |
+
assert idx._cache == {}
|
249 |
+
|
250 |
+
df = pd.DataFrame({"a": range(10)}, index=idx)
|
251 |
+
|
252 |
+
# df.__repr__ should not populate index cache
|
253 |
+
str(df)
|
254 |
+
assert idx._cache == {}
|
255 |
+
|
256 |
+
df.loc[50]
|
257 |
+
assert idx._cache == {}
|
258 |
+
|
259 |
+
with pytest.raises(KeyError, match="51"):
|
260 |
+
df.loc[51]
|
261 |
+
assert idx._cache == {}
|
262 |
+
|
263 |
+
df.loc[10:50]
|
264 |
+
assert idx._cache == {}
|
265 |
+
|
266 |
+
df.iloc[5:10]
|
267 |
+
assert idx._cache == {}
|
268 |
+
|
269 |
+
# after calling take, _cache may contain other keys, but not "_data"
|
270 |
+
idx.take([3, 0, 1])
|
271 |
+
assert "_data" not in idx._cache
|
272 |
+
|
273 |
+
df.loc[[50]]
|
274 |
+
assert "_data" not in idx._cache
|
275 |
+
|
276 |
+
df.iloc[[5, 6, 7, 8, 9]]
|
277 |
+
assert "_data" not in idx._cache
|
278 |
+
|
279 |
+
# idx._cache should contain a _data entry after call to idx._data
|
280 |
+
idx._data
|
281 |
+
assert isinstance(idx._data, np.ndarray)
|
282 |
+
assert idx._data is idx._data # check cached value is reused
|
283 |
+
assert "_data" in idx._cache
|
284 |
+
expected = np.arange(0, 100, 10, dtype="int64")
|
285 |
+
tm.assert_numpy_array_equal(idx._cache["_data"], expected)
|
286 |
+
|
287 |
+
def test_is_monotonic(self):
|
288 |
+
index = RangeIndex(0, 20, 2)
|
289 |
+
assert index.is_monotonic_increasing is True
|
290 |
+
assert index.is_monotonic_increasing is True
|
291 |
+
assert index.is_monotonic_decreasing is False
|
292 |
+
assert index._is_strictly_monotonic_increasing is True
|
293 |
+
assert index._is_strictly_monotonic_decreasing is False
|
294 |
+
|
295 |
+
index = RangeIndex(4, 0, -1)
|
296 |
+
assert index.is_monotonic_increasing is False
|
297 |
+
assert index._is_strictly_monotonic_increasing is False
|
298 |
+
assert index.is_monotonic_decreasing is True
|
299 |
+
assert index._is_strictly_monotonic_decreasing is True
|
300 |
+
|
301 |
+
index = RangeIndex(1, 2)
|
302 |
+
assert index.is_monotonic_increasing is True
|
303 |
+
assert index.is_monotonic_increasing is True
|
304 |
+
assert index.is_monotonic_decreasing is True
|
305 |
+
assert index._is_strictly_monotonic_increasing is True
|
306 |
+
assert index._is_strictly_monotonic_decreasing is True
|
307 |
+
|
308 |
+
index = RangeIndex(2, 1)
|
309 |
+
assert index.is_monotonic_increasing is True
|
310 |
+
assert index.is_monotonic_increasing is True
|
311 |
+
assert index.is_monotonic_decreasing is True
|
312 |
+
assert index._is_strictly_monotonic_increasing is True
|
313 |
+
assert index._is_strictly_monotonic_decreasing is True
|
314 |
+
|
315 |
+
index = RangeIndex(1, 1)
|
316 |
+
assert index.is_monotonic_increasing is True
|
317 |
+
assert index.is_monotonic_increasing is True
|
318 |
+
assert index.is_monotonic_decreasing is True
|
319 |
+
assert index._is_strictly_monotonic_increasing is True
|
320 |
+
assert index._is_strictly_monotonic_decreasing is True
|
321 |
+
|
322 |
+
@pytest.mark.parametrize(
|
323 |
+
"left,right",
|
324 |
+
[
|
325 |
+
(RangeIndex(0, 9, 2), RangeIndex(0, 10, 2)),
|
326 |
+
(RangeIndex(0), RangeIndex(1, -1, 3)),
|
327 |
+
(RangeIndex(1, 2, 3), RangeIndex(1, 3, 4)),
|
328 |
+
(RangeIndex(0, -9, -2), RangeIndex(0, -10, -2)),
|
329 |
+
],
|
330 |
+
)
|
331 |
+
def test_equals_range(self, left, right):
|
332 |
+
assert left.equals(right)
|
333 |
+
assert right.equals(left)
|
334 |
+
|
335 |
+
def test_logical_compat(self, simple_index):
|
336 |
+
idx = simple_index
|
337 |
+
assert idx.all() == idx.values.all()
|
338 |
+
assert idx.any() == idx.values.any()
|
339 |
+
|
340 |
+
def test_identical(self, simple_index):
|
341 |
+
index = simple_index
|
342 |
+
i = Index(index.copy())
|
343 |
+
assert i.identical(index)
|
344 |
+
|
345 |
+
# we don't allow object dtype for RangeIndex
|
346 |
+
if isinstance(index, RangeIndex):
|
347 |
+
return
|
348 |
+
|
349 |
+
same_values_different_type = Index(i, dtype=object)
|
350 |
+
assert not i.identical(same_values_different_type)
|
351 |
+
|
352 |
+
i = index.copy(dtype=object)
|
353 |
+
i = i.rename("foo")
|
354 |
+
same_values = Index(i, dtype=object)
|
355 |
+
assert same_values.identical(index.copy(dtype=object))
|
356 |
+
|
357 |
+
assert not i.identical(index)
|
358 |
+
assert Index(same_values, name="foo", dtype=object).identical(i)
|
359 |
+
|
360 |
+
assert not index.copy(dtype=object).identical(index.copy(dtype="int64"))
|
361 |
+
|
362 |
+
def test_nbytes(self):
|
363 |
+
# memory savings vs int index
|
364 |
+
idx = RangeIndex(0, 1000)
|
365 |
+
assert idx.nbytes < Index(idx._values).nbytes / 10
|
366 |
+
|
367 |
+
# constant memory usage
|
368 |
+
i2 = RangeIndex(0, 10)
|
369 |
+
assert idx.nbytes == i2.nbytes
|
370 |
+
|
371 |
+
@pytest.mark.parametrize(
|
372 |
+
"start,stop,step",
|
373 |
+
[
|
374 |
+
# can't
|
375 |
+
("foo", "bar", "baz"),
|
376 |
+
# shouldn't
|
377 |
+
("0", "1", "2"),
|
378 |
+
],
|
379 |
+
)
|
380 |
+
def test_cant_or_shouldnt_cast(self, start, stop, step):
|
381 |
+
msg = f"Wrong type {type(start)} for value {start}"
|
382 |
+
with pytest.raises(TypeError, match=msg):
|
383 |
+
RangeIndex(start, stop, step)
|
384 |
+
|
385 |
+
def test_view_index(self, simple_index):
|
386 |
+
index = simple_index
|
387 |
+
msg = "Passing a type in RangeIndex.view is deprecated"
|
388 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
389 |
+
index.view(Index)
|
390 |
+
|
391 |
+
def test_prevent_casting(self, simple_index):
|
392 |
+
index = simple_index
|
393 |
+
result = index.astype("O")
|
394 |
+
assert result.dtype == np.object_
|
395 |
+
|
396 |
+
def test_repr_roundtrip(self, simple_index):
|
397 |
+
index = simple_index
|
398 |
+
tm.assert_index_equal(eval(repr(index)), index)
|
399 |
+
|
400 |
+
def test_slice_keep_name(self):
|
401 |
+
idx = RangeIndex(1, 2, name="asdf")
|
402 |
+
assert idx.name == idx[1:].name
|
403 |
+
|
404 |
+
@pytest.mark.parametrize(
|
405 |
+
"index",
|
406 |
+
[
|
407 |
+
RangeIndex(start=0, stop=20, step=2, name="foo"),
|
408 |
+
RangeIndex(start=18, stop=-1, step=-2, name="bar"),
|
409 |
+
],
|
410 |
+
ids=["index_inc", "index_dec"],
|
411 |
+
)
|
412 |
+
def test_has_duplicates(self, index):
|
413 |
+
assert index.is_unique
|
414 |
+
assert not index.has_duplicates
|
415 |
+
|
416 |
+
def test_extended_gcd(self, simple_index):
|
417 |
+
index = simple_index
|
418 |
+
result = index._extended_gcd(6, 10)
|
419 |
+
assert result[0] == result[1] * 6 + result[2] * 10
|
420 |
+
assert 2 == result[0]
|
421 |
+
|
422 |
+
result = index._extended_gcd(10, 6)
|
423 |
+
assert 2 == result[1] * 10 + result[2] * 6
|
424 |
+
assert 2 == result[0]
|
425 |
+
|
426 |
+
def test_min_fitting_element(self):
|
427 |
+
result = RangeIndex(0, 20, 2)._min_fitting_element(1)
|
428 |
+
assert 2 == result
|
429 |
+
|
430 |
+
result = RangeIndex(1, 6)._min_fitting_element(1)
|
431 |
+
assert 1 == result
|
432 |
+
|
433 |
+
result = RangeIndex(18, -2, -2)._min_fitting_element(1)
|
434 |
+
assert 2 == result
|
435 |
+
|
436 |
+
result = RangeIndex(5, 0, -1)._min_fitting_element(1)
|
437 |
+
assert 1 == result
|
438 |
+
|
439 |
+
big_num = 500000000000000000000000
|
440 |
+
|
441 |
+
result = RangeIndex(5, big_num * 2, 1)._min_fitting_element(big_num)
|
442 |
+
assert big_num == result
|
443 |
+
|
444 |
+
def test_slice_specialised(self, simple_index):
|
445 |
+
index = simple_index
|
446 |
+
index.name = "foo"
|
447 |
+
|
448 |
+
# scalar indexing
|
449 |
+
res = index[1]
|
450 |
+
expected = 2
|
451 |
+
assert res == expected
|
452 |
+
|
453 |
+
res = index[-1]
|
454 |
+
expected = 18
|
455 |
+
assert res == expected
|
456 |
+
|
457 |
+
# slicing
|
458 |
+
# slice value completion
|
459 |
+
index_slice = index[:]
|
460 |
+
expected = index
|
461 |
+
tm.assert_index_equal(index_slice, expected)
|
462 |
+
|
463 |
+
# positive slice values
|
464 |
+
index_slice = index[7:10:2]
|
465 |
+
expected = Index([14, 18], name="foo")
|
466 |
+
tm.assert_index_equal(index_slice, expected, exact="equiv")
|
467 |
+
|
468 |
+
# negative slice values
|
469 |
+
index_slice = index[-1:-5:-2]
|
470 |
+
expected = Index([18, 14], name="foo")
|
471 |
+
tm.assert_index_equal(index_slice, expected, exact="equiv")
|
472 |
+
|
473 |
+
# stop overshoot
|
474 |
+
index_slice = index[2:100:4]
|
475 |
+
expected = Index([4, 12], name="foo")
|
476 |
+
tm.assert_index_equal(index_slice, expected, exact="equiv")
|
477 |
+
|
478 |
+
# reverse
|
479 |
+
index_slice = index[::-1]
|
480 |
+
expected = Index(index.values[::-1], name="foo")
|
481 |
+
tm.assert_index_equal(index_slice, expected, exact="equiv")
|
482 |
+
|
483 |
+
index_slice = index[-8::-1]
|
484 |
+
expected = Index([4, 2, 0], name="foo")
|
485 |
+
tm.assert_index_equal(index_slice, expected, exact="equiv")
|
486 |
+
|
487 |
+
index_slice = index[-40::-1]
|
488 |
+
expected = Index(np.array([], dtype=np.int64), name="foo")
|
489 |
+
tm.assert_index_equal(index_slice, expected, exact="equiv")
|
490 |
+
|
491 |
+
index_slice = index[40::-1]
|
492 |
+
expected = Index(index.values[40::-1], name="foo")
|
493 |
+
tm.assert_index_equal(index_slice, expected, exact="equiv")
|
494 |
+
|
495 |
+
index_slice = index[10::-1]
|
496 |
+
expected = Index(index.values[::-1], name="foo")
|
497 |
+
tm.assert_index_equal(index_slice, expected, exact="equiv")
|
498 |
+
|
499 |
+
@pytest.mark.parametrize("step", set(range(-5, 6)) - {0})
|
500 |
+
def test_len_specialised(self, step):
|
501 |
+
# make sure that our len is the same as np.arange calc
|
502 |
+
start, stop = (0, 5) if step > 0 else (5, 0)
|
503 |
+
|
504 |
+
arr = np.arange(start, stop, step)
|
505 |
+
index = RangeIndex(start, stop, step)
|
506 |
+
assert len(index) == len(arr)
|
507 |
+
|
508 |
+
index = RangeIndex(stop, start, step)
|
509 |
+
assert len(index) == 0
|
510 |
+
|
511 |
+
@pytest.mark.parametrize(
|
512 |
+
"indices, expected",
|
513 |
+
[
|
514 |
+
([RangeIndex(1, 12, 5)], RangeIndex(1, 12, 5)),
|
515 |
+
([RangeIndex(0, 6, 4)], RangeIndex(0, 6, 4)),
|
516 |
+
([RangeIndex(1, 3), RangeIndex(3, 7)], RangeIndex(1, 7)),
|
517 |
+
([RangeIndex(1, 5, 2), RangeIndex(5, 6)], RangeIndex(1, 6, 2)),
|
518 |
+
([RangeIndex(1, 3, 2), RangeIndex(4, 7, 3)], RangeIndex(1, 7, 3)),
|
519 |
+
([RangeIndex(-4, 3, 2), RangeIndex(4, 7, 2)], RangeIndex(-4, 7, 2)),
|
520 |
+
([RangeIndex(-4, -8), RangeIndex(-8, -12)], RangeIndex(0, 0)),
|
521 |
+
([RangeIndex(-4, -8), RangeIndex(3, -4)], RangeIndex(0, 0)),
|
522 |
+
([RangeIndex(-4, -8), RangeIndex(3, 5)], RangeIndex(3, 5)),
|
523 |
+
([RangeIndex(-4, -2), RangeIndex(3, 5)], Index([-4, -3, 3, 4])),
|
524 |
+
([RangeIndex(-2), RangeIndex(3, 5)], RangeIndex(3, 5)),
|
525 |
+
([RangeIndex(2), RangeIndex(2)], Index([0, 1, 0, 1])),
|
526 |
+
([RangeIndex(2), RangeIndex(2, 5), RangeIndex(5, 8, 4)], RangeIndex(0, 6)),
|
527 |
+
(
|
528 |
+
[RangeIndex(2), RangeIndex(3, 5), RangeIndex(5, 8, 4)],
|
529 |
+
Index([0, 1, 3, 4, 5]),
|
530 |
+
),
|
531 |
+
(
|
532 |
+
[RangeIndex(-2, 2), RangeIndex(2, 5), RangeIndex(5, 8, 4)],
|
533 |
+
RangeIndex(-2, 6),
|
534 |
+
),
|
535 |
+
([RangeIndex(3), Index([-1, 3, 15])], Index([0, 1, 2, -1, 3, 15])),
|
536 |
+
([RangeIndex(3), Index([-1, 3.1, 15.0])], Index([0, 1, 2, -1, 3.1, 15.0])),
|
537 |
+
([RangeIndex(3), Index(["a", None, 14])], Index([0, 1, 2, "a", None, 14])),
|
538 |
+
([RangeIndex(3, 1), Index(["a", None, 14])], Index(["a", None, 14])),
|
539 |
+
],
|
540 |
+
)
|
541 |
+
def test_append(self, indices, expected):
|
542 |
+
# GH16212
|
543 |
+
result = indices[0].append(indices[1:])
|
544 |
+
tm.assert_index_equal(result, expected, exact=True)
|
545 |
+
|
546 |
+
if len(indices) == 2:
|
547 |
+
# Append single item rather than list
|
548 |
+
result2 = indices[0].append(indices[1])
|
549 |
+
tm.assert_index_equal(result2, expected, exact=True)
|
550 |
+
|
551 |
+
def test_engineless_lookup(self):
|
552 |
+
# GH 16685
|
553 |
+
# Standard lookup on RangeIndex should not require the engine to be
|
554 |
+
# created
|
555 |
+
idx = RangeIndex(2, 10, 3)
|
556 |
+
|
557 |
+
assert idx.get_loc(5) == 1
|
558 |
+
tm.assert_numpy_array_equal(
|
559 |
+
idx.get_indexer([2, 8]), ensure_platform_int(np.array([0, 2]))
|
560 |
+
)
|
561 |
+
with pytest.raises(KeyError, match="3"):
|
562 |
+
idx.get_loc(3)
|
563 |
+
|
564 |
+
assert "_engine" not in idx._cache
|
565 |
+
|
566 |
+
# Different types of scalars can be excluded immediately, no need to
|
567 |
+
# use the _engine
|
568 |
+
with pytest.raises(KeyError, match="'a'"):
|
569 |
+
idx.get_loc("a")
|
570 |
+
|
571 |
+
assert "_engine" not in idx._cache
|
572 |
+
|
573 |
+
def test_format_empty(self):
|
574 |
+
# GH35712
|
575 |
+
empty_idx = RangeIndex(0)
|
576 |
+
msg = r"RangeIndex\.format is deprecated"
|
577 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
578 |
+
assert empty_idx.format() == []
|
579 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
580 |
+
assert empty_idx.format(name=True) == [""]
|
581 |
+
|
582 |
+
@pytest.mark.parametrize(
|
583 |
+
"ri",
|
584 |
+
[
|
585 |
+
RangeIndex(0, -1, -1),
|
586 |
+
RangeIndex(0, 1, 1),
|
587 |
+
RangeIndex(1, 3, 2),
|
588 |
+
RangeIndex(0, -1, -2),
|
589 |
+
RangeIndex(-3, -5, -2),
|
590 |
+
],
|
591 |
+
)
|
592 |
+
def test_append_len_one(self, ri):
|
593 |
+
# GH39401
|
594 |
+
result = ri.append([])
|
595 |
+
tm.assert_index_equal(result, ri, exact=True)
|
596 |
+
|
597 |
+
@pytest.mark.parametrize("base", [RangeIndex(0, 2), Index([0, 1])])
|
598 |
+
def test_isin_range(self, base):
|
599 |
+
# GH#41151
|
600 |
+
values = RangeIndex(0, 1)
|
601 |
+
result = base.isin(values)
|
602 |
+
expected = np.array([True, False])
|
603 |
+
tm.assert_numpy_array_equal(result, expected)
|
604 |
+
|
605 |
+
def test_sort_values_key(self):
|
606 |
+
# GH#43666, GH#52764
|
607 |
+
sort_order = {8: 2, 6: 0, 4: 8, 2: 10, 0: 12}
|
608 |
+
values = RangeIndex(0, 10, 2)
|
609 |
+
result = values.sort_values(key=lambda x: x.map(sort_order))
|
610 |
+
expected = Index([6, 8, 4, 2, 0], dtype="int64")
|
611 |
+
tm.assert_index_equal(result, expected, check_exact=True)
|
612 |
+
|
613 |
+
# check this matches the Series.sort_values behavior
|
614 |
+
ser = values.to_series()
|
615 |
+
result2 = ser.sort_values(key=lambda x: x.map(sort_order))
|
616 |
+
tm.assert_series_equal(result2, expected.to_series(), check_exact=True)
|
617 |
+
|
618 |
+
def test_range_index_rsub_by_const(self):
|
619 |
+
# GH#53255
|
620 |
+
result = 3 - RangeIndex(0, 4, 1)
|
621 |
+
expected = RangeIndex(3, -1, -1)
|
622 |
+
tm.assert_index_equal(result, expected)
|