Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/__pycache__/test_array.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/__pycache__/test_clip.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/__pycache__/test_functions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/__pycache__/test_replace.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/__pycache__/test_util.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/index/__init__.py +0 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/index/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/index/__pycache__/test_datetimeindex.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/index/__pycache__/test_index.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/index/__pycache__/test_periodindex.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/index/__pycache__/test_timedeltaindex.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/index/test_datetimeindex.py +69 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/index/test_index.py +184 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/index/test_periodindex.py +30 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/index/test_timedeltaindex.py +30 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/__init__.py +0 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/conftest.py +41 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/__init__.py +0 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/__pycache__/test_pickle.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/__pycache__/test_resolution.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/methods/__init__.py +0 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/methods/__pycache__/test_is_full.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/methods/__pycache__/test_repeat.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/methods/__pycache__/test_shift.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/methods/test_asfreq.py +189 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/methods/test_factorize.py +41 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/methods/test_insert.py +18 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/methods/test_is_full.py +23 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/methods/test_repeat.py +26 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/methods/test_to_timestamp.py +142 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/test_indexing.py +815 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/test_resolution.py +23 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/test_scalar_compat.py +38 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/test_searchsorted.py +80 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/test_tools.py +52 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/test_any_index.py +172 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/test_base.py +1737 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/test_common.py +511 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/test_datetimelike.py +171 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/test_engines.py +192 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/test_frozen.py +113 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/test_index_new.py +432 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/test_indexing.py +357 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/test_numpy_compat.py +189 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/test_old_base.py +1061 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/test_setops.py +959 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/test_subclass.py +40 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/resample/__init__.py +0 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/resample/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pandas/tests/resample/__pycache__/conftest.cpython-310.pyc +0 -0
env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/__pycache__/test_array.cpython-310.pyc
ADDED
Binary file (4.78 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/__pycache__/test_clip.cpython-310.pyc
ADDED
Binary file (3.07 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/__pycache__/test_functions.cpython-310.pyc
ADDED
Binary file (10.1 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/__pycache__/test_replace.cpython-310.pyc
ADDED
Binary file (12.6 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/__pycache__/test_util.cpython-310.pyc
ADDED
Binary file (711 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/index/__init__.py
ADDED
File without changes
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/index/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (193 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/index/__pycache__/test_datetimeindex.cpython-310.pyc
ADDED
Binary file (2.31 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/index/__pycache__/test_index.cpython-310.pyc
ADDED
Binary file (5.89 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/index/__pycache__/test_periodindex.cpython-310.pyc
ADDED
Binary file (1.06 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/index/__pycache__/test_timedeltaindex.cpython-310.pyc
ADDED
Binary file (1.06 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/index/test_datetimeindex.py
ADDED
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
from pandas import (
|
4 |
+
DatetimeIndex,
|
5 |
+
Series,
|
6 |
+
Timestamp,
|
7 |
+
date_range,
|
8 |
+
)
|
9 |
+
import pandas._testing as tm
|
10 |
+
|
11 |
+
pytestmark = pytest.mark.filterwarnings(
|
12 |
+
"ignore:Setting a value on a view:FutureWarning"
|
13 |
+
)
|
14 |
+
|
15 |
+
|
16 |
+
@pytest.mark.parametrize(
|
17 |
+
"cons",
|
18 |
+
[
|
19 |
+
lambda x: DatetimeIndex(x),
|
20 |
+
lambda x: DatetimeIndex(DatetimeIndex(x)),
|
21 |
+
],
|
22 |
+
)
|
23 |
+
def test_datetimeindex(using_copy_on_write, cons):
|
24 |
+
dt = date_range("2019-12-31", periods=3, freq="D")
|
25 |
+
ser = Series(dt)
|
26 |
+
idx = cons(ser)
|
27 |
+
expected = idx.copy(deep=True)
|
28 |
+
ser.iloc[0] = Timestamp("2020-12-31")
|
29 |
+
if using_copy_on_write:
|
30 |
+
tm.assert_index_equal(idx, expected)
|
31 |
+
|
32 |
+
|
33 |
+
def test_datetimeindex_tz_convert(using_copy_on_write):
|
34 |
+
dt = date_range("2019-12-31", periods=3, freq="D", tz="Europe/Berlin")
|
35 |
+
ser = Series(dt)
|
36 |
+
idx = DatetimeIndex(ser).tz_convert("US/Eastern")
|
37 |
+
expected = idx.copy(deep=True)
|
38 |
+
ser.iloc[0] = Timestamp("2020-12-31", tz="Europe/Berlin")
|
39 |
+
if using_copy_on_write:
|
40 |
+
tm.assert_index_equal(idx, expected)
|
41 |
+
|
42 |
+
|
43 |
+
def test_datetimeindex_tz_localize(using_copy_on_write):
|
44 |
+
dt = date_range("2019-12-31", periods=3, freq="D")
|
45 |
+
ser = Series(dt)
|
46 |
+
idx = DatetimeIndex(ser).tz_localize("Europe/Berlin")
|
47 |
+
expected = idx.copy(deep=True)
|
48 |
+
ser.iloc[0] = Timestamp("2020-12-31")
|
49 |
+
if using_copy_on_write:
|
50 |
+
tm.assert_index_equal(idx, expected)
|
51 |
+
|
52 |
+
|
53 |
+
def test_datetimeindex_isocalendar(using_copy_on_write):
|
54 |
+
dt = date_range("2019-12-31", periods=3, freq="D")
|
55 |
+
ser = Series(dt)
|
56 |
+
df = DatetimeIndex(ser).isocalendar()
|
57 |
+
expected = df.index.copy(deep=True)
|
58 |
+
ser.iloc[0] = Timestamp("2020-12-31")
|
59 |
+
if using_copy_on_write:
|
60 |
+
tm.assert_index_equal(df.index, expected)
|
61 |
+
|
62 |
+
|
63 |
+
def test_index_values(using_copy_on_write):
|
64 |
+
idx = date_range("2019-12-31", periods=3, freq="D")
|
65 |
+
result = idx.values
|
66 |
+
if using_copy_on_write:
|
67 |
+
assert result.flags.writeable is False
|
68 |
+
else:
|
69 |
+
assert result.flags.writeable is True
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/index/test_index.py
ADDED
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas import (
|
5 |
+
DataFrame,
|
6 |
+
Index,
|
7 |
+
Series,
|
8 |
+
)
|
9 |
+
import pandas._testing as tm
|
10 |
+
from pandas.tests.copy_view.util import get_array
|
11 |
+
|
12 |
+
|
13 |
+
def index_view(index_data=[1, 2]):
|
14 |
+
df = DataFrame({"a": index_data, "b": 1.5})
|
15 |
+
view = df[:]
|
16 |
+
df = df.set_index("a", drop=True)
|
17 |
+
idx = df.index
|
18 |
+
# df = None
|
19 |
+
return idx, view
|
20 |
+
|
21 |
+
|
22 |
+
def test_set_index_update_column(using_copy_on_write, warn_copy_on_write):
|
23 |
+
df = DataFrame({"a": [1, 2], "b": 1})
|
24 |
+
df = df.set_index("a", drop=False)
|
25 |
+
expected = df.index.copy(deep=True)
|
26 |
+
with tm.assert_cow_warning(warn_copy_on_write):
|
27 |
+
df.iloc[0, 0] = 100
|
28 |
+
if using_copy_on_write:
|
29 |
+
tm.assert_index_equal(df.index, expected)
|
30 |
+
else:
|
31 |
+
tm.assert_index_equal(df.index, Index([100, 2], name="a"))
|
32 |
+
|
33 |
+
|
34 |
+
def test_set_index_drop_update_column(using_copy_on_write):
|
35 |
+
df = DataFrame({"a": [1, 2], "b": 1.5})
|
36 |
+
view = df[:]
|
37 |
+
df = df.set_index("a", drop=True)
|
38 |
+
expected = df.index.copy(deep=True)
|
39 |
+
view.iloc[0, 0] = 100
|
40 |
+
tm.assert_index_equal(df.index, expected)
|
41 |
+
|
42 |
+
|
43 |
+
def test_set_index_series(using_copy_on_write, warn_copy_on_write):
|
44 |
+
df = DataFrame({"a": [1, 2], "b": 1.5})
|
45 |
+
ser = Series([10, 11])
|
46 |
+
df = df.set_index(ser)
|
47 |
+
expected = df.index.copy(deep=True)
|
48 |
+
with tm.assert_cow_warning(warn_copy_on_write):
|
49 |
+
ser.iloc[0] = 100
|
50 |
+
if using_copy_on_write:
|
51 |
+
tm.assert_index_equal(df.index, expected)
|
52 |
+
else:
|
53 |
+
tm.assert_index_equal(df.index, Index([100, 11]))
|
54 |
+
|
55 |
+
|
56 |
+
def test_assign_index_as_series(using_copy_on_write, warn_copy_on_write):
|
57 |
+
df = DataFrame({"a": [1, 2], "b": 1.5})
|
58 |
+
ser = Series([10, 11])
|
59 |
+
df.index = ser
|
60 |
+
expected = df.index.copy(deep=True)
|
61 |
+
with tm.assert_cow_warning(warn_copy_on_write):
|
62 |
+
ser.iloc[0] = 100
|
63 |
+
if using_copy_on_write:
|
64 |
+
tm.assert_index_equal(df.index, expected)
|
65 |
+
else:
|
66 |
+
tm.assert_index_equal(df.index, Index([100, 11]))
|
67 |
+
|
68 |
+
|
69 |
+
def test_assign_index_as_index(using_copy_on_write, warn_copy_on_write):
|
70 |
+
df = DataFrame({"a": [1, 2], "b": 1.5})
|
71 |
+
ser = Series([10, 11])
|
72 |
+
rhs_index = Index(ser)
|
73 |
+
df.index = rhs_index
|
74 |
+
rhs_index = None # overwrite to clear reference
|
75 |
+
expected = df.index.copy(deep=True)
|
76 |
+
with tm.assert_cow_warning(warn_copy_on_write):
|
77 |
+
ser.iloc[0] = 100
|
78 |
+
if using_copy_on_write:
|
79 |
+
tm.assert_index_equal(df.index, expected)
|
80 |
+
else:
|
81 |
+
tm.assert_index_equal(df.index, Index([100, 11]))
|
82 |
+
|
83 |
+
|
84 |
+
def test_index_from_series(using_copy_on_write, warn_copy_on_write):
|
85 |
+
ser = Series([1, 2])
|
86 |
+
idx = Index(ser)
|
87 |
+
expected = idx.copy(deep=True)
|
88 |
+
with tm.assert_cow_warning(warn_copy_on_write):
|
89 |
+
ser.iloc[0] = 100
|
90 |
+
if using_copy_on_write:
|
91 |
+
tm.assert_index_equal(idx, expected)
|
92 |
+
else:
|
93 |
+
tm.assert_index_equal(idx, Index([100, 2]))
|
94 |
+
|
95 |
+
|
96 |
+
def test_index_from_series_copy(using_copy_on_write):
|
97 |
+
ser = Series([1, 2])
|
98 |
+
idx = Index(ser, copy=True) # noqa: F841
|
99 |
+
arr = get_array(ser)
|
100 |
+
ser.iloc[0] = 100
|
101 |
+
assert np.shares_memory(get_array(ser), arr)
|
102 |
+
|
103 |
+
|
104 |
+
def test_index_from_index(using_copy_on_write, warn_copy_on_write):
|
105 |
+
ser = Series([1, 2])
|
106 |
+
idx = Index(ser)
|
107 |
+
idx = Index(idx)
|
108 |
+
expected = idx.copy(deep=True)
|
109 |
+
with tm.assert_cow_warning(warn_copy_on_write):
|
110 |
+
ser.iloc[0] = 100
|
111 |
+
if using_copy_on_write:
|
112 |
+
tm.assert_index_equal(idx, expected)
|
113 |
+
else:
|
114 |
+
tm.assert_index_equal(idx, Index([100, 2]))
|
115 |
+
|
116 |
+
|
117 |
+
@pytest.mark.parametrize(
|
118 |
+
"func",
|
119 |
+
[
|
120 |
+
lambda x: x._shallow_copy(x._values),
|
121 |
+
lambda x: x.view(),
|
122 |
+
lambda x: x.take([0, 1]),
|
123 |
+
lambda x: x.repeat([1, 1]),
|
124 |
+
lambda x: x[slice(0, 2)],
|
125 |
+
lambda x: x[[0, 1]],
|
126 |
+
lambda x: x._getitem_slice(slice(0, 2)),
|
127 |
+
lambda x: x.delete([]),
|
128 |
+
lambda x: x.rename("b"),
|
129 |
+
lambda x: x.astype("Int64", copy=False),
|
130 |
+
],
|
131 |
+
ids=[
|
132 |
+
"_shallow_copy",
|
133 |
+
"view",
|
134 |
+
"take",
|
135 |
+
"repeat",
|
136 |
+
"getitem_slice",
|
137 |
+
"getitem_list",
|
138 |
+
"_getitem_slice",
|
139 |
+
"delete",
|
140 |
+
"rename",
|
141 |
+
"astype",
|
142 |
+
],
|
143 |
+
)
|
144 |
+
def test_index_ops(using_copy_on_write, func, request):
|
145 |
+
idx, view_ = index_view()
|
146 |
+
expected = idx.copy(deep=True)
|
147 |
+
if "astype" in request.node.callspec.id:
|
148 |
+
expected = expected.astype("Int64")
|
149 |
+
idx = func(idx)
|
150 |
+
view_.iloc[0, 0] = 100
|
151 |
+
if using_copy_on_write:
|
152 |
+
tm.assert_index_equal(idx, expected, check_names=False)
|
153 |
+
|
154 |
+
|
155 |
+
def test_infer_objects(using_copy_on_write):
|
156 |
+
idx, view_ = index_view(["a", "b"])
|
157 |
+
expected = idx.copy(deep=True)
|
158 |
+
idx = idx.infer_objects(copy=False)
|
159 |
+
view_.iloc[0, 0] = "aaaa"
|
160 |
+
if using_copy_on_write:
|
161 |
+
tm.assert_index_equal(idx, expected, check_names=False)
|
162 |
+
|
163 |
+
|
164 |
+
def test_index_to_frame(using_copy_on_write):
|
165 |
+
idx = Index([1, 2, 3], name="a")
|
166 |
+
expected = idx.copy(deep=True)
|
167 |
+
df = idx.to_frame()
|
168 |
+
if using_copy_on_write:
|
169 |
+
assert np.shares_memory(get_array(df, "a"), idx._values)
|
170 |
+
assert not df._mgr._has_no_reference(0)
|
171 |
+
else:
|
172 |
+
assert not np.shares_memory(get_array(df, "a"), idx._values)
|
173 |
+
|
174 |
+
df.iloc[0, 0] = 100
|
175 |
+
tm.assert_index_equal(idx, expected)
|
176 |
+
|
177 |
+
|
178 |
+
def test_index_values(using_copy_on_write):
|
179 |
+
idx = Index([1, 2, 3])
|
180 |
+
result = idx.values
|
181 |
+
if using_copy_on_write:
|
182 |
+
assert result.flags.writeable is False
|
183 |
+
else:
|
184 |
+
assert result.flags.writeable is True
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/index/test_periodindex.py
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
from pandas import (
|
4 |
+
Period,
|
5 |
+
PeriodIndex,
|
6 |
+
Series,
|
7 |
+
period_range,
|
8 |
+
)
|
9 |
+
import pandas._testing as tm
|
10 |
+
|
11 |
+
pytestmark = pytest.mark.filterwarnings(
|
12 |
+
"ignore:Setting a value on a view:FutureWarning"
|
13 |
+
)
|
14 |
+
|
15 |
+
|
16 |
+
@pytest.mark.parametrize(
|
17 |
+
"cons",
|
18 |
+
[
|
19 |
+
lambda x: PeriodIndex(x),
|
20 |
+
lambda x: PeriodIndex(PeriodIndex(x)),
|
21 |
+
],
|
22 |
+
)
|
23 |
+
def test_periodindex(using_copy_on_write, cons):
|
24 |
+
dt = period_range("2019-12-31", periods=3, freq="D")
|
25 |
+
ser = Series(dt)
|
26 |
+
idx = cons(ser)
|
27 |
+
expected = idx.copy(deep=True)
|
28 |
+
ser.iloc[0] = Period("2020-12-31")
|
29 |
+
if using_copy_on_write:
|
30 |
+
tm.assert_index_equal(idx, expected)
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/copy_view/index/test_timedeltaindex.py
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
from pandas import (
|
4 |
+
Series,
|
5 |
+
Timedelta,
|
6 |
+
TimedeltaIndex,
|
7 |
+
timedelta_range,
|
8 |
+
)
|
9 |
+
import pandas._testing as tm
|
10 |
+
|
11 |
+
pytestmark = pytest.mark.filterwarnings(
|
12 |
+
"ignore:Setting a value on a view:FutureWarning"
|
13 |
+
)
|
14 |
+
|
15 |
+
|
16 |
+
@pytest.mark.parametrize(
|
17 |
+
"cons",
|
18 |
+
[
|
19 |
+
lambda x: TimedeltaIndex(x),
|
20 |
+
lambda x: TimedeltaIndex(TimedeltaIndex(x)),
|
21 |
+
],
|
22 |
+
)
|
23 |
+
def test_timedeltaindex(using_copy_on_write, cons):
|
24 |
+
dt = timedelta_range("1 day", periods=3)
|
25 |
+
ser = Series(dt)
|
26 |
+
idx = cons(ser)
|
27 |
+
expected = idx.copy(deep=True)
|
28 |
+
ser.iloc[0] = Timedelta("5 days")
|
29 |
+
if using_copy_on_write:
|
30 |
+
tm.assert_index_equal(idx, expected)
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/__init__.py
ADDED
File without changes
|
env-llmeval/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
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/__init__.py
ADDED
File without changes
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/__pycache__/test_pickle.cpython-310.pyc
ADDED
Binary file (1.21 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/__pycache__/test_resolution.cpython-310.pyc
ADDED
Binary file (852 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/methods/__init__.py
ADDED
File without changes
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/methods/__pycache__/test_is_full.cpython-310.pyc
ADDED
Binary file (759 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/methods/__pycache__/test_repeat.cpython-310.pyc
ADDED
Binary file (1.22 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/methods/__pycache__/test_shift.cpython-310.pyc
ADDED
Binary file (3.56 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/methods/test_asfreq.py
ADDED
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
|
3 |
+
import pytest
|
4 |
+
|
5 |
+
from pandas import (
|
6 |
+
PeriodIndex,
|
7 |
+
Series,
|
8 |
+
period_range,
|
9 |
+
)
|
10 |
+
import pandas._testing as tm
|
11 |
+
|
12 |
+
from pandas.tseries import offsets
|
13 |
+
|
14 |
+
|
15 |
+
class TestPeriodIndex:
|
16 |
+
def test_asfreq(self):
|
17 |
+
pi1 = period_range(freq="Y", start="1/1/2001", end="1/1/2001")
|
18 |
+
pi2 = period_range(freq="Q", start="1/1/2001", end="1/1/2001")
|
19 |
+
pi3 = period_range(freq="M", start="1/1/2001", end="1/1/2001")
|
20 |
+
pi4 = period_range(freq="D", start="1/1/2001", end="1/1/2001")
|
21 |
+
pi5 = period_range(freq="h", start="1/1/2001", end="1/1/2001 00:00")
|
22 |
+
pi6 = period_range(freq="Min", start="1/1/2001", end="1/1/2001 00:00")
|
23 |
+
pi7 = period_range(freq="s", start="1/1/2001", end="1/1/2001 00:00:00")
|
24 |
+
|
25 |
+
assert pi1.asfreq("Q", "s") == pi2
|
26 |
+
assert pi1.asfreq("Q", "s") == pi2
|
27 |
+
assert pi1.asfreq("M", "start") == pi3
|
28 |
+
assert pi1.asfreq("D", "StarT") == pi4
|
29 |
+
assert pi1.asfreq("h", "beGIN") == pi5
|
30 |
+
assert pi1.asfreq("Min", "s") == pi6
|
31 |
+
assert pi1.asfreq("s", "s") == pi7
|
32 |
+
|
33 |
+
assert pi2.asfreq("Y", "s") == pi1
|
34 |
+
assert pi2.asfreq("M", "s") == pi3
|
35 |
+
assert pi2.asfreq("D", "s") == pi4
|
36 |
+
assert pi2.asfreq("h", "s") == pi5
|
37 |
+
assert pi2.asfreq("Min", "s") == pi6
|
38 |
+
assert pi2.asfreq("s", "s") == pi7
|
39 |
+
|
40 |
+
assert pi3.asfreq("Y", "s") == pi1
|
41 |
+
assert pi3.asfreq("Q", "s") == pi2
|
42 |
+
assert pi3.asfreq("D", "s") == pi4
|
43 |
+
assert pi3.asfreq("h", "s") == pi5
|
44 |
+
assert pi3.asfreq("Min", "s") == pi6
|
45 |
+
assert pi3.asfreq("s", "s") == pi7
|
46 |
+
|
47 |
+
assert pi4.asfreq("Y", "s") == pi1
|
48 |
+
assert pi4.asfreq("Q", "s") == pi2
|
49 |
+
assert pi4.asfreq("M", "s") == pi3
|
50 |
+
assert pi4.asfreq("h", "s") == pi5
|
51 |
+
assert pi4.asfreq("Min", "s") == pi6
|
52 |
+
assert pi4.asfreq("s", "s") == pi7
|
53 |
+
|
54 |
+
assert pi5.asfreq("Y", "s") == pi1
|
55 |
+
assert pi5.asfreq("Q", "s") == pi2
|
56 |
+
assert pi5.asfreq("M", "s") == pi3
|
57 |
+
assert pi5.asfreq("D", "s") == pi4
|
58 |
+
assert pi5.asfreq("Min", "s") == pi6
|
59 |
+
assert pi5.asfreq("s", "s") == pi7
|
60 |
+
|
61 |
+
assert pi6.asfreq("Y", "s") == pi1
|
62 |
+
assert pi6.asfreq("Q", "s") == pi2
|
63 |
+
assert pi6.asfreq("M", "s") == pi3
|
64 |
+
assert pi6.asfreq("D", "s") == pi4
|
65 |
+
assert pi6.asfreq("h", "s") == pi5
|
66 |
+
assert pi6.asfreq("s", "s") == pi7
|
67 |
+
|
68 |
+
assert pi7.asfreq("Y", "s") == pi1
|
69 |
+
assert pi7.asfreq("Q", "s") == pi2
|
70 |
+
assert pi7.asfreq("M", "s") == pi3
|
71 |
+
assert pi7.asfreq("D", "s") == pi4
|
72 |
+
assert pi7.asfreq("h", "s") == pi5
|
73 |
+
assert pi7.asfreq("Min", "s") == pi6
|
74 |
+
|
75 |
+
msg = "How must be one of S or E"
|
76 |
+
with pytest.raises(ValueError, match=msg):
|
77 |
+
pi7.asfreq("T", "foo")
|
78 |
+
result1 = pi1.asfreq("3M")
|
79 |
+
result2 = pi1.asfreq("M")
|
80 |
+
expected = period_range(freq="M", start="2001-12", end="2001-12")
|
81 |
+
tm.assert_numpy_array_equal(result1.asi8, expected.asi8)
|
82 |
+
assert result1.freqstr == "3M"
|
83 |
+
tm.assert_numpy_array_equal(result2.asi8, expected.asi8)
|
84 |
+
assert result2.freqstr == "M"
|
85 |
+
|
86 |
+
def test_asfreq_nat(self):
|
87 |
+
idx = PeriodIndex(["2011-01", "2011-02", "NaT", "2011-04"], freq="M")
|
88 |
+
result = idx.asfreq(freq="Q")
|
89 |
+
expected = PeriodIndex(["2011Q1", "2011Q1", "NaT", "2011Q2"], freq="Q")
|
90 |
+
tm.assert_index_equal(result, expected)
|
91 |
+
|
92 |
+
@pytest.mark.parametrize("freq", ["D", "3D"])
|
93 |
+
def test_asfreq_mult_pi(self, freq):
|
94 |
+
pi = PeriodIndex(["2001-01", "2001-02", "NaT", "2001-03"], freq="2M")
|
95 |
+
|
96 |
+
result = pi.asfreq(freq)
|
97 |
+
exp = PeriodIndex(["2001-02-28", "2001-03-31", "NaT", "2001-04-30"], freq=freq)
|
98 |
+
tm.assert_index_equal(result, exp)
|
99 |
+
assert result.freq == exp.freq
|
100 |
+
|
101 |
+
result = pi.asfreq(freq, how="S")
|
102 |
+
exp = PeriodIndex(["2001-01-01", "2001-02-01", "NaT", "2001-03-01"], freq=freq)
|
103 |
+
tm.assert_index_equal(result, exp)
|
104 |
+
assert result.freq == exp.freq
|
105 |
+
|
106 |
+
def test_asfreq_combined_pi(self):
|
107 |
+
pi = PeriodIndex(["2001-01-01 00:00", "2001-01-02 02:00", "NaT"], freq="h")
|
108 |
+
exp = PeriodIndex(["2001-01-01 00:00", "2001-01-02 02:00", "NaT"], freq="25h")
|
109 |
+
for freq, how in zip(["1D1h", "1h1D"], ["S", "E"]):
|
110 |
+
result = pi.asfreq(freq, how=how)
|
111 |
+
tm.assert_index_equal(result, exp)
|
112 |
+
assert result.freq == exp.freq
|
113 |
+
|
114 |
+
for freq in ["1D1h", "1h1D"]:
|
115 |
+
pi = PeriodIndex(["2001-01-01 00:00", "2001-01-02 02:00", "NaT"], freq=freq)
|
116 |
+
result = pi.asfreq("h")
|
117 |
+
exp = PeriodIndex(["2001-01-02 00:00", "2001-01-03 02:00", "NaT"], freq="h")
|
118 |
+
tm.assert_index_equal(result, exp)
|
119 |
+
assert result.freq == exp.freq
|
120 |
+
|
121 |
+
pi = PeriodIndex(["2001-01-01 00:00", "2001-01-02 02:00", "NaT"], freq=freq)
|
122 |
+
result = pi.asfreq("h", how="S")
|
123 |
+
exp = PeriodIndex(["2001-01-01 00:00", "2001-01-02 02:00", "NaT"], freq="h")
|
124 |
+
tm.assert_index_equal(result, exp)
|
125 |
+
assert result.freq == exp.freq
|
126 |
+
|
127 |
+
def test_astype_asfreq(self):
|
128 |
+
pi1 = PeriodIndex(["2011-01-01", "2011-02-01", "2011-03-01"], freq="D")
|
129 |
+
exp = PeriodIndex(["2011-01", "2011-02", "2011-03"], freq="M")
|
130 |
+
tm.assert_index_equal(pi1.asfreq("M"), exp)
|
131 |
+
tm.assert_index_equal(pi1.astype("period[M]"), exp)
|
132 |
+
|
133 |
+
exp = PeriodIndex(["2011-01", "2011-02", "2011-03"], freq="3M")
|
134 |
+
tm.assert_index_equal(pi1.asfreq("3M"), exp)
|
135 |
+
tm.assert_index_equal(pi1.astype("period[3M]"), exp)
|
136 |
+
|
137 |
+
def test_asfreq_with_different_n(self):
|
138 |
+
ser = Series([1, 2], index=PeriodIndex(["2020-01", "2020-03"], freq="2M"))
|
139 |
+
result = ser.asfreq("M")
|
140 |
+
|
141 |
+
excepted = Series([1, 2], index=PeriodIndex(["2020-02", "2020-04"], freq="M"))
|
142 |
+
tm.assert_series_equal(result, excepted)
|
143 |
+
|
144 |
+
@pytest.mark.parametrize(
|
145 |
+
"freq",
|
146 |
+
[
|
147 |
+
"2BMS",
|
148 |
+
"2YS-MAR",
|
149 |
+
"2bh",
|
150 |
+
],
|
151 |
+
)
|
152 |
+
def test_pi_asfreq_not_supported_frequency(self, freq):
|
153 |
+
# GH#55785
|
154 |
+
msg = f"{freq[1:]} is not supported as period frequency"
|
155 |
+
|
156 |
+
pi = PeriodIndex(["2020-01-01", "2021-01-01"], freq="M")
|
157 |
+
with pytest.raises(ValueError, match=msg):
|
158 |
+
pi.asfreq(freq=freq)
|
159 |
+
|
160 |
+
@pytest.mark.parametrize(
|
161 |
+
"freq",
|
162 |
+
[
|
163 |
+
"2BME",
|
164 |
+
"2YE-MAR",
|
165 |
+
"2QE",
|
166 |
+
],
|
167 |
+
)
|
168 |
+
def test_pi_asfreq_invalid_frequency(self, freq):
|
169 |
+
# GH#55785
|
170 |
+
msg = f"Invalid frequency: {freq}"
|
171 |
+
|
172 |
+
pi = PeriodIndex(["2020-01-01", "2021-01-01"], freq="M")
|
173 |
+
with pytest.raises(ValueError, match=msg):
|
174 |
+
pi.asfreq(freq=freq)
|
175 |
+
|
176 |
+
@pytest.mark.parametrize(
|
177 |
+
"freq",
|
178 |
+
[
|
179 |
+
offsets.MonthBegin(2),
|
180 |
+
offsets.BusinessMonthEnd(2),
|
181 |
+
],
|
182 |
+
)
|
183 |
+
def test_pi_asfreq_invalid_baseoffset(self, freq):
|
184 |
+
# GH#56945
|
185 |
+
msg = re.escape(f"{freq} is not supported as period frequency")
|
186 |
+
|
187 |
+
pi = PeriodIndex(["2020-01-01", "2021-01-01"], freq="M")
|
188 |
+
with pytest.raises(ValueError, match=msg):
|
189 |
+
pi.asfreq(freq=freq)
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/methods/test_factorize.py
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
|
3 |
+
from pandas import PeriodIndex
|
4 |
+
import pandas._testing as tm
|
5 |
+
|
6 |
+
|
7 |
+
class TestFactorize:
|
8 |
+
def test_factorize_period(self):
|
9 |
+
idx1 = PeriodIndex(
|
10 |
+
["2014-01", "2014-01", "2014-02", "2014-02", "2014-03", "2014-03"],
|
11 |
+
freq="M",
|
12 |
+
)
|
13 |
+
|
14 |
+
exp_arr = np.array([0, 0, 1, 1, 2, 2], dtype=np.intp)
|
15 |
+
exp_idx = PeriodIndex(["2014-01", "2014-02", "2014-03"], freq="M")
|
16 |
+
|
17 |
+
arr, idx = idx1.factorize()
|
18 |
+
tm.assert_numpy_array_equal(arr, exp_arr)
|
19 |
+
tm.assert_index_equal(idx, exp_idx)
|
20 |
+
|
21 |
+
arr, idx = idx1.factorize(sort=True)
|
22 |
+
tm.assert_numpy_array_equal(arr, exp_arr)
|
23 |
+
tm.assert_index_equal(idx, exp_idx)
|
24 |
+
|
25 |
+
def test_factorize_period_nonmonotonic(self):
|
26 |
+
idx2 = PeriodIndex(
|
27 |
+
["2014-03", "2014-03", "2014-02", "2014-01", "2014-03", "2014-01"],
|
28 |
+
freq="M",
|
29 |
+
)
|
30 |
+
exp_idx = PeriodIndex(["2014-01", "2014-02", "2014-03"], freq="M")
|
31 |
+
|
32 |
+
exp_arr = np.array([2, 2, 1, 0, 2, 0], dtype=np.intp)
|
33 |
+
arr, idx = idx2.factorize(sort=True)
|
34 |
+
tm.assert_numpy_array_equal(arr, exp_arr)
|
35 |
+
tm.assert_index_equal(idx, exp_idx)
|
36 |
+
|
37 |
+
exp_arr = np.array([0, 0, 1, 2, 0, 2], dtype=np.intp)
|
38 |
+
exp_idx = PeriodIndex(["2014-03", "2014-02", "2014-01"], freq="M")
|
39 |
+
arr, idx = idx2.factorize()
|
40 |
+
tm.assert_numpy_array_equal(arr, exp_arr)
|
41 |
+
tm.assert_index_equal(idx, exp_idx)
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/methods/test_insert.py
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas import (
|
5 |
+
NaT,
|
6 |
+
PeriodIndex,
|
7 |
+
period_range,
|
8 |
+
)
|
9 |
+
import pandas._testing as tm
|
10 |
+
|
11 |
+
|
12 |
+
class TestInsert:
|
13 |
+
@pytest.mark.parametrize("na", [np.nan, NaT, None])
|
14 |
+
def test_insert(self, na):
|
15 |
+
# GH#18295 (test missing)
|
16 |
+
expected = PeriodIndex(["2017Q1", NaT, "2017Q2", "2017Q3", "2017Q4"], freq="Q")
|
17 |
+
result = period_range("2017Q1", periods=4, freq="Q").insert(1, na)
|
18 |
+
tm.assert_index_equal(result, expected)
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/methods/test_is_full.py
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
from pandas import PeriodIndex
|
4 |
+
|
5 |
+
|
6 |
+
def test_is_full():
|
7 |
+
index = PeriodIndex([2005, 2007, 2009], freq="Y")
|
8 |
+
assert not index.is_full
|
9 |
+
|
10 |
+
index = PeriodIndex([2005, 2006, 2007], freq="Y")
|
11 |
+
assert index.is_full
|
12 |
+
|
13 |
+
index = PeriodIndex([2005, 2005, 2007], freq="Y")
|
14 |
+
assert not index.is_full
|
15 |
+
|
16 |
+
index = PeriodIndex([2005, 2005, 2006], freq="Y")
|
17 |
+
assert index.is_full
|
18 |
+
|
19 |
+
index = PeriodIndex([2006, 2005, 2005], freq="Y")
|
20 |
+
with pytest.raises(ValueError, match="Index is not monotonic"):
|
21 |
+
index.is_full
|
22 |
+
|
23 |
+
assert index[:0].is_full
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/methods/test_repeat.py
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas import (
|
5 |
+
PeriodIndex,
|
6 |
+
period_range,
|
7 |
+
)
|
8 |
+
import pandas._testing as tm
|
9 |
+
|
10 |
+
|
11 |
+
class TestRepeat:
|
12 |
+
@pytest.mark.parametrize("use_numpy", [True, False])
|
13 |
+
@pytest.mark.parametrize(
|
14 |
+
"index",
|
15 |
+
[
|
16 |
+
period_range("2000-01-01", periods=3, freq="D"),
|
17 |
+
period_range("2001-01-01", periods=3, freq="2D"),
|
18 |
+
PeriodIndex(["2001-01", "NaT", "2003-01"], freq="M"),
|
19 |
+
],
|
20 |
+
)
|
21 |
+
def test_repeat_freqstr(self, index, use_numpy):
|
22 |
+
# GH#10183
|
23 |
+
expected = PeriodIndex([per for per in index for _ in range(3)])
|
24 |
+
result = np.repeat(index, 3) if use_numpy else index.repeat(3)
|
25 |
+
tm.assert_index_equal(result, expected)
|
26 |
+
assert result.freqstr == index.freqstr
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/methods/test_to_timestamp.py
ADDED
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from datetime import datetime
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
import pytest
|
5 |
+
|
6 |
+
from pandas import (
|
7 |
+
DatetimeIndex,
|
8 |
+
NaT,
|
9 |
+
PeriodIndex,
|
10 |
+
Timedelta,
|
11 |
+
Timestamp,
|
12 |
+
date_range,
|
13 |
+
period_range,
|
14 |
+
)
|
15 |
+
import pandas._testing as tm
|
16 |
+
|
17 |
+
|
18 |
+
class TestToTimestamp:
|
19 |
+
def test_to_timestamp_non_contiguous(self):
|
20 |
+
# GH#44100
|
21 |
+
dti = date_range("2021-10-18", periods=9, freq="D")
|
22 |
+
pi = dti.to_period()
|
23 |
+
|
24 |
+
result = pi[::2].to_timestamp()
|
25 |
+
expected = dti[::2]
|
26 |
+
tm.assert_index_equal(result, expected)
|
27 |
+
|
28 |
+
result = pi._data[::2].to_timestamp()
|
29 |
+
expected = dti._data[::2]
|
30 |
+
# TODO: can we get the freq to round-trip?
|
31 |
+
tm.assert_datetime_array_equal(result, expected, check_freq=False)
|
32 |
+
|
33 |
+
result = pi[::-1].to_timestamp()
|
34 |
+
expected = dti[::-1]
|
35 |
+
tm.assert_index_equal(result, expected)
|
36 |
+
|
37 |
+
result = pi._data[::-1].to_timestamp()
|
38 |
+
expected = dti._data[::-1]
|
39 |
+
tm.assert_datetime_array_equal(result, expected, check_freq=False)
|
40 |
+
|
41 |
+
result = pi[::2][::-1].to_timestamp()
|
42 |
+
expected = dti[::2][::-1]
|
43 |
+
tm.assert_index_equal(result, expected)
|
44 |
+
|
45 |
+
result = pi._data[::2][::-1].to_timestamp()
|
46 |
+
expected = dti._data[::2][::-1]
|
47 |
+
tm.assert_datetime_array_equal(result, expected, check_freq=False)
|
48 |
+
|
49 |
+
def test_to_timestamp_freq(self):
|
50 |
+
idx = period_range("2017", periods=12, freq="Y-DEC")
|
51 |
+
result = idx.to_timestamp()
|
52 |
+
expected = date_range("2017", periods=12, freq="YS-JAN")
|
53 |
+
tm.assert_index_equal(result, expected)
|
54 |
+
|
55 |
+
def test_to_timestamp_pi_nat(self):
|
56 |
+
# GH#7228
|
57 |
+
index = PeriodIndex(["NaT", "2011-01", "2011-02"], freq="M", name="idx")
|
58 |
+
|
59 |
+
result = index.to_timestamp("D")
|
60 |
+
expected = DatetimeIndex(
|
61 |
+
[NaT, datetime(2011, 1, 1), datetime(2011, 2, 1)],
|
62 |
+
dtype="M8[ns]",
|
63 |
+
name="idx",
|
64 |
+
)
|
65 |
+
tm.assert_index_equal(result, expected)
|
66 |
+
assert result.name == "idx"
|
67 |
+
|
68 |
+
result2 = result.to_period(freq="M")
|
69 |
+
tm.assert_index_equal(result2, index)
|
70 |
+
assert result2.name == "idx"
|
71 |
+
|
72 |
+
result3 = result.to_period(freq="3M")
|
73 |
+
exp = PeriodIndex(["NaT", "2011-01", "2011-02"], freq="3M", name="idx")
|
74 |
+
tm.assert_index_equal(result3, exp)
|
75 |
+
assert result3.freqstr == "3M"
|
76 |
+
|
77 |
+
msg = "Frequency must be positive, because it represents span: -2Y"
|
78 |
+
with pytest.raises(ValueError, match=msg):
|
79 |
+
result.to_period(freq="-2Y")
|
80 |
+
|
81 |
+
def test_to_timestamp_preserve_name(self):
|
82 |
+
index = period_range(freq="Y", start="1/1/2001", end="12/1/2009", name="foo")
|
83 |
+
assert index.name == "foo"
|
84 |
+
|
85 |
+
conv = index.to_timestamp("D")
|
86 |
+
assert conv.name == "foo"
|
87 |
+
|
88 |
+
def test_to_timestamp_quarterly_bug(self):
|
89 |
+
years = np.arange(1960, 2000).repeat(4)
|
90 |
+
quarters = np.tile(list(range(1, 5)), 40)
|
91 |
+
|
92 |
+
pindex = PeriodIndex.from_fields(year=years, quarter=quarters)
|
93 |
+
|
94 |
+
stamps = pindex.to_timestamp("D", "end")
|
95 |
+
expected = DatetimeIndex([x.to_timestamp("D", "end") for x in pindex])
|
96 |
+
tm.assert_index_equal(stamps, expected)
|
97 |
+
assert stamps.freq == expected.freq
|
98 |
+
|
99 |
+
def test_to_timestamp_pi_mult(self):
|
100 |
+
idx = PeriodIndex(["2011-01", "NaT", "2011-02"], freq="2M", name="idx")
|
101 |
+
|
102 |
+
result = idx.to_timestamp()
|
103 |
+
expected = DatetimeIndex(
|
104 |
+
["2011-01-01", "NaT", "2011-02-01"], dtype="M8[ns]", name="idx"
|
105 |
+
)
|
106 |
+
tm.assert_index_equal(result, expected)
|
107 |
+
|
108 |
+
result = idx.to_timestamp(how="E")
|
109 |
+
expected = DatetimeIndex(
|
110 |
+
["2011-02-28", "NaT", "2011-03-31"], dtype="M8[ns]", name="idx"
|
111 |
+
)
|
112 |
+
expected = expected + Timedelta(1, "D") - Timedelta(1, "ns")
|
113 |
+
tm.assert_index_equal(result, expected)
|
114 |
+
|
115 |
+
def test_to_timestamp_pi_combined(self):
|
116 |
+
idx = period_range(start="2011", periods=2, freq="1D1h", name="idx")
|
117 |
+
|
118 |
+
result = idx.to_timestamp()
|
119 |
+
expected = DatetimeIndex(
|
120 |
+
["2011-01-01 00:00", "2011-01-02 01:00"], dtype="M8[ns]", name="idx"
|
121 |
+
)
|
122 |
+
tm.assert_index_equal(result, expected)
|
123 |
+
|
124 |
+
result = idx.to_timestamp(how="E")
|
125 |
+
expected = DatetimeIndex(
|
126 |
+
["2011-01-02 00:59:59", "2011-01-03 01:59:59"], name="idx", dtype="M8[ns]"
|
127 |
+
)
|
128 |
+
expected = expected + Timedelta(1, "s") - Timedelta(1, "ns")
|
129 |
+
tm.assert_index_equal(result, expected)
|
130 |
+
|
131 |
+
result = idx.to_timestamp(how="E", freq="h")
|
132 |
+
expected = DatetimeIndex(
|
133 |
+
["2011-01-02 00:00", "2011-01-03 01:00"], dtype="M8[ns]", name="idx"
|
134 |
+
)
|
135 |
+
expected = expected + Timedelta(1, "h") - Timedelta(1, "ns")
|
136 |
+
tm.assert_index_equal(result, expected)
|
137 |
+
|
138 |
+
def test_to_timestamp_1703(self):
|
139 |
+
index = period_range("1/1/2012", periods=4, freq="D")
|
140 |
+
|
141 |
+
result = index.to_timestamp()
|
142 |
+
assert result[0] == Timestamp("1/1/2012")
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/test_indexing.py
ADDED
@@ -0,0 +1,815 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from datetime import datetime
|
2 |
+
import re
|
3 |
+
|
4 |
+
import numpy as np
|
5 |
+
import pytest
|
6 |
+
|
7 |
+
from pandas._libs.tslibs import period as libperiod
|
8 |
+
from pandas.errors import InvalidIndexError
|
9 |
+
|
10 |
+
import pandas as pd
|
11 |
+
from pandas import (
|
12 |
+
DatetimeIndex,
|
13 |
+
NaT,
|
14 |
+
Period,
|
15 |
+
PeriodIndex,
|
16 |
+
Series,
|
17 |
+
Timedelta,
|
18 |
+
date_range,
|
19 |
+
notna,
|
20 |
+
period_range,
|
21 |
+
)
|
22 |
+
import pandas._testing as tm
|
23 |
+
|
24 |
+
dti4 = date_range("2016-01-01", periods=4)
|
25 |
+
dti = dti4[:-1]
|
26 |
+
rng = pd.Index(range(3))
|
27 |
+
|
28 |
+
|
29 |
+
@pytest.fixture(
|
30 |
+
params=[
|
31 |
+
dti,
|
32 |
+
dti.tz_localize("UTC"),
|
33 |
+
dti.to_period("W"),
|
34 |
+
dti - dti[0],
|
35 |
+
rng,
|
36 |
+
pd.Index([1, 2, 3]),
|
37 |
+
pd.Index([2.0, 3.0, 4.0]),
|
38 |
+
pd.Index([4, 5, 6], dtype="u8"),
|
39 |
+
pd.IntervalIndex.from_breaks(dti4),
|
40 |
+
]
|
41 |
+
)
|
42 |
+
def non_comparable_idx(request):
|
43 |
+
# All have length 3
|
44 |
+
return request.param
|
45 |
+
|
46 |
+
|
47 |
+
class TestGetItem:
|
48 |
+
def test_getitem_slice_keeps_name(self):
|
49 |
+
idx = period_range("20010101", periods=10, freq="D", name="bob")
|
50 |
+
assert idx.name == idx[1:].name
|
51 |
+
|
52 |
+
def test_getitem(self):
|
53 |
+
idx1 = period_range("2011-01-01", "2011-01-31", freq="D", name="idx")
|
54 |
+
|
55 |
+
for idx in [idx1]:
|
56 |
+
result = idx[0]
|
57 |
+
assert result == Period("2011-01-01", freq="D")
|
58 |
+
|
59 |
+
result = idx[-1]
|
60 |
+
assert result == Period("2011-01-31", freq="D")
|
61 |
+
|
62 |
+
result = idx[0:5]
|
63 |
+
expected = period_range("2011-01-01", "2011-01-05", freq="D", name="idx")
|
64 |
+
tm.assert_index_equal(result, expected)
|
65 |
+
assert result.freq == expected.freq
|
66 |
+
assert result.freq == "D"
|
67 |
+
|
68 |
+
result = idx[0:10:2]
|
69 |
+
expected = PeriodIndex(
|
70 |
+
["2011-01-01", "2011-01-03", "2011-01-05", "2011-01-07", "2011-01-09"],
|
71 |
+
freq="D",
|
72 |
+
name="idx",
|
73 |
+
)
|
74 |
+
tm.assert_index_equal(result, expected)
|
75 |
+
assert result.freq == expected.freq
|
76 |
+
assert result.freq == "D"
|
77 |
+
|
78 |
+
result = idx[-20:-5:3]
|
79 |
+
expected = PeriodIndex(
|
80 |
+
["2011-01-12", "2011-01-15", "2011-01-18", "2011-01-21", "2011-01-24"],
|
81 |
+
freq="D",
|
82 |
+
name="idx",
|
83 |
+
)
|
84 |
+
tm.assert_index_equal(result, expected)
|
85 |
+
assert result.freq == expected.freq
|
86 |
+
assert result.freq == "D"
|
87 |
+
|
88 |
+
result = idx[4::-1]
|
89 |
+
expected = PeriodIndex(
|
90 |
+
["2011-01-05", "2011-01-04", "2011-01-03", "2011-01-02", "2011-01-01"],
|
91 |
+
freq="D",
|
92 |
+
name="idx",
|
93 |
+
)
|
94 |
+
tm.assert_index_equal(result, expected)
|
95 |
+
assert result.freq == expected.freq
|
96 |
+
assert result.freq == "D"
|
97 |
+
|
98 |
+
def test_getitem_index(self):
|
99 |
+
idx = period_range("2007-01", periods=10, freq="M", name="x")
|
100 |
+
|
101 |
+
result = idx[[1, 3, 5]]
|
102 |
+
exp = PeriodIndex(["2007-02", "2007-04", "2007-06"], freq="M", name="x")
|
103 |
+
tm.assert_index_equal(result, exp)
|
104 |
+
|
105 |
+
result = idx[[True, True, False, False, False, True, True, False, False, False]]
|
106 |
+
exp = PeriodIndex(
|
107 |
+
["2007-01", "2007-02", "2007-06", "2007-07"], freq="M", name="x"
|
108 |
+
)
|
109 |
+
tm.assert_index_equal(result, exp)
|
110 |
+
|
111 |
+
def test_getitem_partial(self):
|
112 |
+
rng = period_range("2007-01", periods=50, freq="M")
|
113 |
+
ts = Series(np.random.default_rng(2).standard_normal(len(rng)), rng)
|
114 |
+
|
115 |
+
with pytest.raises(KeyError, match=r"^'2006'$"):
|
116 |
+
ts["2006"]
|
117 |
+
|
118 |
+
result = ts["2008"]
|
119 |
+
assert (result.index.year == 2008).all()
|
120 |
+
|
121 |
+
result = ts["2008":"2009"]
|
122 |
+
assert len(result) == 24
|
123 |
+
|
124 |
+
result = ts["2008-1":"2009-12"]
|
125 |
+
assert len(result) == 24
|
126 |
+
|
127 |
+
result = ts["2008Q1":"2009Q4"]
|
128 |
+
assert len(result) == 24
|
129 |
+
|
130 |
+
result = ts[:"2009"]
|
131 |
+
assert len(result) == 36
|
132 |
+
|
133 |
+
result = ts["2009":]
|
134 |
+
assert len(result) == 50 - 24
|
135 |
+
|
136 |
+
exp = result
|
137 |
+
result = ts[24:]
|
138 |
+
tm.assert_series_equal(exp, result)
|
139 |
+
|
140 |
+
ts = pd.concat([ts[10:], ts[10:]])
|
141 |
+
msg = "left slice bound for non-unique label: '2008'"
|
142 |
+
with pytest.raises(KeyError, match=msg):
|
143 |
+
ts[slice("2008", "2009")]
|
144 |
+
|
145 |
+
def test_getitem_datetime(self):
|
146 |
+
rng = period_range(start="2012-01-01", periods=10, freq="W-MON")
|
147 |
+
ts = Series(range(len(rng)), index=rng)
|
148 |
+
|
149 |
+
dt1 = datetime(2011, 10, 2)
|
150 |
+
dt4 = datetime(2012, 4, 20)
|
151 |
+
|
152 |
+
rs = ts[dt1:dt4]
|
153 |
+
tm.assert_series_equal(rs, ts)
|
154 |
+
|
155 |
+
def test_getitem_nat(self):
|
156 |
+
idx = PeriodIndex(["2011-01", "NaT", "2011-02"], freq="M")
|
157 |
+
assert idx[0] == Period("2011-01", freq="M")
|
158 |
+
assert idx[1] is NaT
|
159 |
+
|
160 |
+
s = Series([0, 1, 2], index=idx)
|
161 |
+
assert s[NaT] == 1
|
162 |
+
|
163 |
+
s = Series(idx, index=idx)
|
164 |
+
assert s[Period("2011-01", freq="M")] == Period("2011-01", freq="M")
|
165 |
+
assert s[NaT] is NaT
|
166 |
+
|
167 |
+
def test_getitem_list_periods(self):
|
168 |
+
# GH 7710
|
169 |
+
rng = period_range(start="2012-01-01", periods=10, freq="D")
|
170 |
+
ts = Series(range(len(rng)), index=rng)
|
171 |
+
exp = ts.iloc[[1]]
|
172 |
+
tm.assert_series_equal(ts[[Period("2012-01-02", freq="D")]], exp)
|
173 |
+
|
174 |
+
@pytest.mark.arm_slow
|
175 |
+
def test_getitem_seconds(self):
|
176 |
+
# GH#6716
|
177 |
+
didx = date_range(start="2013/01/01 09:00:00", freq="s", periods=4000)
|
178 |
+
pidx = period_range(start="2013/01/01 09:00:00", freq="s", periods=4000)
|
179 |
+
|
180 |
+
for idx in [didx, pidx]:
|
181 |
+
# getitem against index should raise ValueError
|
182 |
+
values = [
|
183 |
+
"2014",
|
184 |
+
"2013/02",
|
185 |
+
"2013/01/02",
|
186 |
+
"2013/02/01 9h",
|
187 |
+
"2013/02/01 09:00",
|
188 |
+
]
|
189 |
+
for val in values:
|
190 |
+
# GH7116
|
191 |
+
# these show deprecations as we are trying
|
192 |
+
# to slice with non-integer indexers
|
193 |
+
with pytest.raises(IndexError, match="only integers, slices"):
|
194 |
+
idx[val]
|
195 |
+
|
196 |
+
ser = Series(np.random.default_rng(2).random(len(idx)), index=idx)
|
197 |
+
tm.assert_series_equal(ser["2013/01/01 10:00"], ser[3600:3660])
|
198 |
+
tm.assert_series_equal(ser["2013/01/01 9h"], ser[:3600])
|
199 |
+
for d in ["2013/01/01", "2013/01", "2013"]:
|
200 |
+
tm.assert_series_equal(ser[d], ser)
|
201 |
+
|
202 |
+
@pytest.mark.parametrize(
|
203 |
+
"idx_range",
|
204 |
+
[
|
205 |
+
date_range,
|
206 |
+
period_range,
|
207 |
+
],
|
208 |
+
)
|
209 |
+
def test_getitem_day(self, idx_range):
|
210 |
+
# GH#6716
|
211 |
+
# Confirm DatetimeIndex and PeriodIndex works identically
|
212 |
+
# getitem against index should raise ValueError
|
213 |
+
idx = idx_range(start="2013/01/01", freq="D", periods=400)
|
214 |
+
values = [
|
215 |
+
"2014",
|
216 |
+
"2013/02",
|
217 |
+
"2013/01/02",
|
218 |
+
"2013/02/01 9h",
|
219 |
+
"2013/02/01 09:00",
|
220 |
+
]
|
221 |
+
for val in values:
|
222 |
+
# GH7116
|
223 |
+
# these show deprecations as we are trying
|
224 |
+
# to slice with non-integer indexers
|
225 |
+
with pytest.raises(IndexError, match="only integers, slices"):
|
226 |
+
idx[val]
|
227 |
+
|
228 |
+
ser = Series(np.random.default_rng(2).random(len(idx)), index=idx)
|
229 |
+
tm.assert_series_equal(ser["2013/01"], ser[0:31])
|
230 |
+
tm.assert_series_equal(ser["2013/02"], ser[31:59])
|
231 |
+
tm.assert_series_equal(ser["2014"], ser[365:])
|
232 |
+
|
233 |
+
invalid = ["2013/02/01 9h", "2013/02/01 09:00"]
|
234 |
+
for val in invalid:
|
235 |
+
with pytest.raises(KeyError, match=val):
|
236 |
+
ser[val]
|
237 |
+
|
238 |
+
|
239 |
+
class TestGetLoc:
|
240 |
+
def test_get_loc_msg(self):
|
241 |
+
idx = period_range("2000-1-1", freq="Y", periods=10)
|
242 |
+
bad_period = Period("2012", "Y")
|
243 |
+
with pytest.raises(KeyError, match=r"^Period\('2012', 'Y-DEC'\)$"):
|
244 |
+
idx.get_loc(bad_period)
|
245 |
+
|
246 |
+
try:
|
247 |
+
idx.get_loc(bad_period)
|
248 |
+
except KeyError as inst:
|
249 |
+
assert inst.args[0] == bad_period
|
250 |
+
|
251 |
+
def test_get_loc_nat(self):
|
252 |
+
didx = DatetimeIndex(["2011-01-01", "NaT", "2011-01-03"])
|
253 |
+
pidx = PeriodIndex(["2011-01-01", "NaT", "2011-01-03"], freq="M")
|
254 |
+
|
255 |
+
# check DatetimeIndex compat
|
256 |
+
for idx in [didx, pidx]:
|
257 |
+
assert idx.get_loc(NaT) == 1
|
258 |
+
assert idx.get_loc(None) == 1
|
259 |
+
assert idx.get_loc(float("nan")) == 1
|
260 |
+
assert idx.get_loc(np.nan) == 1
|
261 |
+
|
262 |
+
def test_get_loc(self):
|
263 |
+
# GH 17717
|
264 |
+
p0 = Period("2017-09-01")
|
265 |
+
p1 = Period("2017-09-02")
|
266 |
+
p2 = Period("2017-09-03")
|
267 |
+
|
268 |
+
# get the location of p1/p2 from
|
269 |
+
# monotonic increasing PeriodIndex with non-duplicate
|
270 |
+
idx0 = PeriodIndex([p0, p1, p2])
|
271 |
+
expected_idx1_p1 = 1
|
272 |
+
expected_idx1_p2 = 2
|
273 |
+
|
274 |
+
assert idx0.get_loc(p1) == expected_idx1_p1
|
275 |
+
assert idx0.get_loc(str(p1)) == expected_idx1_p1
|
276 |
+
assert idx0.get_loc(p2) == expected_idx1_p2
|
277 |
+
assert idx0.get_loc(str(p2)) == expected_idx1_p2
|
278 |
+
|
279 |
+
msg = "Cannot interpret 'foo' as period"
|
280 |
+
with pytest.raises(KeyError, match=msg):
|
281 |
+
idx0.get_loc("foo")
|
282 |
+
with pytest.raises(KeyError, match=r"^1\.1$"):
|
283 |
+
idx0.get_loc(1.1)
|
284 |
+
|
285 |
+
with pytest.raises(InvalidIndexError, match=re.escape(str(idx0))):
|
286 |
+
idx0.get_loc(idx0)
|
287 |
+
|
288 |
+
# get the location of p1/p2 from
|
289 |
+
# monotonic increasing PeriodIndex with duplicate
|
290 |
+
idx1 = PeriodIndex([p1, p1, p2])
|
291 |
+
expected_idx1_p1 = slice(0, 2)
|
292 |
+
expected_idx1_p2 = 2
|
293 |
+
|
294 |
+
assert idx1.get_loc(p1) == expected_idx1_p1
|
295 |
+
assert idx1.get_loc(str(p1)) == expected_idx1_p1
|
296 |
+
assert idx1.get_loc(p2) == expected_idx1_p2
|
297 |
+
assert idx1.get_loc(str(p2)) == expected_idx1_p2
|
298 |
+
|
299 |
+
msg = "Cannot interpret 'foo' as period"
|
300 |
+
with pytest.raises(KeyError, match=msg):
|
301 |
+
idx1.get_loc("foo")
|
302 |
+
|
303 |
+
with pytest.raises(KeyError, match=r"^1\.1$"):
|
304 |
+
idx1.get_loc(1.1)
|
305 |
+
|
306 |
+
with pytest.raises(InvalidIndexError, match=re.escape(str(idx1))):
|
307 |
+
idx1.get_loc(idx1)
|
308 |
+
|
309 |
+
# get the location of p1/p2 from
|
310 |
+
# non-monotonic increasing/decreasing PeriodIndex with duplicate
|
311 |
+
idx2 = PeriodIndex([p2, p1, p2])
|
312 |
+
expected_idx2_p1 = 1
|
313 |
+
expected_idx2_p2 = np.array([True, False, True])
|
314 |
+
|
315 |
+
assert idx2.get_loc(p1) == expected_idx2_p1
|
316 |
+
assert idx2.get_loc(str(p1)) == expected_idx2_p1
|
317 |
+
tm.assert_numpy_array_equal(idx2.get_loc(p2), expected_idx2_p2)
|
318 |
+
tm.assert_numpy_array_equal(idx2.get_loc(str(p2)), expected_idx2_p2)
|
319 |
+
|
320 |
+
def test_get_loc_integer(self):
|
321 |
+
dti = date_range("2016-01-01", periods=3)
|
322 |
+
pi = dti.to_period("D")
|
323 |
+
with pytest.raises(KeyError, match="16801"):
|
324 |
+
pi.get_loc(16801)
|
325 |
+
|
326 |
+
pi2 = dti.to_period("Y") # duplicates, ordinals are all 46
|
327 |
+
with pytest.raises(KeyError, match="46"):
|
328 |
+
pi2.get_loc(46)
|
329 |
+
|
330 |
+
def test_get_loc_invalid_string_raises_keyerror(self):
|
331 |
+
# GH#34240
|
332 |
+
pi = period_range("2000", periods=3, name="A")
|
333 |
+
with pytest.raises(KeyError, match="A"):
|
334 |
+
pi.get_loc("A")
|
335 |
+
|
336 |
+
ser = Series([1, 2, 3], index=pi)
|
337 |
+
with pytest.raises(KeyError, match="A"):
|
338 |
+
ser.loc["A"]
|
339 |
+
|
340 |
+
with pytest.raises(KeyError, match="A"):
|
341 |
+
ser["A"]
|
342 |
+
|
343 |
+
assert "A" not in ser
|
344 |
+
assert "A" not in pi
|
345 |
+
|
346 |
+
def test_get_loc_mismatched_freq(self):
|
347 |
+
# see also test_get_indexer_mismatched_dtype testing we get analogous
|
348 |
+
# behavior for get_loc
|
349 |
+
dti = date_range("2016-01-01", periods=3)
|
350 |
+
pi = dti.to_period("D")
|
351 |
+
pi2 = dti.to_period("W")
|
352 |
+
pi3 = pi.view(pi2.dtype) # i.e. matching i8 representations
|
353 |
+
|
354 |
+
with pytest.raises(KeyError, match="W-SUN"):
|
355 |
+
pi.get_loc(pi2[0])
|
356 |
+
|
357 |
+
with pytest.raises(KeyError, match="W-SUN"):
|
358 |
+
# even though we have matching i8 values
|
359 |
+
pi.get_loc(pi3[0])
|
360 |
+
|
361 |
+
|
362 |
+
class TestGetIndexer:
|
363 |
+
def test_get_indexer(self):
|
364 |
+
# GH 17717
|
365 |
+
p1 = Period("2017-09-01")
|
366 |
+
p2 = Period("2017-09-04")
|
367 |
+
p3 = Period("2017-09-07")
|
368 |
+
|
369 |
+
tp0 = Period("2017-08-31")
|
370 |
+
tp1 = Period("2017-09-02")
|
371 |
+
tp2 = Period("2017-09-05")
|
372 |
+
tp3 = Period("2017-09-09")
|
373 |
+
|
374 |
+
idx = PeriodIndex([p1, p2, p3])
|
375 |
+
|
376 |
+
tm.assert_numpy_array_equal(
|
377 |
+
idx.get_indexer(idx), np.array([0, 1, 2], dtype=np.intp)
|
378 |
+
)
|
379 |
+
|
380 |
+
target = PeriodIndex([tp0, tp1, tp2, tp3])
|
381 |
+
tm.assert_numpy_array_equal(
|
382 |
+
idx.get_indexer(target, "pad"), np.array([-1, 0, 1, 2], dtype=np.intp)
|
383 |
+
)
|
384 |
+
tm.assert_numpy_array_equal(
|
385 |
+
idx.get_indexer(target, "backfill"), np.array([0, 1, 2, -1], dtype=np.intp)
|
386 |
+
)
|
387 |
+
tm.assert_numpy_array_equal(
|
388 |
+
idx.get_indexer(target, "nearest"), np.array([0, 0, 1, 2], dtype=np.intp)
|
389 |
+
)
|
390 |
+
|
391 |
+
res = idx.get_indexer(target, "nearest", tolerance=Timedelta("1 day"))
|
392 |
+
tm.assert_numpy_array_equal(res, np.array([0, 0, 1, -1], dtype=np.intp))
|
393 |
+
|
394 |
+
def test_get_indexer_mismatched_dtype(self):
|
395 |
+
# Check that we return all -1s and do not raise or cast incorrectly
|
396 |
+
|
397 |
+
dti = date_range("2016-01-01", periods=3)
|
398 |
+
pi = dti.to_period("D")
|
399 |
+
pi2 = dti.to_period("W")
|
400 |
+
|
401 |
+
expected = np.array([-1, -1, -1], dtype=np.intp)
|
402 |
+
|
403 |
+
result = pi.get_indexer(dti)
|
404 |
+
tm.assert_numpy_array_equal(result, expected)
|
405 |
+
|
406 |
+
# This should work in both directions
|
407 |
+
result = dti.get_indexer(pi)
|
408 |
+
tm.assert_numpy_array_equal(result, expected)
|
409 |
+
|
410 |
+
result = pi.get_indexer(pi2)
|
411 |
+
tm.assert_numpy_array_equal(result, expected)
|
412 |
+
|
413 |
+
# We expect the same from get_indexer_non_unique
|
414 |
+
result = pi.get_indexer_non_unique(dti)[0]
|
415 |
+
tm.assert_numpy_array_equal(result, expected)
|
416 |
+
|
417 |
+
result = dti.get_indexer_non_unique(pi)[0]
|
418 |
+
tm.assert_numpy_array_equal(result, expected)
|
419 |
+
|
420 |
+
result = pi.get_indexer_non_unique(pi2)[0]
|
421 |
+
tm.assert_numpy_array_equal(result, expected)
|
422 |
+
|
423 |
+
def test_get_indexer_mismatched_dtype_different_length(self, non_comparable_idx):
|
424 |
+
# without method we aren't checking inequalities, so get all-missing
|
425 |
+
# but do not raise
|
426 |
+
dti = date_range("2016-01-01", periods=3)
|
427 |
+
pi = dti.to_period("D")
|
428 |
+
|
429 |
+
other = non_comparable_idx
|
430 |
+
|
431 |
+
res = pi[:-1].get_indexer(other)
|
432 |
+
expected = -np.ones(other.shape, dtype=np.intp)
|
433 |
+
tm.assert_numpy_array_equal(res, expected)
|
434 |
+
|
435 |
+
@pytest.mark.parametrize("method", ["pad", "backfill", "nearest"])
|
436 |
+
def test_get_indexer_mismatched_dtype_with_method(self, non_comparable_idx, method):
|
437 |
+
dti = date_range("2016-01-01", periods=3)
|
438 |
+
pi = dti.to_period("D")
|
439 |
+
|
440 |
+
other = non_comparable_idx
|
441 |
+
|
442 |
+
msg = re.escape(f"Cannot compare dtypes {pi.dtype} and {other.dtype}")
|
443 |
+
with pytest.raises(TypeError, match=msg):
|
444 |
+
pi.get_indexer(other, method=method)
|
445 |
+
|
446 |
+
for dtype in ["object", "category"]:
|
447 |
+
other2 = other.astype(dtype)
|
448 |
+
if dtype == "object" and isinstance(other, PeriodIndex):
|
449 |
+
continue
|
450 |
+
# Two different error message patterns depending on dtypes
|
451 |
+
msg = "|".join(
|
452 |
+
[
|
453 |
+
re.escape(msg)
|
454 |
+
for msg in (
|
455 |
+
f"Cannot compare dtypes {pi.dtype} and {other.dtype}",
|
456 |
+
" not supported between instances of ",
|
457 |
+
)
|
458 |
+
]
|
459 |
+
)
|
460 |
+
with pytest.raises(TypeError, match=msg):
|
461 |
+
pi.get_indexer(other2, method=method)
|
462 |
+
|
463 |
+
def test_get_indexer_non_unique(self):
|
464 |
+
# GH 17717
|
465 |
+
p1 = Period("2017-09-02")
|
466 |
+
p2 = Period("2017-09-03")
|
467 |
+
p3 = Period("2017-09-04")
|
468 |
+
p4 = Period("2017-09-05")
|
469 |
+
|
470 |
+
idx1 = PeriodIndex([p1, p2, p1])
|
471 |
+
idx2 = PeriodIndex([p2, p1, p3, p4])
|
472 |
+
|
473 |
+
result = idx1.get_indexer_non_unique(idx2)
|
474 |
+
expected_indexer = np.array([1, 0, 2, -1, -1], dtype=np.intp)
|
475 |
+
expected_missing = np.array([2, 3], dtype=np.intp)
|
476 |
+
|
477 |
+
tm.assert_numpy_array_equal(result[0], expected_indexer)
|
478 |
+
tm.assert_numpy_array_equal(result[1], expected_missing)
|
479 |
+
|
480 |
+
# TODO: This method came from test_period; de-dup with version above
|
481 |
+
def test_get_indexer2(self):
|
482 |
+
idx = period_range("2000-01-01", periods=3).asfreq("h", how="start")
|
483 |
+
tm.assert_numpy_array_equal(
|
484 |
+
idx.get_indexer(idx), np.array([0, 1, 2], dtype=np.intp)
|
485 |
+
)
|
486 |
+
|
487 |
+
target = PeriodIndex(
|
488 |
+
["1999-12-31T23", "2000-01-01T12", "2000-01-02T01"], freq="h"
|
489 |
+
)
|
490 |
+
tm.assert_numpy_array_equal(
|
491 |
+
idx.get_indexer(target, "pad"), np.array([-1, 0, 1], dtype=np.intp)
|
492 |
+
)
|
493 |
+
tm.assert_numpy_array_equal(
|
494 |
+
idx.get_indexer(target, "backfill"), np.array([0, 1, 2], dtype=np.intp)
|
495 |
+
)
|
496 |
+
tm.assert_numpy_array_equal(
|
497 |
+
idx.get_indexer(target, "nearest"), np.array([0, 1, 1], dtype=np.intp)
|
498 |
+
)
|
499 |
+
tm.assert_numpy_array_equal(
|
500 |
+
idx.get_indexer(target, "nearest", tolerance="1 hour"),
|
501 |
+
np.array([0, -1, 1], dtype=np.intp),
|
502 |
+
)
|
503 |
+
|
504 |
+
msg = "Input has different freq=None from PeriodArray\\(freq=h\\)"
|
505 |
+
with pytest.raises(ValueError, match=msg):
|
506 |
+
idx.get_indexer(target, "nearest", tolerance="1 minute")
|
507 |
+
|
508 |
+
tm.assert_numpy_array_equal(
|
509 |
+
idx.get_indexer(target, "nearest", tolerance="1 day"),
|
510 |
+
np.array([0, 1, 1], dtype=np.intp),
|
511 |
+
)
|
512 |
+
tol_raw = [
|
513 |
+
Timedelta("1 hour"),
|
514 |
+
Timedelta("1 hour"),
|
515 |
+
np.timedelta64(1, "D"),
|
516 |
+
]
|
517 |
+
tm.assert_numpy_array_equal(
|
518 |
+
idx.get_indexer(
|
519 |
+
target, "nearest", tolerance=[np.timedelta64(x) for x in tol_raw]
|
520 |
+
),
|
521 |
+
np.array([0, -1, 1], dtype=np.intp),
|
522 |
+
)
|
523 |
+
tol_bad = [
|
524 |
+
Timedelta("2 hour").to_timedelta64(),
|
525 |
+
Timedelta("1 hour").to_timedelta64(),
|
526 |
+
np.timedelta64(1, "M"),
|
527 |
+
]
|
528 |
+
with pytest.raises(
|
529 |
+
libperiod.IncompatibleFrequency, match="Input has different freq=None from"
|
530 |
+
):
|
531 |
+
idx.get_indexer(target, "nearest", tolerance=tol_bad)
|
532 |
+
|
533 |
+
|
534 |
+
class TestWhere:
|
535 |
+
def test_where(self, listlike_box):
|
536 |
+
i = period_range("20130101", periods=5, freq="D")
|
537 |
+
cond = [True] * len(i)
|
538 |
+
expected = i
|
539 |
+
result = i.where(listlike_box(cond))
|
540 |
+
tm.assert_index_equal(result, expected)
|
541 |
+
|
542 |
+
cond = [False] + [True] * (len(i) - 1)
|
543 |
+
expected = PeriodIndex([NaT] + i[1:].tolist(), freq="D")
|
544 |
+
result = i.where(listlike_box(cond))
|
545 |
+
tm.assert_index_equal(result, expected)
|
546 |
+
|
547 |
+
def test_where_other(self):
|
548 |
+
i = period_range("20130101", periods=5, freq="D")
|
549 |
+
for arr in [np.nan, NaT]:
|
550 |
+
result = i.where(notna(i), other=arr)
|
551 |
+
expected = i
|
552 |
+
tm.assert_index_equal(result, expected)
|
553 |
+
|
554 |
+
i2 = i.copy()
|
555 |
+
i2 = PeriodIndex([NaT, NaT] + i[2:].tolist(), freq="D")
|
556 |
+
result = i.where(notna(i2), i2)
|
557 |
+
tm.assert_index_equal(result, i2)
|
558 |
+
|
559 |
+
i2 = i.copy()
|
560 |
+
i2 = PeriodIndex([NaT, NaT] + i[2:].tolist(), freq="D")
|
561 |
+
result = i.where(notna(i2), i2.values)
|
562 |
+
tm.assert_index_equal(result, i2)
|
563 |
+
|
564 |
+
def test_where_invalid_dtypes(self):
|
565 |
+
pi = period_range("20130101", periods=5, freq="D")
|
566 |
+
|
567 |
+
tail = pi[2:].tolist()
|
568 |
+
i2 = PeriodIndex([NaT, NaT] + tail, freq="D")
|
569 |
+
mask = notna(i2)
|
570 |
+
|
571 |
+
result = pi.where(mask, i2.asi8)
|
572 |
+
expected = pd.Index([NaT._value, NaT._value] + tail, dtype=object)
|
573 |
+
assert isinstance(expected[0], int)
|
574 |
+
tm.assert_index_equal(result, expected)
|
575 |
+
|
576 |
+
tdi = i2.asi8.view("timedelta64[ns]")
|
577 |
+
expected = pd.Index([tdi[0], tdi[1]] + tail, dtype=object)
|
578 |
+
assert isinstance(expected[0], np.timedelta64)
|
579 |
+
result = pi.where(mask, tdi)
|
580 |
+
tm.assert_index_equal(result, expected)
|
581 |
+
|
582 |
+
dti = i2.to_timestamp("s")
|
583 |
+
expected = pd.Index([dti[0], dti[1]] + tail, dtype=object)
|
584 |
+
assert expected[0] is NaT
|
585 |
+
result = pi.where(mask, dti)
|
586 |
+
tm.assert_index_equal(result, expected)
|
587 |
+
|
588 |
+
td = Timedelta(days=4)
|
589 |
+
expected = pd.Index([td, td] + tail, dtype=object)
|
590 |
+
assert expected[0] == td
|
591 |
+
result = pi.where(mask, td)
|
592 |
+
tm.assert_index_equal(result, expected)
|
593 |
+
|
594 |
+
def test_where_mismatched_nat(self):
|
595 |
+
pi = period_range("20130101", periods=5, freq="D")
|
596 |
+
cond = np.array([True, False, True, True, False])
|
597 |
+
|
598 |
+
tdnat = np.timedelta64("NaT", "ns")
|
599 |
+
expected = pd.Index([pi[0], tdnat, pi[2], pi[3], tdnat], dtype=object)
|
600 |
+
assert expected[1] is tdnat
|
601 |
+
result = pi.where(cond, tdnat)
|
602 |
+
tm.assert_index_equal(result, expected)
|
603 |
+
|
604 |
+
|
605 |
+
class TestTake:
|
606 |
+
def test_take(self):
|
607 |
+
# GH#10295
|
608 |
+
idx1 = period_range("2011-01-01", "2011-01-31", freq="D", name="idx")
|
609 |
+
|
610 |
+
for idx in [idx1]:
|
611 |
+
result = idx.take([0])
|
612 |
+
assert result == Period("2011-01-01", freq="D")
|
613 |
+
|
614 |
+
result = idx.take([5])
|
615 |
+
assert result == Period("2011-01-06", freq="D")
|
616 |
+
|
617 |
+
result = idx.take([0, 1, 2])
|
618 |
+
expected = period_range("2011-01-01", "2011-01-03", freq="D", name="idx")
|
619 |
+
tm.assert_index_equal(result, expected)
|
620 |
+
assert result.freq == "D"
|
621 |
+
assert result.freq == expected.freq
|
622 |
+
|
623 |
+
result = idx.take([0, 2, 4])
|
624 |
+
expected = PeriodIndex(
|
625 |
+
["2011-01-01", "2011-01-03", "2011-01-05"], freq="D", name="idx"
|
626 |
+
)
|
627 |
+
tm.assert_index_equal(result, expected)
|
628 |
+
assert result.freq == expected.freq
|
629 |
+
assert result.freq == "D"
|
630 |
+
|
631 |
+
result = idx.take([7, 4, 1])
|
632 |
+
expected = PeriodIndex(
|
633 |
+
["2011-01-08", "2011-01-05", "2011-01-02"], freq="D", name="idx"
|
634 |
+
)
|
635 |
+
tm.assert_index_equal(result, expected)
|
636 |
+
assert result.freq == expected.freq
|
637 |
+
assert result.freq == "D"
|
638 |
+
|
639 |
+
result = idx.take([3, 2, 5])
|
640 |
+
expected = PeriodIndex(
|
641 |
+
["2011-01-04", "2011-01-03", "2011-01-06"], freq="D", name="idx"
|
642 |
+
)
|
643 |
+
tm.assert_index_equal(result, expected)
|
644 |
+
assert result.freq == expected.freq
|
645 |
+
assert result.freq == "D"
|
646 |
+
|
647 |
+
result = idx.take([-3, 2, 5])
|
648 |
+
expected = PeriodIndex(
|
649 |
+
["2011-01-29", "2011-01-03", "2011-01-06"], freq="D", name="idx"
|
650 |
+
)
|
651 |
+
tm.assert_index_equal(result, expected)
|
652 |
+
assert result.freq == expected.freq
|
653 |
+
assert result.freq == "D"
|
654 |
+
|
655 |
+
def test_take_misc(self):
|
656 |
+
index = period_range(start="1/1/10", end="12/31/12", freq="D", name="idx")
|
657 |
+
expected = PeriodIndex(
|
658 |
+
[
|
659 |
+
datetime(2010, 1, 6),
|
660 |
+
datetime(2010, 1, 7),
|
661 |
+
datetime(2010, 1, 9),
|
662 |
+
datetime(2010, 1, 13),
|
663 |
+
],
|
664 |
+
freq="D",
|
665 |
+
name="idx",
|
666 |
+
)
|
667 |
+
|
668 |
+
taken1 = index.take([5, 6, 8, 12])
|
669 |
+
taken2 = index[[5, 6, 8, 12]]
|
670 |
+
|
671 |
+
for taken in [taken1, taken2]:
|
672 |
+
tm.assert_index_equal(taken, expected)
|
673 |
+
assert isinstance(taken, PeriodIndex)
|
674 |
+
assert taken.freq == index.freq
|
675 |
+
assert taken.name == expected.name
|
676 |
+
|
677 |
+
def test_take_fill_value(self):
|
678 |
+
# GH#12631
|
679 |
+
idx = PeriodIndex(
|
680 |
+
["2011-01-01", "2011-02-01", "2011-03-01"], name="xxx", freq="D"
|
681 |
+
)
|
682 |
+
result = idx.take(np.array([1, 0, -1]))
|
683 |
+
expected = PeriodIndex(
|
684 |
+
["2011-02-01", "2011-01-01", "2011-03-01"], name="xxx", freq="D"
|
685 |
+
)
|
686 |
+
tm.assert_index_equal(result, expected)
|
687 |
+
|
688 |
+
# fill_value
|
689 |
+
result = idx.take(np.array([1, 0, -1]), fill_value=True)
|
690 |
+
expected = PeriodIndex(
|
691 |
+
["2011-02-01", "2011-01-01", "NaT"], name="xxx", freq="D"
|
692 |
+
)
|
693 |
+
tm.assert_index_equal(result, expected)
|
694 |
+
|
695 |
+
# allow_fill=False
|
696 |
+
result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True)
|
697 |
+
expected = PeriodIndex(
|
698 |
+
["2011-02-01", "2011-01-01", "2011-03-01"], name="xxx", freq="D"
|
699 |
+
)
|
700 |
+
tm.assert_index_equal(result, expected)
|
701 |
+
|
702 |
+
msg = (
|
703 |
+
"When allow_fill=True and fill_value is not None, "
|
704 |
+
"all indices must be >= -1"
|
705 |
+
)
|
706 |
+
with pytest.raises(ValueError, match=msg):
|
707 |
+
idx.take(np.array([1, 0, -2]), fill_value=True)
|
708 |
+
with pytest.raises(ValueError, match=msg):
|
709 |
+
idx.take(np.array([1, 0, -5]), fill_value=True)
|
710 |
+
|
711 |
+
msg = "index -5 is out of bounds for( axis 0 with)? size 3"
|
712 |
+
with pytest.raises(IndexError, match=msg):
|
713 |
+
idx.take(np.array([1, -5]))
|
714 |
+
|
715 |
+
|
716 |
+
class TestGetValue:
|
717 |
+
@pytest.mark.parametrize("freq", ["h", "D"])
|
718 |
+
def test_get_value_datetime_hourly(self, freq):
|
719 |
+
# get_loc and get_value should treat datetime objects symmetrically
|
720 |
+
# TODO: this test used to test get_value, which is removed in 2.0.
|
721 |
+
# should this test be moved somewhere, or is what's left redundant?
|
722 |
+
dti = date_range("2016-01-01", periods=3, freq="MS")
|
723 |
+
pi = dti.to_period(freq)
|
724 |
+
ser = Series(range(7, 10), index=pi)
|
725 |
+
|
726 |
+
ts = dti[0]
|
727 |
+
|
728 |
+
assert pi.get_loc(ts) == 0
|
729 |
+
assert ser[ts] == 7
|
730 |
+
assert ser.loc[ts] == 7
|
731 |
+
|
732 |
+
ts2 = ts + Timedelta(hours=3)
|
733 |
+
if freq == "h":
|
734 |
+
with pytest.raises(KeyError, match="2016-01-01 03:00"):
|
735 |
+
pi.get_loc(ts2)
|
736 |
+
with pytest.raises(KeyError, match="2016-01-01 03:00"):
|
737 |
+
ser[ts2]
|
738 |
+
with pytest.raises(KeyError, match="2016-01-01 03:00"):
|
739 |
+
ser.loc[ts2]
|
740 |
+
else:
|
741 |
+
assert pi.get_loc(ts2) == 0
|
742 |
+
assert ser[ts2] == 7
|
743 |
+
assert ser.loc[ts2] == 7
|
744 |
+
|
745 |
+
|
746 |
+
class TestContains:
|
747 |
+
def test_contains(self):
|
748 |
+
# GH 17717
|
749 |
+
p0 = Period("2017-09-01")
|
750 |
+
p1 = Period("2017-09-02")
|
751 |
+
p2 = Period("2017-09-03")
|
752 |
+
p3 = Period("2017-09-04")
|
753 |
+
|
754 |
+
ps0 = [p0, p1, p2]
|
755 |
+
idx0 = PeriodIndex(ps0)
|
756 |
+
|
757 |
+
for p in ps0:
|
758 |
+
assert p in idx0
|
759 |
+
assert str(p) in idx0
|
760 |
+
|
761 |
+
# GH#31172
|
762 |
+
# Higher-resolution period-like are _not_ considered as contained
|
763 |
+
key = "2017-09-01 00:00:01"
|
764 |
+
assert key not in idx0
|
765 |
+
with pytest.raises(KeyError, match=key):
|
766 |
+
idx0.get_loc(key)
|
767 |
+
|
768 |
+
assert "2017-09" in idx0
|
769 |
+
|
770 |
+
assert p3 not in idx0
|
771 |
+
|
772 |
+
def test_contains_freq_mismatch(self):
|
773 |
+
rng = period_range("2007-01", freq="M", periods=10)
|
774 |
+
|
775 |
+
assert Period("2007-01", freq="M") in rng
|
776 |
+
assert Period("2007-01", freq="D") not in rng
|
777 |
+
assert Period("2007-01", freq="2M") not in rng
|
778 |
+
|
779 |
+
def test_contains_nat(self):
|
780 |
+
# see gh-13582
|
781 |
+
idx = period_range("2007-01", freq="M", periods=10)
|
782 |
+
assert NaT not in idx
|
783 |
+
assert None not in idx
|
784 |
+
assert float("nan") not in idx
|
785 |
+
assert np.nan not in idx
|
786 |
+
|
787 |
+
idx = PeriodIndex(["2011-01", "NaT", "2011-02"], freq="M")
|
788 |
+
assert NaT in idx
|
789 |
+
assert None in idx
|
790 |
+
assert float("nan") in idx
|
791 |
+
assert np.nan in idx
|
792 |
+
|
793 |
+
|
794 |
+
class TestAsOfLocs:
|
795 |
+
def test_asof_locs_mismatched_type(self):
|
796 |
+
dti = date_range("2016-01-01", periods=3)
|
797 |
+
pi = dti.to_period("D")
|
798 |
+
pi2 = dti.to_period("h")
|
799 |
+
|
800 |
+
mask = np.array([0, 1, 0], dtype=bool)
|
801 |
+
|
802 |
+
msg = "must be DatetimeIndex or PeriodIndex"
|
803 |
+
with pytest.raises(TypeError, match=msg):
|
804 |
+
pi.asof_locs(pd.Index(pi.asi8, dtype=np.int64), mask)
|
805 |
+
|
806 |
+
with pytest.raises(TypeError, match=msg):
|
807 |
+
pi.asof_locs(pd.Index(pi.asi8, dtype=np.float64), mask)
|
808 |
+
|
809 |
+
with pytest.raises(TypeError, match=msg):
|
810 |
+
# TimedeltaIndex
|
811 |
+
pi.asof_locs(dti - dti, mask)
|
812 |
+
|
813 |
+
msg = "Input has different freq=h"
|
814 |
+
with pytest.raises(libperiod.IncompatibleFrequency, match=msg):
|
815 |
+
pi.asof_locs(pi2, mask)
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/test_resolution.py
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
import pandas as pd
|
4 |
+
|
5 |
+
|
6 |
+
class TestResolution:
|
7 |
+
@pytest.mark.parametrize(
|
8 |
+
"freq,expected",
|
9 |
+
[
|
10 |
+
("Y", "year"),
|
11 |
+
("Q", "quarter"),
|
12 |
+
("M", "month"),
|
13 |
+
("D", "day"),
|
14 |
+
("h", "hour"),
|
15 |
+
("min", "minute"),
|
16 |
+
("s", "second"),
|
17 |
+
("ms", "millisecond"),
|
18 |
+
("us", "microsecond"),
|
19 |
+
],
|
20 |
+
)
|
21 |
+
def test_resolution(self, freq, expected):
|
22 |
+
idx = pd.period_range(start="2013-04-01", periods=30, freq=freq)
|
23 |
+
assert idx.resolution == expected
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/test_scalar_compat.py
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Tests for PeriodIndex behaving like a vectorized Period scalar"""
|
2 |
+
|
3 |
+
import pytest
|
4 |
+
|
5 |
+
from pandas import (
|
6 |
+
Timedelta,
|
7 |
+
date_range,
|
8 |
+
period_range,
|
9 |
+
)
|
10 |
+
import pandas._testing as tm
|
11 |
+
|
12 |
+
|
13 |
+
class TestPeriodIndexOps:
|
14 |
+
def test_start_time(self):
|
15 |
+
# GH#17157
|
16 |
+
index = period_range(freq="M", start="2016-01-01", end="2016-05-31")
|
17 |
+
expected_index = date_range("2016-01-01", end="2016-05-31", freq="MS")
|
18 |
+
tm.assert_index_equal(index.start_time, expected_index)
|
19 |
+
|
20 |
+
def test_end_time(self):
|
21 |
+
# GH#17157
|
22 |
+
index = period_range(freq="M", start="2016-01-01", end="2016-05-31")
|
23 |
+
expected_index = date_range("2016-01-01", end="2016-05-31", freq="ME")
|
24 |
+
expected_index += Timedelta(1, "D") - Timedelta(1, "ns")
|
25 |
+
tm.assert_index_equal(index.end_time, expected_index)
|
26 |
+
|
27 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
28 |
+
@pytest.mark.filterwarnings(
|
29 |
+
"ignore:Period with BDay freq is deprecated:FutureWarning"
|
30 |
+
)
|
31 |
+
def test_end_time_business_friday(self):
|
32 |
+
# GH#34449
|
33 |
+
pi = period_range("1990-01-05", freq="B", periods=1)
|
34 |
+
result = pi.end_time
|
35 |
+
|
36 |
+
dti = date_range("1990-01-05", freq="D", periods=1)._with_freq(None)
|
37 |
+
expected = dti + Timedelta(days=1, nanoseconds=-1)
|
38 |
+
tm.assert_index_equal(result, expected)
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/test_searchsorted.py
ADDED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas._libs.tslibs import IncompatibleFrequency
|
5 |
+
|
6 |
+
from pandas import (
|
7 |
+
NaT,
|
8 |
+
Period,
|
9 |
+
PeriodIndex,
|
10 |
+
)
|
11 |
+
import pandas._testing as tm
|
12 |
+
|
13 |
+
|
14 |
+
class TestSearchsorted:
|
15 |
+
@pytest.mark.parametrize("freq", ["D", "2D"])
|
16 |
+
def test_searchsorted(self, freq):
|
17 |
+
pidx = PeriodIndex(
|
18 |
+
["2014-01-01", "2014-01-02", "2014-01-03", "2014-01-04", "2014-01-05"],
|
19 |
+
freq=freq,
|
20 |
+
)
|
21 |
+
|
22 |
+
p1 = Period("2014-01-01", freq=freq)
|
23 |
+
assert pidx.searchsorted(p1) == 0
|
24 |
+
|
25 |
+
p2 = Period("2014-01-04", freq=freq)
|
26 |
+
assert pidx.searchsorted(p2) == 3
|
27 |
+
|
28 |
+
assert pidx.searchsorted(NaT) == 5
|
29 |
+
|
30 |
+
msg = "Input has different freq=h from PeriodArray"
|
31 |
+
with pytest.raises(IncompatibleFrequency, match=msg):
|
32 |
+
pidx.searchsorted(Period("2014-01-01", freq="h"))
|
33 |
+
|
34 |
+
msg = "Input has different freq=5D from PeriodArray"
|
35 |
+
with pytest.raises(IncompatibleFrequency, match=msg):
|
36 |
+
pidx.searchsorted(Period("2014-01-01", freq="5D"))
|
37 |
+
|
38 |
+
def test_searchsorted_different_argument_classes(self, listlike_box):
|
39 |
+
pidx = PeriodIndex(
|
40 |
+
["2014-01-01", "2014-01-02", "2014-01-03", "2014-01-04", "2014-01-05"],
|
41 |
+
freq="D",
|
42 |
+
)
|
43 |
+
result = pidx.searchsorted(listlike_box(pidx))
|
44 |
+
expected = np.arange(len(pidx), dtype=result.dtype)
|
45 |
+
tm.assert_numpy_array_equal(result, expected)
|
46 |
+
|
47 |
+
result = pidx._data.searchsorted(listlike_box(pidx))
|
48 |
+
tm.assert_numpy_array_equal(result, expected)
|
49 |
+
|
50 |
+
def test_searchsorted_invalid(self):
|
51 |
+
pidx = PeriodIndex(
|
52 |
+
["2014-01-01", "2014-01-02", "2014-01-03", "2014-01-04", "2014-01-05"],
|
53 |
+
freq="D",
|
54 |
+
)
|
55 |
+
|
56 |
+
other = np.array([0, 1], dtype=np.int64)
|
57 |
+
|
58 |
+
msg = "|".join(
|
59 |
+
[
|
60 |
+
"searchsorted requires compatible dtype or scalar",
|
61 |
+
"value should be a 'Period', 'NaT', or array of those. Got",
|
62 |
+
]
|
63 |
+
)
|
64 |
+
with pytest.raises(TypeError, match=msg):
|
65 |
+
pidx.searchsorted(other)
|
66 |
+
|
67 |
+
with pytest.raises(TypeError, match=msg):
|
68 |
+
pidx.searchsorted(other.astype("timedelta64[ns]"))
|
69 |
+
|
70 |
+
with pytest.raises(TypeError, match=msg):
|
71 |
+
pidx.searchsorted(np.timedelta64(4))
|
72 |
+
|
73 |
+
with pytest.raises(TypeError, match=msg):
|
74 |
+
pidx.searchsorted(np.timedelta64("NaT", "ms"))
|
75 |
+
|
76 |
+
with pytest.raises(TypeError, match=msg):
|
77 |
+
pidx.searchsorted(np.datetime64(4, "ns"))
|
78 |
+
|
79 |
+
with pytest.raises(TypeError, match=msg):
|
80 |
+
pidx.searchsorted(np.datetime64("NaT", "ns"))
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/period/test_tools.py
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas import (
|
5 |
+
Period,
|
6 |
+
PeriodIndex,
|
7 |
+
period_range,
|
8 |
+
)
|
9 |
+
import pandas._testing as tm
|
10 |
+
|
11 |
+
|
12 |
+
class TestPeriodRepresentation:
|
13 |
+
"""
|
14 |
+
Wish to match NumPy units
|
15 |
+
"""
|
16 |
+
|
17 |
+
@pytest.mark.parametrize(
|
18 |
+
"freq, base_date",
|
19 |
+
[
|
20 |
+
("W-THU", "1970-01-01"),
|
21 |
+
("D", "1970-01-01"),
|
22 |
+
("B", "1970-01-01"),
|
23 |
+
("h", "1970-01-01"),
|
24 |
+
("min", "1970-01-01"),
|
25 |
+
("s", "1970-01-01"),
|
26 |
+
("ms", "1970-01-01"),
|
27 |
+
("us", "1970-01-01"),
|
28 |
+
("ns", "1970-01-01"),
|
29 |
+
("M", "1970-01"),
|
30 |
+
("Y", 1970),
|
31 |
+
],
|
32 |
+
)
|
33 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
34 |
+
@pytest.mark.filterwarnings(
|
35 |
+
"ignore:Period with BDay freq is deprecated:FutureWarning"
|
36 |
+
)
|
37 |
+
def test_freq(self, freq, base_date):
|
38 |
+
rng = period_range(start=base_date, periods=10, freq=freq)
|
39 |
+
exp = np.arange(10, dtype=np.int64)
|
40 |
+
|
41 |
+
tm.assert_numpy_array_equal(rng.asi8, exp)
|
42 |
+
|
43 |
+
|
44 |
+
class TestPeriodIndexConversion:
|
45 |
+
def test_tolist(self):
|
46 |
+
index = period_range(freq="Y", start="1/1/2001", end="12/1/2009")
|
47 |
+
rs = index.tolist()
|
48 |
+
for x in rs:
|
49 |
+
assert isinstance(x, Period)
|
50 |
+
|
51 |
+
recon = PeriodIndex(rs)
|
52 |
+
tm.assert_index_equal(index, recon)
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/test_any_index.py
ADDED
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Tests that can be parametrized over _any_ Index object.
|
3 |
+
"""
|
4 |
+
import re
|
5 |
+
|
6 |
+
import numpy as np
|
7 |
+
import pytest
|
8 |
+
|
9 |
+
from pandas.errors import InvalidIndexError
|
10 |
+
|
11 |
+
import pandas._testing as tm
|
12 |
+
|
13 |
+
|
14 |
+
def test_boolean_context_compat(index):
|
15 |
+
# GH#7897
|
16 |
+
with pytest.raises(ValueError, match="The truth value of a"):
|
17 |
+
if index:
|
18 |
+
pass
|
19 |
+
|
20 |
+
with pytest.raises(ValueError, match="The truth value of a"):
|
21 |
+
bool(index)
|
22 |
+
|
23 |
+
|
24 |
+
def test_sort(index):
|
25 |
+
msg = "cannot sort an Index object in-place, use sort_values instead"
|
26 |
+
with pytest.raises(TypeError, match=msg):
|
27 |
+
index.sort()
|
28 |
+
|
29 |
+
|
30 |
+
def test_hash_error(index):
|
31 |
+
with pytest.raises(TypeError, match=f"unhashable type: '{type(index).__name__}'"):
|
32 |
+
hash(index)
|
33 |
+
|
34 |
+
|
35 |
+
def test_mutability(index):
|
36 |
+
if not len(index):
|
37 |
+
pytest.skip("Test doesn't make sense for empty index")
|
38 |
+
msg = "Index does not support mutable operations"
|
39 |
+
with pytest.raises(TypeError, match=msg):
|
40 |
+
index[0] = index[0]
|
41 |
+
|
42 |
+
|
43 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
44 |
+
def test_map_identity_mapping(index, request):
|
45 |
+
# GH#12766
|
46 |
+
|
47 |
+
result = index.map(lambda x: x)
|
48 |
+
if index.dtype == object and result.dtype == bool:
|
49 |
+
assert (index == result).all()
|
50 |
+
# TODO: could work that into the 'exact="equiv"'?
|
51 |
+
return # FIXME: doesn't belong in this file anymore!
|
52 |
+
tm.assert_index_equal(result, index, exact="equiv")
|
53 |
+
|
54 |
+
|
55 |
+
def test_wrong_number_names(index):
|
56 |
+
names = index.nlevels * ["apple", "banana", "carrot"]
|
57 |
+
with pytest.raises(ValueError, match="^Length"):
|
58 |
+
index.names = names
|
59 |
+
|
60 |
+
|
61 |
+
def test_view_preserves_name(index):
|
62 |
+
assert index.view().name == index.name
|
63 |
+
|
64 |
+
|
65 |
+
def test_ravel(index):
|
66 |
+
# GH#19956 ravel returning ndarray is deprecated, in 2.0 returns a view on self
|
67 |
+
res = index.ravel()
|
68 |
+
tm.assert_index_equal(res, index)
|
69 |
+
|
70 |
+
|
71 |
+
class TestConversion:
|
72 |
+
def test_to_series(self, index):
|
73 |
+
# assert that we are creating a copy of the index
|
74 |
+
|
75 |
+
ser = index.to_series()
|
76 |
+
assert ser.values is not index.values
|
77 |
+
assert ser.index is not index
|
78 |
+
assert ser.name == index.name
|
79 |
+
|
80 |
+
def test_to_series_with_arguments(self, index):
|
81 |
+
# GH#18699
|
82 |
+
|
83 |
+
# index kwarg
|
84 |
+
ser = index.to_series(index=index)
|
85 |
+
|
86 |
+
assert ser.values is not index.values
|
87 |
+
assert ser.index is index
|
88 |
+
assert ser.name == index.name
|
89 |
+
|
90 |
+
# name kwarg
|
91 |
+
ser = index.to_series(name="__test")
|
92 |
+
|
93 |
+
assert ser.values is not index.values
|
94 |
+
assert ser.index is not index
|
95 |
+
assert ser.name != index.name
|
96 |
+
|
97 |
+
def test_tolist_matches_list(self, index):
|
98 |
+
assert index.tolist() == list(index)
|
99 |
+
|
100 |
+
|
101 |
+
class TestRoundTrips:
|
102 |
+
def test_pickle_roundtrip(self, index):
|
103 |
+
result = tm.round_trip_pickle(index)
|
104 |
+
tm.assert_index_equal(result, index, exact=True)
|
105 |
+
if result.nlevels > 1:
|
106 |
+
# GH#8367 round-trip with timezone
|
107 |
+
assert index.equal_levels(result)
|
108 |
+
|
109 |
+
def test_pickle_preserves_name(self, index):
|
110 |
+
original_name, index.name = index.name, "foo"
|
111 |
+
unpickled = tm.round_trip_pickle(index)
|
112 |
+
assert index.equals(unpickled)
|
113 |
+
index.name = original_name
|
114 |
+
|
115 |
+
|
116 |
+
class TestIndexing:
|
117 |
+
def test_get_loc_listlike_raises_invalid_index_error(self, index):
|
118 |
+
# and never TypeError
|
119 |
+
key = np.array([0, 1], dtype=np.intp)
|
120 |
+
|
121 |
+
with pytest.raises(InvalidIndexError, match=r"\[0 1\]"):
|
122 |
+
index.get_loc(key)
|
123 |
+
|
124 |
+
with pytest.raises(InvalidIndexError, match=r"\[False True\]"):
|
125 |
+
index.get_loc(key.astype(bool))
|
126 |
+
|
127 |
+
def test_getitem_ellipsis(self, index):
|
128 |
+
# GH#21282
|
129 |
+
result = index[...]
|
130 |
+
assert result.equals(index)
|
131 |
+
assert result is not index
|
132 |
+
|
133 |
+
def test_slice_keeps_name(self, index):
|
134 |
+
assert index.name == index[1:].name
|
135 |
+
|
136 |
+
@pytest.mark.parametrize("item", [101, "no_int", 2.5])
|
137 |
+
def test_getitem_error(self, index, item):
|
138 |
+
msg = "|".join(
|
139 |
+
[
|
140 |
+
r"index 101 is out of bounds for axis 0 with size [\d]+",
|
141 |
+
re.escape(
|
142 |
+
"only integers, slices (`:`), ellipsis (`...`), "
|
143 |
+
"numpy.newaxis (`None`) and integer or boolean arrays "
|
144 |
+
"are valid indices"
|
145 |
+
),
|
146 |
+
"index out of bounds", # string[pyarrow]
|
147 |
+
]
|
148 |
+
)
|
149 |
+
with pytest.raises(IndexError, match=msg):
|
150 |
+
index[item]
|
151 |
+
|
152 |
+
|
153 |
+
class TestRendering:
|
154 |
+
def test_str(self, index):
|
155 |
+
# test the string repr
|
156 |
+
index.name = "foo"
|
157 |
+
assert "'foo'" in str(index)
|
158 |
+
assert type(index).__name__ in str(index)
|
159 |
+
|
160 |
+
|
161 |
+
class TestReductions:
|
162 |
+
def test_argmax_axis_invalid(self, index):
|
163 |
+
# GH#23081
|
164 |
+
msg = r"`axis` must be fewer than the number of dimensions \(1\)"
|
165 |
+
with pytest.raises(ValueError, match=msg):
|
166 |
+
index.argmax(axis=1)
|
167 |
+
with pytest.raises(ValueError, match=msg):
|
168 |
+
index.argmin(axis=2)
|
169 |
+
with pytest.raises(ValueError, match=msg):
|
170 |
+
index.min(axis=-2)
|
171 |
+
with pytest.raises(ValueError, match=msg):
|
172 |
+
index.max(axis=-3)
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/test_base.py
ADDED
@@ -0,0 +1,1737 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from collections import defaultdict
|
2 |
+
from datetime import datetime
|
3 |
+
from functools import partial
|
4 |
+
import math
|
5 |
+
import operator
|
6 |
+
import re
|
7 |
+
|
8 |
+
import numpy as np
|
9 |
+
import pytest
|
10 |
+
|
11 |
+
from pandas.compat import IS64
|
12 |
+
from pandas.errors import InvalidIndexError
|
13 |
+
import pandas.util._test_decorators as td
|
14 |
+
|
15 |
+
from pandas.core.dtypes.common import (
|
16 |
+
is_any_real_numeric_dtype,
|
17 |
+
is_numeric_dtype,
|
18 |
+
is_object_dtype,
|
19 |
+
)
|
20 |
+
|
21 |
+
import pandas as pd
|
22 |
+
from pandas import (
|
23 |
+
CategoricalIndex,
|
24 |
+
DataFrame,
|
25 |
+
DatetimeIndex,
|
26 |
+
IntervalIndex,
|
27 |
+
PeriodIndex,
|
28 |
+
RangeIndex,
|
29 |
+
Series,
|
30 |
+
TimedeltaIndex,
|
31 |
+
date_range,
|
32 |
+
period_range,
|
33 |
+
timedelta_range,
|
34 |
+
)
|
35 |
+
import pandas._testing as tm
|
36 |
+
from pandas.core.indexes.api import (
|
37 |
+
Index,
|
38 |
+
MultiIndex,
|
39 |
+
_get_combined_index,
|
40 |
+
ensure_index,
|
41 |
+
ensure_index_from_sequences,
|
42 |
+
)
|
43 |
+
|
44 |
+
|
45 |
+
class TestIndex:
|
46 |
+
@pytest.fixture
|
47 |
+
def simple_index(self) -> Index:
|
48 |
+
return Index(list("abcde"))
|
49 |
+
|
50 |
+
def test_can_hold_identifiers(self, simple_index):
|
51 |
+
index = simple_index
|
52 |
+
key = index[0]
|
53 |
+
assert index._can_hold_identifiers_and_holds_name(key) is True
|
54 |
+
|
55 |
+
@pytest.mark.parametrize("index", ["datetime"], indirect=True)
|
56 |
+
def test_new_axis(self, index):
|
57 |
+
# TODO: a bunch of scattered tests check this deprecation is enforced.
|
58 |
+
# de-duplicate/centralize them.
|
59 |
+
with pytest.raises(ValueError, match="Multi-dimensional indexing"):
|
60 |
+
# GH#30588 multi-dimensional indexing deprecated
|
61 |
+
index[None, :]
|
62 |
+
|
63 |
+
def test_constructor_regular(self, index):
|
64 |
+
tm.assert_contains_all(index, index)
|
65 |
+
|
66 |
+
@pytest.mark.parametrize("index", ["string"], indirect=True)
|
67 |
+
def test_constructor_casting(self, index):
|
68 |
+
# casting
|
69 |
+
arr = np.array(index)
|
70 |
+
new_index = Index(arr)
|
71 |
+
tm.assert_contains_all(arr, new_index)
|
72 |
+
tm.assert_index_equal(index, new_index)
|
73 |
+
|
74 |
+
@pytest.mark.parametrize("index", ["string"], indirect=True)
|
75 |
+
def test_constructor_copy(self, index, using_infer_string):
|
76 |
+
arr = np.array(index)
|
77 |
+
new_index = Index(arr, copy=True, name="name")
|
78 |
+
assert isinstance(new_index, Index)
|
79 |
+
assert new_index.name == "name"
|
80 |
+
if using_infer_string:
|
81 |
+
tm.assert_extension_array_equal(
|
82 |
+
new_index.values, pd.array(arr, dtype="string[pyarrow_numpy]")
|
83 |
+
)
|
84 |
+
else:
|
85 |
+
tm.assert_numpy_array_equal(arr, new_index.values)
|
86 |
+
arr[0] = "SOMEBIGLONGSTRING"
|
87 |
+
assert new_index[0] != "SOMEBIGLONGSTRING"
|
88 |
+
|
89 |
+
@pytest.mark.parametrize("cast_as_obj", [True, False])
|
90 |
+
@pytest.mark.parametrize(
|
91 |
+
"index",
|
92 |
+
[
|
93 |
+
date_range(
|
94 |
+
"2015-01-01 10:00",
|
95 |
+
freq="D",
|
96 |
+
periods=3,
|
97 |
+
tz="US/Eastern",
|
98 |
+
name="Green Eggs & Ham",
|
99 |
+
), # DTI with tz
|
100 |
+
date_range("2015-01-01 10:00", freq="D", periods=3), # DTI no tz
|
101 |
+
timedelta_range("1 days", freq="D", periods=3), # td
|
102 |
+
period_range("2015-01-01", freq="D", periods=3), # period
|
103 |
+
],
|
104 |
+
)
|
105 |
+
def test_constructor_from_index_dtlike(self, cast_as_obj, index):
|
106 |
+
if cast_as_obj:
|
107 |
+
with tm.assert_produces_warning(FutureWarning, match="Dtype inference"):
|
108 |
+
result = Index(index.astype(object))
|
109 |
+
else:
|
110 |
+
result = Index(index)
|
111 |
+
|
112 |
+
tm.assert_index_equal(result, index)
|
113 |
+
|
114 |
+
if isinstance(index, DatetimeIndex):
|
115 |
+
assert result.tz == index.tz
|
116 |
+
if cast_as_obj:
|
117 |
+
# GH#23524 check that Index(dti, dtype=object) does not
|
118 |
+
# incorrectly raise ValueError, and that nanoseconds are not
|
119 |
+
# dropped
|
120 |
+
index += pd.Timedelta(nanoseconds=50)
|
121 |
+
result = Index(index, dtype=object)
|
122 |
+
assert result.dtype == np.object_
|
123 |
+
assert list(result) == list(index)
|
124 |
+
|
125 |
+
@pytest.mark.parametrize(
|
126 |
+
"index,has_tz",
|
127 |
+
[
|
128 |
+
(
|
129 |
+
date_range("2015-01-01 10:00", freq="D", periods=3, tz="US/Eastern"),
|
130 |
+
True,
|
131 |
+
), # datetimetz
|
132 |
+
(timedelta_range("1 days", freq="D", periods=3), False), # td
|
133 |
+
(period_range("2015-01-01", freq="D", periods=3), False), # period
|
134 |
+
],
|
135 |
+
)
|
136 |
+
def test_constructor_from_series_dtlike(self, index, has_tz):
|
137 |
+
result = Index(Series(index))
|
138 |
+
tm.assert_index_equal(result, index)
|
139 |
+
|
140 |
+
if has_tz:
|
141 |
+
assert result.tz == index.tz
|
142 |
+
|
143 |
+
def test_constructor_from_series_freq(self):
|
144 |
+
# GH 6273
|
145 |
+
# create from a series, passing a freq
|
146 |
+
dts = ["1-1-1990", "2-1-1990", "3-1-1990", "4-1-1990", "5-1-1990"]
|
147 |
+
expected = DatetimeIndex(dts, freq="MS")
|
148 |
+
|
149 |
+
s = Series(pd.to_datetime(dts))
|
150 |
+
result = DatetimeIndex(s, freq="MS")
|
151 |
+
|
152 |
+
tm.assert_index_equal(result, expected)
|
153 |
+
|
154 |
+
def test_constructor_from_frame_series_freq(self, using_infer_string):
|
155 |
+
# GH 6273
|
156 |
+
# create from a series, passing a freq
|
157 |
+
dts = ["1-1-1990", "2-1-1990", "3-1-1990", "4-1-1990", "5-1-1990"]
|
158 |
+
expected = DatetimeIndex(dts, freq="MS")
|
159 |
+
|
160 |
+
df = DataFrame(np.random.default_rng(2).random((5, 3)))
|
161 |
+
df["date"] = dts
|
162 |
+
result = DatetimeIndex(df["date"], freq="MS")
|
163 |
+
dtype = object if not using_infer_string else "string"
|
164 |
+
assert df["date"].dtype == dtype
|
165 |
+
expected.name = "date"
|
166 |
+
tm.assert_index_equal(result, expected)
|
167 |
+
|
168 |
+
expected = Series(dts, name="date")
|
169 |
+
tm.assert_series_equal(df["date"], expected)
|
170 |
+
|
171 |
+
# GH 6274
|
172 |
+
# infer freq of same
|
173 |
+
if not using_infer_string:
|
174 |
+
# Doesn't work with arrow strings
|
175 |
+
freq = pd.infer_freq(df["date"])
|
176 |
+
assert freq == "MS"
|
177 |
+
|
178 |
+
def test_constructor_int_dtype_nan(self):
|
179 |
+
# see gh-15187
|
180 |
+
data = [np.nan]
|
181 |
+
expected = Index(data, dtype=np.float64)
|
182 |
+
result = Index(data, dtype="float")
|
183 |
+
tm.assert_index_equal(result, expected)
|
184 |
+
|
185 |
+
@pytest.mark.parametrize(
|
186 |
+
"klass,dtype,na_val",
|
187 |
+
[
|
188 |
+
(Index, np.float64, np.nan),
|
189 |
+
(DatetimeIndex, "datetime64[ns]", pd.NaT),
|
190 |
+
],
|
191 |
+
)
|
192 |
+
def test_index_ctor_infer_nan_nat(self, klass, dtype, na_val):
|
193 |
+
# GH 13467
|
194 |
+
na_list = [na_val, na_val]
|
195 |
+
expected = klass(na_list)
|
196 |
+
assert expected.dtype == dtype
|
197 |
+
|
198 |
+
result = Index(na_list)
|
199 |
+
tm.assert_index_equal(result, expected)
|
200 |
+
|
201 |
+
result = Index(np.array(na_list))
|
202 |
+
tm.assert_index_equal(result, expected)
|
203 |
+
|
204 |
+
@pytest.mark.parametrize(
|
205 |
+
"vals,dtype",
|
206 |
+
[
|
207 |
+
([1, 2, 3, 4, 5], "int"),
|
208 |
+
([1.1, np.nan, 2.2, 3.0], "float"),
|
209 |
+
(["A", "B", "C", np.nan], "obj"),
|
210 |
+
],
|
211 |
+
)
|
212 |
+
def test_constructor_simple_new(self, vals, dtype):
|
213 |
+
index = Index(vals, name=dtype)
|
214 |
+
result = index._simple_new(index.values, dtype)
|
215 |
+
tm.assert_index_equal(result, index)
|
216 |
+
|
217 |
+
@pytest.mark.parametrize("attr", ["values", "asi8"])
|
218 |
+
@pytest.mark.parametrize("klass", [Index, DatetimeIndex])
|
219 |
+
def test_constructor_dtypes_datetime(self, tz_naive_fixture, attr, klass):
|
220 |
+
# Test constructing with a datetimetz dtype
|
221 |
+
# .values produces numpy datetimes, so these are considered naive
|
222 |
+
# .asi8 produces integers, so these are considered epoch timestamps
|
223 |
+
# ^the above will be true in a later version. Right now we `.view`
|
224 |
+
# the i8 values as NS_DTYPE, effectively treating them as wall times.
|
225 |
+
index = date_range("2011-01-01", periods=5)
|
226 |
+
arg = getattr(index, attr)
|
227 |
+
index = index.tz_localize(tz_naive_fixture)
|
228 |
+
dtype = index.dtype
|
229 |
+
|
230 |
+
# As of 2.0 astype raises on dt64.astype(dt64tz)
|
231 |
+
err = tz_naive_fixture is not None
|
232 |
+
msg = "Cannot use .astype to convert from timezone-naive dtype to"
|
233 |
+
|
234 |
+
if attr == "asi8":
|
235 |
+
result = DatetimeIndex(arg).tz_localize(tz_naive_fixture)
|
236 |
+
tm.assert_index_equal(result, index)
|
237 |
+
elif klass is Index:
|
238 |
+
with pytest.raises(TypeError, match="unexpected keyword"):
|
239 |
+
klass(arg, tz=tz_naive_fixture)
|
240 |
+
else:
|
241 |
+
result = klass(arg, tz=tz_naive_fixture)
|
242 |
+
tm.assert_index_equal(result, index)
|
243 |
+
|
244 |
+
if attr == "asi8":
|
245 |
+
if err:
|
246 |
+
with pytest.raises(TypeError, match=msg):
|
247 |
+
DatetimeIndex(arg).astype(dtype)
|
248 |
+
else:
|
249 |
+
result = DatetimeIndex(arg).astype(dtype)
|
250 |
+
tm.assert_index_equal(result, index)
|
251 |
+
else:
|
252 |
+
result = klass(arg, dtype=dtype)
|
253 |
+
tm.assert_index_equal(result, index)
|
254 |
+
|
255 |
+
if attr == "asi8":
|
256 |
+
result = DatetimeIndex(list(arg)).tz_localize(tz_naive_fixture)
|
257 |
+
tm.assert_index_equal(result, index)
|
258 |
+
elif klass is Index:
|
259 |
+
with pytest.raises(TypeError, match="unexpected keyword"):
|
260 |
+
klass(arg, tz=tz_naive_fixture)
|
261 |
+
else:
|
262 |
+
result = klass(list(arg), tz=tz_naive_fixture)
|
263 |
+
tm.assert_index_equal(result, index)
|
264 |
+
|
265 |
+
if attr == "asi8":
|
266 |
+
if err:
|
267 |
+
with pytest.raises(TypeError, match=msg):
|
268 |
+
DatetimeIndex(list(arg)).astype(dtype)
|
269 |
+
else:
|
270 |
+
result = DatetimeIndex(list(arg)).astype(dtype)
|
271 |
+
tm.assert_index_equal(result, index)
|
272 |
+
else:
|
273 |
+
result = klass(list(arg), dtype=dtype)
|
274 |
+
tm.assert_index_equal(result, index)
|
275 |
+
|
276 |
+
@pytest.mark.parametrize("attr", ["values", "asi8"])
|
277 |
+
@pytest.mark.parametrize("klass", [Index, TimedeltaIndex])
|
278 |
+
def test_constructor_dtypes_timedelta(self, attr, klass):
|
279 |
+
index = timedelta_range("1 days", periods=5)
|
280 |
+
index = index._with_freq(None) # won't be preserved by constructors
|
281 |
+
dtype = index.dtype
|
282 |
+
|
283 |
+
values = getattr(index, attr)
|
284 |
+
|
285 |
+
result = klass(values, dtype=dtype)
|
286 |
+
tm.assert_index_equal(result, index)
|
287 |
+
|
288 |
+
result = klass(list(values), dtype=dtype)
|
289 |
+
tm.assert_index_equal(result, index)
|
290 |
+
|
291 |
+
@pytest.mark.parametrize("value", [[], iter([]), (_ for _ in [])])
|
292 |
+
@pytest.mark.parametrize(
|
293 |
+
"klass",
|
294 |
+
[
|
295 |
+
Index,
|
296 |
+
CategoricalIndex,
|
297 |
+
DatetimeIndex,
|
298 |
+
TimedeltaIndex,
|
299 |
+
],
|
300 |
+
)
|
301 |
+
def test_constructor_empty(self, value, klass):
|
302 |
+
empty = klass(value)
|
303 |
+
assert isinstance(empty, klass)
|
304 |
+
assert not len(empty)
|
305 |
+
|
306 |
+
@pytest.mark.parametrize(
|
307 |
+
"empty,klass",
|
308 |
+
[
|
309 |
+
(PeriodIndex([], freq="D"), PeriodIndex),
|
310 |
+
(PeriodIndex(iter([]), freq="D"), PeriodIndex),
|
311 |
+
(PeriodIndex((_ for _ in []), freq="D"), PeriodIndex),
|
312 |
+
(RangeIndex(step=1), RangeIndex),
|
313 |
+
(MultiIndex(levels=[[1, 2], ["blue", "red"]], codes=[[], []]), MultiIndex),
|
314 |
+
],
|
315 |
+
)
|
316 |
+
def test_constructor_empty_special(self, empty, klass):
|
317 |
+
assert isinstance(empty, klass)
|
318 |
+
assert not len(empty)
|
319 |
+
|
320 |
+
@pytest.mark.parametrize(
|
321 |
+
"index",
|
322 |
+
[
|
323 |
+
"datetime",
|
324 |
+
"float64",
|
325 |
+
"float32",
|
326 |
+
"int64",
|
327 |
+
"int32",
|
328 |
+
"period",
|
329 |
+
"range",
|
330 |
+
"repeats",
|
331 |
+
"timedelta",
|
332 |
+
"tuples",
|
333 |
+
"uint64",
|
334 |
+
"uint32",
|
335 |
+
],
|
336 |
+
indirect=True,
|
337 |
+
)
|
338 |
+
def test_view_with_args(self, index):
|
339 |
+
index.view("i8")
|
340 |
+
|
341 |
+
@pytest.mark.parametrize(
|
342 |
+
"index",
|
343 |
+
[
|
344 |
+
"string",
|
345 |
+
pytest.param("categorical", marks=pytest.mark.xfail(reason="gh-25464")),
|
346 |
+
"bool-object",
|
347 |
+
"bool-dtype",
|
348 |
+
"empty",
|
349 |
+
],
|
350 |
+
indirect=True,
|
351 |
+
)
|
352 |
+
def test_view_with_args_object_array_raises(self, index):
|
353 |
+
if index.dtype == bool:
|
354 |
+
msg = "When changing to a larger dtype"
|
355 |
+
with pytest.raises(ValueError, match=msg):
|
356 |
+
index.view("i8")
|
357 |
+
elif index.dtype == "string":
|
358 |
+
with pytest.raises(NotImplementedError, match="i8"):
|
359 |
+
index.view("i8")
|
360 |
+
else:
|
361 |
+
msg = (
|
362 |
+
"Cannot change data-type for array of references|"
|
363 |
+
"Cannot change data-type for object array|"
|
364 |
+
)
|
365 |
+
with pytest.raises(TypeError, match=msg):
|
366 |
+
index.view("i8")
|
367 |
+
|
368 |
+
@pytest.mark.parametrize(
|
369 |
+
"index",
|
370 |
+
["int64", "int32", "range"],
|
371 |
+
indirect=True,
|
372 |
+
)
|
373 |
+
def test_astype(self, index):
|
374 |
+
casted = index.astype("i8")
|
375 |
+
|
376 |
+
# it works!
|
377 |
+
casted.get_loc(5)
|
378 |
+
|
379 |
+
# pass on name
|
380 |
+
index.name = "foobar"
|
381 |
+
casted = index.astype("i8")
|
382 |
+
assert casted.name == "foobar"
|
383 |
+
|
384 |
+
def test_equals_object(self):
|
385 |
+
# same
|
386 |
+
assert Index(["a", "b", "c"]).equals(Index(["a", "b", "c"]))
|
387 |
+
|
388 |
+
@pytest.mark.parametrize(
|
389 |
+
"comp", [Index(["a", "b"]), Index(["a", "b", "d"]), ["a", "b", "c"]]
|
390 |
+
)
|
391 |
+
def test_not_equals_object(self, comp):
|
392 |
+
assert not Index(["a", "b", "c"]).equals(comp)
|
393 |
+
|
394 |
+
def test_identical(self):
|
395 |
+
# index
|
396 |
+
i1 = Index(["a", "b", "c"])
|
397 |
+
i2 = Index(["a", "b", "c"])
|
398 |
+
|
399 |
+
assert i1.identical(i2)
|
400 |
+
|
401 |
+
i1 = i1.rename("foo")
|
402 |
+
assert i1.equals(i2)
|
403 |
+
assert not i1.identical(i2)
|
404 |
+
|
405 |
+
i2 = i2.rename("foo")
|
406 |
+
assert i1.identical(i2)
|
407 |
+
|
408 |
+
i3 = Index([("a", "a"), ("a", "b"), ("b", "a")])
|
409 |
+
i4 = Index([("a", "a"), ("a", "b"), ("b", "a")], tupleize_cols=False)
|
410 |
+
assert not i3.identical(i4)
|
411 |
+
|
412 |
+
def test_is_(self):
|
413 |
+
ind = Index(range(10))
|
414 |
+
assert ind.is_(ind)
|
415 |
+
assert ind.is_(ind.view().view().view().view())
|
416 |
+
assert not ind.is_(Index(range(10)))
|
417 |
+
assert not ind.is_(ind.copy())
|
418 |
+
assert not ind.is_(ind.copy(deep=False))
|
419 |
+
assert not ind.is_(ind[:])
|
420 |
+
assert not ind.is_(np.array(range(10)))
|
421 |
+
|
422 |
+
# quasi-implementation dependent
|
423 |
+
assert ind.is_(ind.view())
|
424 |
+
ind2 = ind.view()
|
425 |
+
ind2.name = "bob"
|
426 |
+
assert ind.is_(ind2)
|
427 |
+
assert ind2.is_(ind)
|
428 |
+
# doesn't matter if Indices are *actually* views of underlying data,
|
429 |
+
assert not ind.is_(Index(ind.values))
|
430 |
+
arr = np.array(range(1, 11))
|
431 |
+
ind1 = Index(arr, copy=False)
|
432 |
+
ind2 = Index(arr, copy=False)
|
433 |
+
assert not ind1.is_(ind2)
|
434 |
+
|
435 |
+
def test_asof_numeric_vs_bool_raises(self):
|
436 |
+
left = Index([1, 2, 3])
|
437 |
+
right = Index([True, False], dtype=object)
|
438 |
+
|
439 |
+
msg = "Cannot compare dtypes int64 and bool"
|
440 |
+
with pytest.raises(TypeError, match=msg):
|
441 |
+
left.asof(right[0])
|
442 |
+
# TODO: should right.asof(left[0]) also raise?
|
443 |
+
|
444 |
+
with pytest.raises(InvalidIndexError, match=re.escape(str(right))):
|
445 |
+
left.asof(right)
|
446 |
+
|
447 |
+
with pytest.raises(InvalidIndexError, match=re.escape(str(left))):
|
448 |
+
right.asof(left)
|
449 |
+
|
450 |
+
@pytest.mark.parametrize("index", ["string"], indirect=True)
|
451 |
+
def test_booleanindex(self, index):
|
452 |
+
bool_index = np.ones(len(index), dtype=bool)
|
453 |
+
bool_index[5:30:2] = False
|
454 |
+
|
455 |
+
sub_index = index[bool_index]
|
456 |
+
|
457 |
+
for i, val in enumerate(sub_index):
|
458 |
+
assert sub_index.get_loc(val) == i
|
459 |
+
|
460 |
+
sub_index = index[list(bool_index)]
|
461 |
+
for i, val in enumerate(sub_index):
|
462 |
+
assert sub_index.get_loc(val) == i
|
463 |
+
|
464 |
+
def test_fancy(self, simple_index):
|
465 |
+
index = simple_index
|
466 |
+
sl = index[[1, 2, 3]]
|
467 |
+
for i in sl:
|
468 |
+
assert i == sl[sl.get_loc(i)]
|
469 |
+
|
470 |
+
@pytest.mark.parametrize(
|
471 |
+
"index",
|
472 |
+
["string", "int64", "int32", "uint64", "uint32", "float64", "float32"],
|
473 |
+
indirect=True,
|
474 |
+
)
|
475 |
+
@pytest.mark.parametrize("dtype", [int, np.bool_])
|
476 |
+
def test_empty_fancy(self, index, dtype, request, using_infer_string):
|
477 |
+
if dtype is np.bool_ and using_infer_string and index.dtype == "string":
|
478 |
+
request.applymarker(pytest.mark.xfail(reason="numpy behavior is buggy"))
|
479 |
+
empty_arr = np.array([], dtype=dtype)
|
480 |
+
empty_index = type(index)([], dtype=index.dtype)
|
481 |
+
|
482 |
+
assert index[[]].identical(empty_index)
|
483 |
+
if dtype == np.bool_:
|
484 |
+
with tm.assert_produces_warning(FutureWarning, match="is deprecated"):
|
485 |
+
assert index[empty_arr].identical(empty_index)
|
486 |
+
else:
|
487 |
+
assert index[empty_arr].identical(empty_index)
|
488 |
+
|
489 |
+
@pytest.mark.parametrize(
|
490 |
+
"index",
|
491 |
+
["string", "int64", "int32", "uint64", "uint32", "float64", "float32"],
|
492 |
+
indirect=True,
|
493 |
+
)
|
494 |
+
def test_empty_fancy_raises(self, index):
|
495 |
+
# DatetimeIndex is excluded, because it overrides getitem and should
|
496 |
+
# be tested separately.
|
497 |
+
empty_farr = np.array([], dtype=np.float64)
|
498 |
+
empty_index = type(index)([], dtype=index.dtype)
|
499 |
+
|
500 |
+
assert index[[]].identical(empty_index)
|
501 |
+
# np.ndarray only accepts ndarray of int & bool dtypes, so should Index
|
502 |
+
msg = r"arrays used as indices must be of integer"
|
503 |
+
with pytest.raises(IndexError, match=msg):
|
504 |
+
index[empty_farr]
|
505 |
+
|
506 |
+
def test_union_dt_as_obj(self, simple_index):
|
507 |
+
# TODO: Replace with fixturesult
|
508 |
+
index = simple_index
|
509 |
+
date_index = date_range("2019-01-01", periods=10)
|
510 |
+
first_cat = index.union(date_index)
|
511 |
+
second_cat = index.union(index)
|
512 |
+
|
513 |
+
appended = Index(np.append(index, date_index.astype("O")))
|
514 |
+
|
515 |
+
tm.assert_index_equal(first_cat, appended)
|
516 |
+
tm.assert_index_equal(second_cat, index)
|
517 |
+
tm.assert_contains_all(index, first_cat)
|
518 |
+
tm.assert_contains_all(index, second_cat)
|
519 |
+
tm.assert_contains_all(date_index, first_cat)
|
520 |
+
|
521 |
+
def test_map_with_tuples(self):
|
522 |
+
# GH 12766
|
523 |
+
|
524 |
+
# Test that returning a single tuple from an Index
|
525 |
+
# returns an Index.
|
526 |
+
index = Index(np.arange(3), dtype=np.int64)
|
527 |
+
result = index.map(lambda x: (x,))
|
528 |
+
expected = Index([(i,) for i in index])
|
529 |
+
tm.assert_index_equal(result, expected)
|
530 |
+
|
531 |
+
# Test that returning a tuple from a map of a single index
|
532 |
+
# returns a MultiIndex object.
|
533 |
+
result = index.map(lambda x: (x, x == 1))
|
534 |
+
expected = MultiIndex.from_tuples([(i, i == 1) for i in index])
|
535 |
+
tm.assert_index_equal(result, expected)
|
536 |
+
|
537 |
+
def test_map_with_tuples_mi(self):
|
538 |
+
# Test that returning a single object from a MultiIndex
|
539 |
+
# returns an Index.
|
540 |
+
first_level = ["foo", "bar", "baz"]
|
541 |
+
multi_index = MultiIndex.from_tuples(zip(first_level, [1, 2, 3]))
|
542 |
+
reduced_index = multi_index.map(lambda x: x[0])
|
543 |
+
tm.assert_index_equal(reduced_index, Index(first_level))
|
544 |
+
|
545 |
+
@pytest.mark.parametrize(
|
546 |
+
"index",
|
547 |
+
[
|
548 |
+
date_range("2020-01-01", freq="D", periods=10),
|
549 |
+
period_range("2020-01-01", freq="D", periods=10),
|
550 |
+
timedelta_range("1 day", periods=10),
|
551 |
+
],
|
552 |
+
)
|
553 |
+
def test_map_tseries_indices_return_index(self, index):
|
554 |
+
expected = Index([1] * 10)
|
555 |
+
result = index.map(lambda x: 1)
|
556 |
+
tm.assert_index_equal(expected, result)
|
557 |
+
|
558 |
+
def test_map_tseries_indices_accsr_return_index(self):
|
559 |
+
date_index = DatetimeIndex(
|
560 |
+
date_range("2020-01-01", periods=24, freq="h"), name="hourly"
|
561 |
+
)
|
562 |
+
result = date_index.map(lambda x: x.hour)
|
563 |
+
expected = Index(np.arange(24, dtype="int64"), name="hourly")
|
564 |
+
tm.assert_index_equal(result, expected, exact=True)
|
565 |
+
|
566 |
+
@pytest.mark.parametrize(
|
567 |
+
"mapper",
|
568 |
+
[
|
569 |
+
lambda values, index: {i: e for e, i in zip(values, index)},
|
570 |
+
lambda values, index: Series(values, index),
|
571 |
+
],
|
572 |
+
)
|
573 |
+
def test_map_dictlike_simple(self, mapper):
|
574 |
+
# GH 12756
|
575 |
+
expected = Index(["foo", "bar", "baz"])
|
576 |
+
index = Index(np.arange(3), dtype=np.int64)
|
577 |
+
result = index.map(mapper(expected.values, index))
|
578 |
+
tm.assert_index_equal(result, expected)
|
579 |
+
|
580 |
+
@pytest.mark.parametrize(
|
581 |
+
"mapper",
|
582 |
+
[
|
583 |
+
lambda values, index: {i: e for e, i in zip(values, index)},
|
584 |
+
lambda values, index: Series(values, index),
|
585 |
+
],
|
586 |
+
)
|
587 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
588 |
+
def test_map_dictlike(self, index, mapper, request):
|
589 |
+
# GH 12756
|
590 |
+
if isinstance(index, CategoricalIndex):
|
591 |
+
pytest.skip("Tested in test_categorical")
|
592 |
+
elif not index.is_unique:
|
593 |
+
pytest.skip("Cannot map duplicated index")
|
594 |
+
|
595 |
+
rng = np.arange(len(index), 0, -1, dtype=np.int64)
|
596 |
+
|
597 |
+
if index.empty:
|
598 |
+
# to match proper result coercion for uints
|
599 |
+
expected = Index([])
|
600 |
+
elif is_numeric_dtype(index.dtype):
|
601 |
+
expected = index._constructor(rng, dtype=index.dtype)
|
602 |
+
elif type(index) is Index and index.dtype != object:
|
603 |
+
# i.e. EA-backed, for now just Nullable
|
604 |
+
expected = Index(rng, dtype=index.dtype)
|
605 |
+
else:
|
606 |
+
expected = Index(rng)
|
607 |
+
|
608 |
+
result = index.map(mapper(expected, index))
|
609 |
+
tm.assert_index_equal(result, expected)
|
610 |
+
|
611 |
+
@pytest.mark.parametrize(
|
612 |
+
"mapper",
|
613 |
+
[Series(["foo", 2.0, "baz"], index=[0, 2, -1]), {0: "foo", 2: 2.0, -1: "baz"}],
|
614 |
+
)
|
615 |
+
def test_map_with_non_function_missing_values(self, mapper):
|
616 |
+
# GH 12756
|
617 |
+
expected = Index([2.0, np.nan, "foo"])
|
618 |
+
result = Index([2, 1, 0]).map(mapper)
|
619 |
+
|
620 |
+
tm.assert_index_equal(expected, result)
|
621 |
+
|
622 |
+
def test_map_na_exclusion(self):
|
623 |
+
index = Index([1.5, np.nan, 3, np.nan, 5])
|
624 |
+
|
625 |
+
result = index.map(lambda x: x * 2, na_action="ignore")
|
626 |
+
expected = index * 2
|
627 |
+
tm.assert_index_equal(result, expected)
|
628 |
+
|
629 |
+
def test_map_defaultdict(self):
|
630 |
+
index = Index([1, 2, 3])
|
631 |
+
default_dict = defaultdict(lambda: "blank")
|
632 |
+
default_dict[1] = "stuff"
|
633 |
+
result = index.map(default_dict)
|
634 |
+
expected = Index(["stuff", "blank", "blank"])
|
635 |
+
tm.assert_index_equal(result, expected)
|
636 |
+
|
637 |
+
@pytest.mark.parametrize("name,expected", [("foo", "foo"), ("bar", None)])
|
638 |
+
def test_append_empty_preserve_name(self, name, expected):
|
639 |
+
left = Index([], name="foo")
|
640 |
+
right = Index([1, 2, 3], name=name)
|
641 |
+
|
642 |
+
msg = "The behavior of array concatenation with empty entries is deprecated"
|
643 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
644 |
+
result = left.append(right)
|
645 |
+
assert result.name == expected
|
646 |
+
|
647 |
+
@pytest.mark.parametrize(
|
648 |
+
"index, expected",
|
649 |
+
[
|
650 |
+
("string", False),
|
651 |
+
("bool-object", False),
|
652 |
+
("bool-dtype", False),
|
653 |
+
("categorical", False),
|
654 |
+
("int64", True),
|
655 |
+
("int32", True),
|
656 |
+
("uint64", True),
|
657 |
+
("uint32", True),
|
658 |
+
("datetime", False),
|
659 |
+
("float64", True),
|
660 |
+
("float32", True),
|
661 |
+
],
|
662 |
+
indirect=["index"],
|
663 |
+
)
|
664 |
+
def test_is_numeric(self, index, expected):
|
665 |
+
assert is_any_real_numeric_dtype(index) is expected
|
666 |
+
|
667 |
+
@pytest.mark.parametrize(
|
668 |
+
"index, expected",
|
669 |
+
[
|
670 |
+
("string", True),
|
671 |
+
("bool-object", True),
|
672 |
+
("bool-dtype", False),
|
673 |
+
("categorical", False),
|
674 |
+
("int64", False),
|
675 |
+
("int32", False),
|
676 |
+
("uint64", False),
|
677 |
+
("uint32", False),
|
678 |
+
("datetime", False),
|
679 |
+
("float64", False),
|
680 |
+
("float32", False),
|
681 |
+
],
|
682 |
+
indirect=["index"],
|
683 |
+
)
|
684 |
+
def test_is_object(self, index, expected, using_infer_string):
|
685 |
+
if using_infer_string and index.dtype == "string" and expected:
|
686 |
+
expected = False
|
687 |
+
assert is_object_dtype(index) is expected
|
688 |
+
|
689 |
+
def test_summary(self, index):
|
690 |
+
index._summary()
|
691 |
+
|
692 |
+
def test_format_bug(self):
|
693 |
+
# GH 14626
|
694 |
+
# windows has different precision on datetime.datetime.now (it doesn't
|
695 |
+
# include us since the default for Timestamp shows these but Index
|
696 |
+
# formatting does not we are skipping)
|
697 |
+
now = datetime.now()
|
698 |
+
msg = r"Index\.format is deprecated"
|
699 |
+
|
700 |
+
if not str(now).endswith("000"):
|
701 |
+
index = Index([now])
|
702 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
703 |
+
formatted = index.format()
|
704 |
+
expected = [str(index[0])]
|
705 |
+
assert formatted == expected
|
706 |
+
|
707 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
708 |
+
Index([]).format()
|
709 |
+
|
710 |
+
@pytest.mark.parametrize("vals", [[1, 2.0 + 3.0j, 4.0], ["a", "b", "c"]])
|
711 |
+
def test_format_missing(self, vals, nulls_fixture):
|
712 |
+
# 2845
|
713 |
+
vals = list(vals) # Copy for each iteration
|
714 |
+
vals.append(nulls_fixture)
|
715 |
+
index = Index(vals, dtype=object)
|
716 |
+
# TODO: case with complex dtype?
|
717 |
+
|
718 |
+
msg = r"Index\.format is deprecated"
|
719 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
720 |
+
formatted = index.format()
|
721 |
+
null_repr = "NaN" if isinstance(nulls_fixture, float) else str(nulls_fixture)
|
722 |
+
expected = [str(index[0]), str(index[1]), str(index[2]), null_repr]
|
723 |
+
|
724 |
+
assert formatted == expected
|
725 |
+
assert index[3] is nulls_fixture
|
726 |
+
|
727 |
+
@pytest.mark.parametrize("op", ["any", "all"])
|
728 |
+
def test_logical_compat(self, op, simple_index):
|
729 |
+
index = simple_index
|
730 |
+
left = getattr(index, op)()
|
731 |
+
assert left == getattr(index.values, op)()
|
732 |
+
right = getattr(index.to_series(), op)()
|
733 |
+
# left might not match right exactly in e.g. string cases where the
|
734 |
+
# because we use np.any/all instead of .any/all
|
735 |
+
assert bool(left) == bool(right)
|
736 |
+
|
737 |
+
@pytest.mark.parametrize(
|
738 |
+
"index", ["string", "int64", "int32", "float64", "float32"], indirect=True
|
739 |
+
)
|
740 |
+
def test_drop_by_str_label(self, index):
|
741 |
+
n = len(index)
|
742 |
+
drop = index[list(range(5, 10))]
|
743 |
+
dropped = index.drop(drop)
|
744 |
+
|
745 |
+
expected = index[list(range(5)) + list(range(10, n))]
|
746 |
+
tm.assert_index_equal(dropped, expected)
|
747 |
+
|
748 |
+
dropped = index.drop(index[0])
|
749 |
+
expected = index[1:]
|
750 |
+
tm.assert_index_equal(dropped, expected)
|
751 |
+
|
752 |
+
@pytest.mark.parametrize(
|
753 |
+
"index", ["string", "int64", "int32", "float64", "float32"], indirect=True
|
754 |
+
)
|
755 |
+
@pytest.mark.parametrize("keys", [["foo", "bar"], ["1", "bar"]])
|
756 |
+
def test_drop_by_str_label_raises_missing_keys(self, index, keys):
|
757 |
+
with pytest.raises(KeyError, match=""):
|
758 |
+
index.drop(keys)
|
759 |
+
|
760 |
+
@pytest.mark.parametrize(
|
761 |
+
"index", ["string", "int64", "int32", "float64", "float32"], indirect=True
|
762 |
+
)
|
763 |
+
def test_drop_by_str_label_errors_ignore(self, index):
|
764 |
+
n = len(index)
|
765 |
+
drop = index[list(range(5, 10))]
|
766 |
+
mixed = drop.tolist() + ["foo"]
|
767 |
+
dropped = index.drop(mixed, errors="ignore")
|
768 |
+
|
769 |
+
expected = index[list(range(5)) + list(range(10, n))]
|
770 |
+
tm.assert_index_equal(dropped, expected)
|
771 |
+
|
772 |
+
dropped = index.drop(["foo", "bar"], errors="ignore")
|
773 |
+
expected = index[list(range(n))]
|
774 |
+
tm.assert_index_equal(dropped, expected)
|
775 |
+
|
776 |
+
def test_drop_by_numeric_label_loc(self):
|
777 |
+
# TODO: Parametrize numeric and str tests after self.strIndex fixture
|
778 |
+
index = Index([1, 2, 3])
|
779 |
+
dropped = index.drop(1)
|
780 |
+
expected = Index([2, 3])
|
781 |
+
|
782 |
+
tm.assert_index_equal(dropped, expected)
|
783 |
+
|
784 |
+
def test_drop_by_numeric_label_raises_missing_keys(self):
|
785 |
+
index = Index([1, 2, 3])
|
786 |
+
with pytest.raises(KeyError, match=""):
|
787 |
+
index.drop([3, 4])
|
788 |
+
|
789 |
+
@pytest.mark.parametrize(
|
790 |
+
"key,expected", [(4, Index([1, 2, 3])), ([3, 4, 5], Index([1, 2]))]
|
791 |
+
)
|
792 |
+
def test_drop_by_numeric_label_errors_ignore(self, key, expected):
|
793 |
+
index = Index([1, 2, 3])
|
794 |
+
dropped = index.drop(key, errors="ignore")
|
795 |
+
|
796 |
+
tm.assert_index_equal(dropped, expected)
|
797 |
+
|
798 |
+
@pytest.mark.parametrize(
|
799 |
+
"values",
|
800 |
+
[["a", "b", ("c", "d")], ["a", ("c", "d"), "b"], [("c", "d"), "a", "b"]],
|
801 |
+
)
|
802 |
+
@pytest.mark.parametrize("to_drop", [[("c", "d"), "a"], ["a", ("c", "d")]])
|
803 |
+
def test_drop_tuple(self, values, to_drop):
|
804 |
+
# GH 18304
|
805 |
+
index = Index(values)
|
806 |
+
expected = Index(["b"], dtype=object)
|
807 |
+
|
808 |
+
result = index.drop(to_drop)
|
809 |
+
tm.assert_index_equal(result, expected)
|
810 |
+
|
811 |
+
removed = index.drop(to_drop[0])
|
812 |
+
for drop_me in to_drop[1], [to_drop[1]]:
|
813 |
+
result = removed.drop(drop_me)
|
814 |
+
tm.assert_index_equal(result, expected)
|
815 |
+
|
816 |
+
removed = index.drop(to_drop[1])
|
817 |
+
msg = rf"\"\[{re.escape(to_drop[1].__repr__())}\] not found in axis\""
|
818 |
+
for drop_me in to_drop[1], [to_drop[1]]:
|
819 |
+
with pytest.raises(KeyError, match=msg):
|
820 |
+
removed.drop(drop_me)
|
821 |
+
|
822 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
823 |
+
def test_drop_with_duplicates_in_index(self, index):
|
824 |
+
# GH38051
|
825 |
+
if len(index) == 0 or isinstance(index, MultiIndex):
|
826 |
+
pytest.skip("Test doesn't make sense for empty MultiIndex")
|
827 |
+
if isinstance(index, IntervalIndex) and not IS64:
|
828 |
+
pytest.skip("Cannot test IntervalIndex with int64 dtype on 32 bit platform")
|
829 |
+
index = index.unique().repeat(2)
|
830 |
+
expected = index[2:]
|
831 |
+
result = index.drop(index[0])
|
832 |
+
tm.assert_index_equal(result, expected)
|
833 |
+
|
834 |
+
@pytest.mark.parametrize(
|
835 |
+
"attr",
|
836 |
+
[
|
837 |
+
"is_monotonic_increasing",
|
838 |
+
"is_monotonic_decreasing",
|
839 |
+
"_is_strictly_monotonic_increasing",
|
840 |
+
"_is_strictly_monotonic_decreasing",
|
841 |
+
],
|
842 |
+
)
|
843 |
+
def test_is_monotonic_incomparable(self, attr):
|
844 |
+
index = Index([5, datetime.now(), 7])
|
845 |
+
assert not getattr(index, attr)
|
846 |
+
|
847 |
+
@pytest.mark.parametrize("values", [["foo", "bar", "quux"], {"foo", "bar", "quux"}])
|
848 |
+
@pytest.mark.parametrize(
|
849 |
+
"index,expected",
|
850 |
+
[
|
851 |
+
(Index(["qux", "baz", "foo", "bar"]), np.array([False, False, True, True])),
|
852 |
+
(Index([]), np.array([], dtype=bool)), # empty
|
853 |
+
],
|
854 |
+
)
|
855 |
+
def test_isin(self, values, index, expected):
|
856 |
+
result = index.isin(values)
|
857 |
+
tm.assert_numpy_array_equal(result, expected)
|
858 |
+
|
859 |
+
def test_isin_nan_common_object(
|
860 |
+
self, nulls_fixture, nulls_fixture2, using_infer_string
|
861 |
+
):
|
862 |
+
# Test cartesian product of null fixtures and ensure that we don't
|
863 |
+
# mangle the various types (save a corner case with PyPy)
|
864 |
+
idx = Index(["a", nulls_fixture])
|
865 |
+
|
866 |
+
# all nans are the same
|
867 |
+
if (
|
868 |
+
isinstance(nulls_fixture, float)
|
869 |
+
and isinstance(nulls_fixture2, float)
|
870 |
+
and math.isnan(nulls_fixture)
|
871 |
+
and math.isnan(nulls_fixture2)
|
872 |
+
):
|
873 |
+
tm.assert_numpy_array_equal(
|
874 |
+
idx.isin([nulls_fixture2]),
|
875 |
+
np.array([False, True]),
|
876 |
+
)
|
877 |
+
|
878 |
+
elif nulls_fixture is nulls_fixture2: # should preserve NA type
|
879 |
+
tm.assert_numpy_array_equal(
|
880 |
+
idx.isin([nulls_fixture2]),
|
881 |
+
np.array([False, True]),
|
882 |
+
)
|
883 |
+
|
884 |
+
elif using_infer_string and idx.dtype == "string":
|
885 |
+
tm.assert_numpy_array_equal(
|
886 |
+
idx.isin([nulls_fixture2]),
|
887 |
+
np.array([False, True]),
|
888 |
+
)
|
889 |
+
|
890 |
+
else:
|
891 |
+
tm.assert_numpy_array_equal(
|
892 |
+
idx.isin([nulls_fixture2]),
|
893 |
+
np.array([False, False]),
|
894 |
+
)
|
895 |
+
|
896 |
+
def test_isin_nan_common_float64(self, nulls_fixture, float_numpy_dtype):
|
897 |
+
dtype = float_numpy_dtype
|
898 |
+
|
899 |
+
if nulls_fixture is pd.NaT or nulls_fixture is pd.NA:
|
900 |
+
# Check 1) that we cannot construct a float64 Index with this value
|
901 |
+
# and 2) that with an NaN we do not have .isin(nulls_fixture)
|
902 |
+
msg = (
|
903 |
+
r"float\(\) argument must be a string or a (real )?number, "
|
904 |
+
f"not {repr(type(nulls_fixture).__name__)}"
|
905 |
+
)
|
906 |
+
with pytest.raises(TypeError, match=msg):
|
907 |
+
Index([1.0, nulls_fixture], dtype=dtype)
|
908 |
+
|
909 |
+
idx = Index([1.0, np.nan], dtype=dtype)
|
910 |
+
assert not idx.isin([nulls_fixture]).any()
|
911 |
+
return
|
912 |
+
|
913 |
+
idx = Index([1.0, nulls_fixture], dtype=dtype)
|
914 |
+
res = idx.isin([np.nan])
|
915 |
+
tm.assert_numpy_array_equal(res, np.array([False, True]))
|
916 |
+
|
917 |
+
# we cannot compare NaT with NaN
|
918 |
+
res = idx.isin([pd.NaT])
|
919 |
+
tm.assert_numpy_array_equal(res, np.array([False, False]))
|
920 |
+
|
921 |
+
@pytest.mark.parametrize("level", [0, -1])
|
922 |
+
@pytest.mark.parametrize(
|
923 |
+
"index",
|
924 |
+
[
|
925 |
+
Index(["qux", "baz", "foo", "bar"]),
|
926 |
+
Index([1.0, 2.0, 3.0, 4.0], dtype=np.float64),
|
927 |
+
],
|
928 |
+
)
|
929 |
+
def test_isin_level_kwarg(self, level, index):
|
930 |
+
values = index.tolist()[-2:] + ["nonexisting"]
|
931 |
+
|
932 |
+
expected = np.array([False, False, True, True])
|
933 |
+
tm.assert_numpy_array_equal(expected, index.isin(values, level=level))
|
934 |
+
|
935 |
+
index.name = "foobar"
|
936 |
+
tm.assert_numpy_array_equal(expected, index.isin(values, level="foobar"))
|
937 |
+
|
938 |
+
def test_isin_level_kwarg_bad_level_raises(self, index):
|
939 |
+
for level in [10, index.nlevels, -(index.nlevels + 1)]:
|
940 |
+
with pytest.raises(IndexError, match="Too many levels"):
|
941 |
+
index.isin([], level=level)
|
942 |
+
|
943 |
+
@pytest.mark.parametrize("label", [1.0, "foobar", "xyzzy", np.nan])
|
944 |
+
def test_isin_level_kwarg_bad_label_raises(self, label, index):
|
945 |
+
if isinstance(index, MultiIndex):
|
946 |
+
index = index.rename(["foo", "bar"] + index.names[2:])
|
947 |
+
msg = f"'Level {label} not found'"
|
948 |
+
else:
|
949 |
+
index = index.rename("foo")
|
950 |
+
msg = rf"Requested level \({label}\) does not match index name \(foo\)"
|
951 |
+
with pytest.raises(KeyError, match=msg):
|
952 |
+
index.isin([], level=label)
|
953 |
+
|
954 |
+
@pytest.mark.parametrize("empty", [[], Series(dtype=object), np.array([])])
|
955 |
+
def test_isin_empty(self, empty):
|
956 |
+
# see gh-16991
|
957 |
+
index = Index(["a", "b"])
|
958 |
+
expected = np.array([False, False])
|
959 |
+
|
960 |
+
result = index.isin(empty)
|
961 |
+
tm.assert_numpy_array_equal(expected, result)
|
962 |
+
|
963 |
+
@td.skip_if_no("pyarrow")
|
964 |
+
def test_isin_arrow_string_null(self):
|
965 |
+
# GH#55821
|
966 |
+
index = Index(["a", "b"], dtype="string[pyarrow_numpy]")
|
967 |
+
result = index.isin([None])
|
968 |
+
expected = np.array([False, False])
|
969 |
+
tm.assert_numpy_array_equal(result, expected)
|
970 |
+
|
971 |
+
@pytest.mark.parametrize(
|
972 |
+
"values",
|
973 |
+
[
|
974 |
+
[1, 2, 3, 4],
|
975 |
+
[1.0, 2.0, 3.0, 4.0],
|
976 |
+
[True, True, True, True],
|
977 |
+
["foo", "bar", "baz", "qux"],
|
978 |
+
date_range("2018-01-01", freq="D", periods=4),
|
979 |
+
],
|
980 |
+
)
|
981 |
+
def test_boolean_cmp(self, values):
|
982 |
+
index = Index(values)
|
983 |
+
result = index == values
|
984 |
+
expected = np.array([True, True, True, True], dtype=bool)
|
985 |
+
|
986 |
+
tm.assert_numpy_array_equal(result, expected)
|
987 |
+
|
988 |
+
@pytest.mark.parametrize("index", ["string"], indirect=True)
|
989 |
+
@pytest.mark.parametrize("name,level", [(None, 0), ("a", "a")])
|
990 |
+
def test_get_level_values(self, index, name, level):
|
991 |
+
expected = index.copy()
|
992 |
+
if name:
|
993 |
+
expected.name = name
|
994 |
+
|
995 |
+
result = expected.get_level_values(level)
|
996 |
+
tm.assert_index_equal(result, expected)
|
997 |
+
|
998 |
+
def test_slice_keep_name(self):
|
999 |
+
index = Index(["a", "b"], name="asdf")
|
1000 |
+
assert index.name == index[1:].name
|
1001 |
+
|
1002 |
+
@pytest.mark.parametrize(
|
1003 |
+
"index",
|
1004 |
+
[
|
1005 |
+
"string",
|
1006 |
+
"datetime",
|
1007 |
+
"int64",
|
1008 |
+
"int32",
|
1009 |
+
"uint64",
|
1010 |
+
"uint32",
|
1011 |
+
"float64",
|
1012 |
+
"float32",
|
1013 |
+
],
|
1014 |
+
indirect=True,
|
1015 |
+
)
|
1016 |
+
def test_join_self(self, index, join_type):
|
1017 |
+
result = index.join(index, how=join_type)
|
1018 |
+
expected = index
|
1019 |
+
if join_type == "outer":
|
1020 |
+
expected = expected.sort_values()
|
1021 |
+
tm.assert_index_equal(result, expected)
|
1022 |
+
|
1023 |
+
@pytest.mark.parametrize("method", ["strip", "rstrip", "lstrip"])
|
1024 |
+
def test_str_attribute(self, method):
|
1025 |
+
# GH9068
|
1026 |
+
index = Index([" jack", "jill ", " jesse ", "frank"])
|
1027 |
+
expected = Index([getattr(str, method)(x) for x in index.values])
|
1028 |
+
|
1029 |
+
result = getattr(index.str, method)()
|
1030 |
+
tm.assert_index_equal(result, expected)
|
1031 |
+
|
1032 |
+
@pytest.mark.parametrize(
|
1033 |
+
"index",
|
1034 |
+
[
|
1035 |
+
Index(range(5)),
|
1036 |
+
date_range("2020-01-01", periods=10),
|
1037 |
+
MultiIndex.from_tuples([("foo", "1"), ("bar", "3")]),
|
1038 |
+
period_range(start="2000", end="2010", freq="Y"),
|
1039 |
+
],
|
1040 |
+
)
|
1041 |
+
def test_str_attribute_raises(self, index):
|
1042 |
+
with pytest.raises(AttributeError, match="only use .str accessor"):
|
1043 |
+
index.str.repeat(2)
|
1044 |
+
|
1045 |
+
@pytest.mark.parametrize(
|
1046 |
+
"expand,expected",
|
1047 |
+
[
|
1048 |
+
(None, Index([["a", "b", "c"], ["d", "e"], ["f"]])),
|
1049 |
+
(False, Index([["a", "b", "c"], ["d", "e"], ["f"]])),
|
1050 |
+
(
|
1051 |
+
True,
|
1052 |
+
MultiIndex.from_tuples(
|
1053 |
+
[("a", "b", "c"), ("d", "e", np.nan), ("f", np.nan, np.nan)]
|
1054 |
+
),
|
1055 |
+
),
|
1056 |
+
],
|
1057 |
+
)
|
1058 |
+
def test_str_split(self, expand, expected):
|
1059 |
+
index = Index(["a b c", "d e", "f"])
|
1060 |
+
if expand is not None:
|
1061 |
+
result = index.str.split(expand=expand)
|
1062 |
+
else:
|
1063 |
+
result = index.str.split()
|
1064 |
+
|
1065 |
+
tm.assert_index_equal(result, expected)
|
1066 |
+
|
1067 |
+
def test_str_bool_return(self):
|
1068 |
+
# test boolean case, should return np.array instead of boolean Index
|
1069 |
+
index = Index(["a1", "a2", "b1", "b2"])
|
1070 |
+
result = index.str.startswith("a")
|
1071 |
+
expected = np.array([True, True, False, False])
|
1072 |
+
|
1073 |
+
tm.assert_numpy_array_equal(result, expected)
|
1074 |
+
assert isinstance(result, np.ndarray)
|
1075 |
+
|
1076 |
+
def test_str_bool_series_indexing(self):
|
1077 |
+
index = Index(["a1", "a2", "b1", "b2"])
|
1078 |
+
s = Series(range(4), index=index)
|
1079 |
+
|
1080 |
+
result = s[s.index.str.startswith("a")]
|
1081 |
+
expected = Series(range(2), index=["a1", "a2"])
|
1082 |
+
tm.assert_series_equal(result, expected)
|
1083 |
+
|
1084 |
+
@pytest.mark.parametrize(
|
1085 |
+
"index,expected", [(Index(list("abcd")), True), (Index(range(4)), False)]
|
1086 |
+
)
|
1087 |
+
def test_tab_completion(self, index, expected):
|
1088 |
+
# GH 9910
|
1089 |
+
result = "str" in dir(index)
|
1090 |
+
assert result == expected
|
1091 |
+
|
1092 |
+
def test_indexing_doesnt_change_class(self):
|
1093 |
+
index = Index([1, 2, 3, "a", "b", "c"])
|
1094 |
+
|
1095 |
+
assert index[1:3].identical(Index([2, 3], dtype=np.object_))
|
1096 |
+
assert index[[0, 1]].identical(Index([1, 2], dtype=np.object_))
|
1097 |
+
|
1098 |
+
def test_outer_join_sort(self):
|
1099 |
+
left_index = Index(np.random.default_rng(2).permutation(15))
|
1100 |
+
right_index = date_range("2020-01-01", periods=10)
|
1101 |
+
|
1102 |
+
with tm.assert_produces_warning(RuntimeWarning):
|
1103 |
+
result = left_index.join(right_index, how="outer")
|
1104 |
+
|
1105 |
+
with tm.assert_produces_warning(RuntimeWarning):
|
1106 |
+
expected = left_index.astype(object).union(right_index.astype(object))
|
1107 |
+
|
1108 |
+
tm.assert_index_equal(result, expected)
|
1109 |
+
|
1110 |
+
def test_take_fill_value(self):
|
1111 |
+
# GH 12631
|
1112 |
+
index = Index(list("ABC"), name="xxx")
|
1113 |
+
result = index.take(np.array([1, 0, -1]))
|
1114 |
+
expected = Index(list("BAC"), name="xxx")
|
1115 |
+
tm.assert_index_equal(result, expected)
|
1116 |
+
|
1117 |
+
# fill_value
|
1118 |
+
result = index.take(np.array([1, 0, -1]), fill_value=True)
|
1119 |
+
expected = Index(["B", "A", np.nan], name="xxx")
|
1120 |
+
tm.assert_index_equal(result, expected)
|
1121 |
+
|
1122 |
+
# allow_fill=False
|
1123 |
+
result = index.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True)
|
1124 |
+
expected = Index(["B", "A", "C"], name="xxx")
|
1125 |
+
tm.assert_index_equal(result, expected)
|
1126 |
+
|
1127 |
+
def test_take_fill_value_none_raises(self):
|
1128 |
+
index = Index(list("ABC"), name="xxx")
|
1129 |
+
msg = (
|
1130 |
+
"When allow_fill=True and fill_value is not None, "
|
1131 |
+
"all indices must be >= -1"
|
1132 |
+
)
|
1133 |
+
|
1134 |
+
with pytest.raises(ValueError, match=msg):
|
1135 |
+
index.take(np.array([1, 0, -2]), fill_value=True)
|
1136 |
+
with pytest.raises(ValueError, match=msg):
|
1137 |
+
index.take(np.array([1, 0, -5]), fill_value=True)
|
1138 |
+
|
1139 |
+
def test_take_bad_bounds_raises(self):
|
1140 |
+
index = Index(list("ABC"), name="xxx")
|
1141 |
+
with pytest.raises(IndexError, match="out of bounds"):
|
1142 |
+
index.take(np.array([1, -5]))
|
1143 |
+
|
1144 |
+
@pytest.mark.parametrize("name", [None, "foobar"])
|
1145 |
+
@pytest.mark.parametrize(
|
1146 |
+
"labels",
|
1147 |
+
[
|
1148 |
+
[],
|
1149 |
+
np.array([]),
|
1150 |
+
["A", "B", "C"],
|
1151 |
+
["C", "B", "A"],
|
1152 |
+
np.array(["A", "B", "C"]),
|
1153 |
+
np.array(["C", "B", "A"]),
|
1154 |
+
# Must preserve name even if dtype changes
|
1155 |
+
date_range("20130101", periods=3).values,
|
1156 |
+
date_range("20130101", periods=3).tolist(),
|
1157 |
+
],
|
1158 |
+
)
|
1159 |
+
def test_reindex_preserves_name_if_target_is_list_or_ndarray(self, name, labels):
|
1160 |
+
# GH6552
|
1161 |
+
index = Index([0, 1, 2])
|
1162 |
+
index.name = name
|
1163 |
+
assert index.reindex(labels)[0].name == name
|
1164 |
+
|
1165 |
+
@pytest.mark.parametrize("labels", [[], np.array([]), np.array([], dtype=np.int64)])
|
1166 |
+
def test_reindex_preserves_type_if_target_is_empty_list_or_array(self, labels):
|
1167 |
+
# GH7774
|
1168 |
+
index = Index(list("abc"))
|
1169 |
+
assert index.reindex(labels)[0].dtype.type == index.dtype.type
|
1170 |
+
|
1171 |
+
@pytest.mark.parametrize(
|
1172 |
+
"labels,dtype",
|
1173 |
+
[
|
1174 |
+
(DatetimeIndex([]), np.datetime64),
|
1175 |
+
],
|
1176 |
+
)
|
1177 |
+
def test_reindex_doesnt_preserve_type_if_target_is_empty_index(self, labels, dtype):
|
1178 |
+
# GH7774
|
1179 |
+
index = Index(list("abc"))
|
1180 |
+
assert index.reindex(labels)[0].dtype.type == dtype
|
1181 |
+
|
1182 |
+
def test_reindex_doesnt_preserve_type_if_target_is_empty_index_numeric(
|
1183 |
+
self, any_real_numpy_dtype
|
1184 |
+
):
|
1185 |
+
# GH7774
|
1186 |
+
dtype = any_real_numpy_dtype
|
1187 |
+
index = Index(list("abc"))
|
1188 |
+
labels = Index([], dtype=dtype)
|
1189 |
+
assert index.reindex(labels)[0].dtype == dtype
|
1190 |
+
|
1191 |
+
def test_reindex_no_type_preserve_target_empty_mi(self):
|
1192 |
+
index = Index(list("abc"))
|
1193 |
+
result = index.reindex(
|
1194 |
+
MultiIndex([Index([], np.int64), Index([], np.float64)], [[], []])
|
1195 |
+
)[0]
|
1196 |
+
assert result.levels[0].dtype.type == np.int64
|
1197 |
+
assert result.levels[1].dtype.type == np.float64
|
1198 |
+
|
1199 |
+
def test_reindex_ignoring_level(self):
|
1200 |
+
# GH#35132
|
1201 |
+
idx = Index([1, 2, 3], name="x")
|
1202 |
+
idx2 = Index([1, 2, 3, 4], name="x")
|
1203 |
+
expected = Index([1, 2, 3, 4], name="x")
|
1204 |
+
result, _ = idx.reindex(idx2, level="x")
|
1205 |
+
tm.assert_index_equal(result, expected)
|
1206 |
+
|
1207 |
+
def test_groupby(self):
|
1208 |
+
index = Index(range(5))
|
1209 |
+
result = index.groupby(np.array([1, 1, 2, 2, 2]))
|
1210 |
+
expected = {1: Index([0, 1]), 2: Index([2, 3, 4])}
|
1211 |
+
|
1212 |
+
tm.assert_dict_equal(result, expected)
|
1213 |
+
|
1214 |
+
@pytest.mark.parametrize(
|
1215 |
+
"mi,expected",
|
1216 |
+
[
|
1217 |
+
(MultiIndex.from_tuples([(1, 2), (4, 5)]), np.array([True, True])),
|
1218 |
+
(MultiIndex.from_tuples([(1, 2), (4, 6)]), np.array([True, False])),
|
1219 |
+
],
|
1220 |
+
)
|
1221 |
+
def test_equals_op_multiindex(self, mi, expected):
|
1222 |
+
# GH9785
|
1223 |
+
# test comparisons of multiindex
|
1224 |
+
df = DataFrame(
|
1225 |
+
[3, 6],
|
1226 |
+
columns=["c"],
|
1227 |
+
index=MultiIndex.from_arrays([[1, 4], [2, 5]], names=["a", "b"]),
|
1228 |
+
)
|
1229 |
+
|
1230 |
+
result = df.index == mi
|
1231 |
+
tm.assert_numpy_array_equal(result, expected)
|
1232 |
+
|
1233 |
+
def test_equals_op_multiindex_identify(self):
|
1234 |
+
df = DataFrame(
|
1235 |
+
[3, 6],
|
1236 |
+
columns=["c"],
|
1237 |
+
index=MultiIndex.from_arrays([[1, 4], [2, 5]], names=["a", "b"]),
|
1238 |
+
)
|
1239 |
+
|
1240 |
+
result = df.index == df.index
|
1241 |
+
expected = np.array([True, True])
|
1242 |
+
tm.assert_numpy_array_equal(result, expected)
|
1243 |
+
|
1244 |
+
@pytest.mark.parametrize(
|
1245 |
+
"index",
|
1246 |
+
[
|
1247 |
+
MultiIndex.from_tuples([(1, 2), (4, 5), (8, 9)]),
|
1248 |
+
Index(["foo", "bar", "baz"]),
|
1249 |
+
],
|
1250 |
+
)
|
1251 |
+
def test_equals_op_mismatched_multiindex_raises(self, index):
|
1252 |
+
df = DataFrame(
|
1253 |
+
[3, 6],
|
1254 |
+
columns=["c"],
|
1255 |
+
index=MultiIndex.from_arrays([[1, 4], [2, 5]], names=["a", "b"]),
|
1256 |
+
)
|
1257 |
+
|
1258 |
+
with pytest.raises(ValueError, match="Lengths must match"):
|
1259 |
+
df.index == index
|
1260 |
+
|
1261 |
+
def test_equals_op_index_vs_mi_same_length(self, using_infer_string):
|
1262 |
+
mi = MultiIndex.from_tuples([(1, 2), (4, 5), (8, 9)])
|
1263 |
+
index = Index(["foo", "bar", "baz"])
|
1264 |
+
|
1265 |
+
result = mi == index
|
1266 |
+
expected = np.array([False, False, False])
|
1267 |
+
tm.assert_numpy_array_equal(result, expected)
|
1268 |
+
|
1269 |
+
@pytest.mark.parametrize(
|
1270 |
+
"dt_conv, arg",
|
1271 |
+
[
|
1272 |
+
(pd.to_datetime, ["2000-01-01", "2000-01-02"]),
|
1273 |
+
(pd.to_timedelta, ["01:02:03", "01:02:04"]),
|
1274 |
+
],
|
1275 |
+
)
|
1276 |
+
def test_dt_conversion_preserves_name(self, dt_conv, arg):
|
1277 |
+
# GH 10875
|
1278 |
+
index = Index(arg, name="label")
|
1279 |
+
assert index.name == dt_conv(index).name
|
1280 |
+
|
1281 |
+
def test_cached_properties_not_settable(self):
|
1282 |
+
index = Index([1, 2, 3])
|
1283 |
+
with pytest.raises(AttributeError, match="Can't set attribute"):
|
1284 |
+
index.is_unique = False
|
1285 |
+
|
1286 |
+
def test_tab_complete_warning(self, ip):
|
1287 |
+
# https://github.com/pandas-dev/pandas/issues/16409
|
1288 |
+
pytest.importorskip("IPython", minversion="6.0.0")
|
1289 |
+
from IPython.core.completer import provisionalcompleter
|
1290 |
+
|
1291 |
+
code = "import pandas as pd; idx = pd.Index([1, 2])"
|
1292 |
+
ip.run_cell(code)
|
1293 |
+
|
1294 |
+
# GH 31324 newer jedi version raises Deprecation warning;
|
1295 |
+
# appears resolved 2021-02-02
|
1296 |
+
with tm.assert_produces_warning(None, raise_on_extra_warnings=False):
|
1297 |
+
with provisionalcompleter("ignore"):
|
1298 |
+
list(ip.Completer.completions("idx.", 4))
|
1299 |
+
|
1300 |
+
def test_contains_method_removed(self, index):
|
1301 |
+
# GH#30103 method removed for all types except IntervalIndex
|
1302 |
+
if isinstance(index, IntervalIndex):
|
1303 |
+
index.contains(1)
|
1304 |
+
else:
|
1305 |
+
msg = f"'{type(index).__name__}' object has no attribute 'contains'"
|
1306 |
+
with pytest.raises(AttributeError, match=msg):
|
1307 |
+
index.contains(1)
|
1308 |
+
|
1309 |
+
def test_sortlevel(self):
|
1310 |
+
index = Index([5, 4, 3, 2, 1])
|
1311 |
+
with pytest.raises(Exception, match="ascending must be a single bool value or"):
|
1312 |
+
index.sortlevel(ascending="True")
|
1313 |
+
|
1314 |
+
with pytest.raises(
|
1315 |
+
Exception, match="ascending must be a list of bool values of length 1"
|
1316 |
+
):
|
1317 |
+
index.sortlevel(ascending=[True, True])
|
1318 |
+
|
1319 |
+
with pytest.raises(Exception, match="ascending must be a bool value"):
|
1320 |
+
index.sortlevel(ascending=["True"])
|
1321 |
+
|
1322 |
+
expected = Index([1, 2, 3, 4, 5])
|
1323 |
+
result = index.sortlevel(ascending=[True])
|
1324 |
+
tm.assert_index_equal(result[0], expected)
|
1325 |
+
|
1326 |
+
expected = Index([1, 2, 3, 4, 5])
|
1327 |
+
result = index.sortlevel(ascending=True)
|
1328 |
+
tm.assert_index_equal(result[0], expected)
|
1329 |
+
|
1330 |
+
expected = Index([5, 4, 3, 2, 1])
|
1331 |
+
result = index.sortlevel(ascending=False)
|
1332 |
+
tm.assert_index_equal(result[0], expected)
|
1333 |
+
|
1334 |
+
def test_sortlevel_na_position(self):
|
1335 |
+
# GH#51612
|
1336 |
+
idx = Index([1, np.nan])
|
1337 |
+
result = idx.sortlevel(na_position="first")[0]
|
1338 |
+
expected = Index([np.nan, 1])
|
1339 |
+
tm.assert_index_equal(result, expected)
|
1340 |
+
|
1341 |
+
@pytest.mark.parametrize(
|
1342 |
+
"periods, expected_results",
|
1343 |
+
[
|
1344 |
+
(1, [np.nan, 10, 10, 10, 10]),
|
1345 |
+
(2, [np.nan, np.nan, 20, 20, 20]),
|
1346 |
+
(3, [np.nan, np.nan, np.nan, 30, 30]),
|
1347 |
+
],
|
1348 |
+
)
|
1349 |
+
def test_index_diff(self, periods, expected_results):
|
1350 |
+
# GH#19708
|
1351 |
+
idx = Index([10, 20, 30, 40, 50])
|
1352 |
+
result = idx.diff(periods)
|
1353 |
+
expected = Index(expected_results)
|
1354 |
+
|
1355 |
+
tm.assert_index_equal(result, expected)
|
1356 |
+
|
1357 |
+
@pytest.mark.parametrize(
|
1358 |
+
"decimals, expected_results",
|
1359 |
+
[
|
1360 |
+
(0, [1.0, 2.0, 3.0]),
|
1361 |
+
(1, [1.2, 2.3, 3.5]),
|
1362 |
+
(2, [1.23, 2.35, 3.46]),
|
1363 |
+
],
|
1364 |
+
)
|
1365 |
+
def test_index_round(self, decimals, expected_results):
|
1366 |
+
# GH#19708
|
1367 |
+
idx = Index([1.234, 2.345, 3.456])
|
1368 |
+
result = idx.round(decimals)
|
1369 |
+
expected = Index(expected_results)
|
1370 |
+
|
1371 |
+
tm.assert_index_equal(result, expected)
|
1372 |
+
|
1373 |
+
|
1374 |
+
class TestMixedIntIndex:
|
1375 |
+
# Mostly the tests from common.py for which the results differ
|
1376 |
+
# in py2 and py3 because ints and strings are uncomparable in py3
|
1377 |
+
# (GH 13514)
|
1378 |
+
@pytest.fixture
|
1379 |
+
def simple_index(self) -> Index:
|
1380 |
+
return Index([0, "a", 1, "b", 2, "c"])
|
1381 |
+
|
1382 |
+
def test_argsort(self, simple_index):
|
1383 |
+
index = simple_index
|
1384 |
+
with pytest.raises(TypeError, match="'>|<' not supported"):
|
1385 |
+
index.argsort()
|
1386 |
+
|
1387 |
+
def test_numpy_argsort(self, simple_index):
|
1388 |
+
index = simple_index
|
1389 |
+
with pytest.raises(TypeError, match="'>|<' not supported"):
|
1390 |
+
np.argsort(index)
|
1391 |
+
|
1392 |
+
def test_copy_name(self, simple_index):
|
1393 |
+
# Check that "name" argument passed at initialization is honoured
|
1394 |
+
# GH12309
|
1395 |
+
index = simple_index
|
1396 |
+
|
1397 |
+
first = type(index)(index, copy=True, name="mario")
|
1398 |
+
second = type(first)(first, copy=False)
|
1399 |
+
|
1400 |
+
# Even though "copy=False", we want a new object.
|
1401 |
+
assert first is not second
|
1402 |
+
tm.assert_index_equal(first, second)
|
1403 |
+
|
1404 |
+
assert first.name == "mario"
|
1405 |
+
assert second.name == "mario"
|
1406 |
+
|
1407 |
+
s1 = Series(2, index=first)
|
1408 |
+
s2 = Series(3, index=second[:-1])
|
1409 |
+
|
1410 |
+
s3 = s1 * s2
|
1411 |
+
|
1412 |
+
assert s3.index.name == "mario"
|
1413 |
+
|
1414 |
+
def test_copy_name2(self):
|
1415 |
+
# Check that adding a "name" parameter to the copy is honored
|
1416 |
+
# GH14302
|
1417 |
+
index = Index([1, 2], name="MyName")
|
1418 |
+
index1 = index.copy()
|
1419 |
+
|
1420 |
+
tm.assert_index_equal(index, index1)
|
1421 |
+
|
1422 |
+
index2 = index.copy(name="NewName")
|
1423 |
+
tm.assert_index_equal(index, index2, check_names=False)
|
1424 |
+
assert index.name == "MyName"
|
1425 |
+
assert index2.name == "NewName"
|
1426 |
+
|
1427 |
+
def test_unique_na(self):
|
1428 |
+
idx = Index([2, np.nan, 2, 1], name="my_index")
|
1429 |
+
expected = Index([2, np.nan, 1], name="my_index")
|
1430 |
+
result = idx.unique()
|
1431 |
+
tm.assert_index_equal(result, expected)
|
1432 |
+
|
1433 |
+
def test_logical_compat(self, simple_index):
|
1434 |
+
index = simple_index
|
1435 |
+
assert index.all() == index.values.all()
|
1436 |
+
assert index.any() == index.values.any()
|
1437 |
+
|
1438 |
+
@pytest.mark.parametrize("how", ["any", "all"])
|
1439 |
+
@pytest.mark.parametrize("dtype", [None, object, "category"])
|
1440 |
+
@pytest.mark.parametrize(
|
1441 |
+
"vals,expected",
|
1442 |
+
[
|
1443 |
+
([1, 2, 3], [1, 2, 3]),
|
1444 |
+
([1.0, 2.0, 3.0], [1.0, 2.0, 3.0]),
|
1445 |
+
([1.0, 2.0, np.nan, 3.0], [1.0, 2.0, 3.0]),
|
1446 |
+
(["A", "B", "C"], ["A", "B", "C"]),
|
1447 |
+
(["A", np.nan, "B", "C"], ["A", "B", "C"]),
|
1448 |
+
],
|
1449 |
+
)
|
1450 |
+
def test_dropna(self, how, dtype, vals, expected):
|
1451 |
+
# GH 6194
|
1452 |
+
index = Index(vals, dtype=dtype)
|
1453 |
+
result = index.dropna(how=how)
|
1454 |
+
expected = Index(expected, dtype=dtype)
|
1455 |
+
tm.assert_index_equal(result, expected)
|
1456 |
+
|
1457 |
+
@pytest.mark.parametrize("how", ["any", "all"])
|
1458 |
+
@pytest.mark.parametrize(
|
1459 |
+
"index,expected",
|
1460 |
+
[
|
1461 |
+
(
|
1462 |
+
DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03"]),
|
1463 |
+
DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03"]),
|
1464 |
+
),
|
1465 |
+
(
|
1466 |
+
DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03", pd.NaT]),
|
1467 |
+
DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03"]),
|
1468 |
+
),
|
1469 |
+
(
|
1470 |
+
TimedeltaIndex(["1 days", "2 days", "3 days"]),
|
1471 |
+
TimedeltaIndex(["1 days", "2 days", "3 days"]),
|
1472 |
+
),
|
1473 |
+
(
|
1474 |
+
TimedeltaIndex([pd.NaT, "1 days", "2 days", "3 days", pd.NaT]),
|
1475 |
+
TimedeltaIndex(["1 days", "2 days", "3 days"]),
|
1476 |
+
),
|
1477 |
+
(
|
1478 |
+
PeriodIndex(["2012-02", "2012-04", "2012-05"], freq="M"),
|
1479 |
+
PeriodIndex(["2012-02", "2012-04", "2012-05"], freq="M"),
|
1480 |
+
),
|
1481 |
+
(
|
1482 |
+
PeriodIndex(["2012-02", "2012-04", "NaT", "2012-05"], freq="M"),
|
1483 |
+
PeriodIndex(["2012-02", "2012-04", "2012-05"], freq="M"),
|
1484 |
+
),
|
1485 |
+
],
|
1486 |
+
)
|
1487 |
+
def test_dropna_dt_like(self, how, index, expected):
|
1488 |
+
result = index.dropna(how=how)
|
1489 |
+
tm.assert_index_equal(result, expected)
|
1490 |
+
|
1491 |
+
def test_dropna_invalid_how_raises(self):
|
1492 |
+
msg = "invalid how option: xxx"
|
1493 |
+
with pytest.raises(ValueError, match=msg):
|
1494 |
+
Index([1, 2, 3]).dropna(how="xxx")
|
1495 |
+
|
1496 |
+
@pytest.mark.parametrize(
|
1497 |
+
"index",
|
1498 |
+
[
|
1499 |
+
Index([np.nan]),
|
1500 |
+
Index([np.nan, 1]),
|
1501 |
+
Index([1, 2, np.nan]),
|
1502 |
+
Index(["a", "b", np.nan]),
|
1503 |
+
pd.to_datetime(["NaT"]),
|
1504 |
+
pd.to_datetime(["NaT", "2000-01-01"]),
|
1505 |
+
pd.to_datetime(["2000-01-01", "NaT", "2000-01-02"]),
|
1506 |
+
pd.to_timedelta(["1 day", "NaT"]),
|
1507 |
+
],
|
1508 |
+
)
|
1509 |
+
def test_is_monotonic_na(self, index):
|
1510 |
+
assert index.is_monotonic_increasing is False
|
1511 |
+
assert index.is_monotonic_decreasing is False
|
1512 |
+
assert index._is_strictly_monotonic_increasing is False
|
1513 |
+
assert index._is_strictly_monotonic_decreasing is False
|
1514 |
+
|
1515 |
+
@pytest.mark.parametrize("dtype", ["f8", "m8[ns]", "M8[us]"])
|
1516 |
+
@pytest.mark.parametrize("unique_first", [True, False])
|
1517 |
+
def test_is_monotonic_unique_na(self, dtype, unique_first):
|
1518 |
+
# GH 55755
|
1519 |
+
index = Index([None, 1, 1], dtype=dtype)
|
1520 |
+
if unique_first:
|
1521 |
+
assert index.is_unique is False
|
1522 |
+
assert index.is_monotonic_increasing is False
|
1523 |
+
assert index.is_monotonic_decreasing is False
|
1524 |
+
else:
|
1525 |
+
assert index.is_monotonic_increasing is False
|
1526 |
+
assert index.is_monotonic_decreasing is False
|
1527 |
+
assert index.is_unique is False
|
1528 |
+
|
1529 |
+
def test_int_name_format(self, frame_or_series):
|
1530 |
+
index = Index(["a", "b", "c"], name=0)
|
1531 |
+
result = frame_or_series(list(range(3)), index=index)
|
1532 |
+
assert "0" in repr(result)
|
1533 |
+
|
1534 |
+
def test_str_to_bytes_raises(self):
|
1535 |
+
# GH 26447
|
1536 |
+
index = Index([str(x) for x in range(10)])
|
1537 |
+
msg = "^'str' object cannot be interpreted as an integer$"
|
1538 |
+
with pytest.raises(TypeError, match=msg):
|
1539 |
+
bytes(index)
|
1540 |
+
|
1541 |
+
@pytest.mark.filterwarnings("ignore:elementwise comparison failed:FutureWarning")
|
1542 |
+
def test_index_with_tuple_bool(self):
|
1543 |
+
# GH34123
|
1544 |
+
# TODO: also this op right now produces FutureWarning from numpy
|
1545 |
+
# https://github.com/numpy/numpy/issues/11521
|
1546 |
+
idx = Index([("a", "b"), ("b", "c"), ("c", "a")])
|
1547 |
+
result = idx == ("c", "a")
|
1548 |
+
expected = np.array([False, False, True])
|
1549 |
+
tm.assert_numpy_array_equal(result, expected)
|
1550 |
+
|
1551 |
+
|
1552 |
+
class TestIndexUtils:
|
1553 |
+
@pytest.mark.parametrize(
|
1554 |
+
"data, names, expected",
|
1555 |
+
[
|
1556 |
+
([[1, 2, 3]], None, Index([1, 2, 3])),
|
1557 |
+
([[1, 2, 3]], ["name"], Index([1, 2, 3], name="name")),
|
1558 |
+
(
|
1559 |
+
[["a", "a"], ["c", "d"]],
|
1560 |
+
None,
|
1561 |
+
MultiIndex([["a"], ["c", "d"]], [[0, 0], [0, 1]]),
|
1562 |
+
),
|
1563 |
+
(
|
1564 |
+
[["a", "a"], ["c", "d"]],
|
1565 |
+
["L1", "L2"],
|
1566 |
+
MultiIndex([["a"], ["c", "d"]], [[0, 0], [0, 1]], names=["L1", "L2"]),
|
1567 |
+
),
|
1568 |
+
],
|
1569 |
+
)
|
1570 |
+
def test_ensure_index_from_sequences(self, data, names, expected):
|
1571 |
+
result = ensure_index_from_sequences(data, names)
|
1572 |
+
tm.assert_index_equal(result, expected)
|
1573 |
+
|
1574 |
+
def test_ensure_index_mixed_closed_intervals(self):
|
1575 |
+
# GH27172
|
1576 |
+
intervals = [
|
1577 |
+
pd.Interval(0, 1, closed="left"),
|
1578 |
+
pd.Interval(1, 2, closed="right"),
|
1579 |
+
pd.Interval(2, 3, closed="neither"),
|
1580 |
+
pd.Interval(3, 4, closed="both"),
|
1581 |
+
]
|
1582 |
+
result = ensure_index(intervals)
|
1583 |
+
expected = Index(intervals, dtype=object)
|
1584 |
+
tm.assert_index_equal(result, expected)
|
1585 |
+
|
1586 |
+
def test_ensure_index_uint64(self):
|
1587 |
+
# with both 0 and a large-uint64, np.array will infer to float64
|
1588 |
+
# https://github.com/numpy/numpy/issues/19146
|
1589 |
+
# but a more accurate choice would be uint64
|
1590 |
+
values = [0, np.iinfo(np.uint64).max]
|
1591 |
+
|
1592 |
+
result = ensure_index(values)
|
1593 |
+
assert list(result) == values
|
1594 |
+
|
1595 |
+
expected = Index(values, dtype="uint64")
|
1596 |
+
tm.assert_index_equal(result, expected)
|
1597 |
+
|
1598 |
+
def test_get_combined_index(self):
|
1599 |
+
result = _get_combined_index([])
|
1600 |
+
expected = Index([])
|
1601 |
+
tm.assert_index_equal(result, expected)
|
1602 |
+
|
1603 |
+
|
1604 |
+
@pytest.mark.parametrize(
|
1605 |
+
"opname",
|
1606 |
+
[
|
1607 |
+
"eq",
|
1608 |
+
"ne",
|
1609 |
+
"le",
|
1610 |
+
"lt",
|
1611 |
+
"ge",
|
1612 |
+
"gt",
|
1613 |
+
"add",
|
1614 |
+
"radd",
|
1615 |
+
"sub",
|
1616 |
+
"rsub",
|
1617 |
+
"mul",
|
1618 |
+
"rmul",
|
1619 |
+
"truediv",
|
1620 |
+
"rtruediv",
|
1621 |
+
"floordiv",
|
1622 |
+
"rfloordiv",
|
1623 |
+
"pow",
|
1624 |
+
"rpow",
|
1625 |
+
"mod",
|
1626 |
+
"divmod",
|
1627 |
+
],
|
1628 |
+
)
|
1629 |
+
def test_generated_op_names(opname, index):
|
1630 |
+
opname = f"__{opname}__"
|
1631 |
+
method = getattr(index, opname)
|
1632 |
+
assert method.__name__ == opname
|
1633 |
+
|
1634 |
+
|
1635 |
+
@pytest.mark.parametrize(
|
1636 |
+
"klass",
|
1637 |
+
[
|
1638 |
+
partial(CategoricalIndex, data=[1]),
|
1639 |
+
partial(DatetimeIndex, data=["2020-01-01"]),
|
1640 |
+
partial(PeriodIndex, data=["2020-01-01"]),
|
1641 |
+
partial(TimedeltaIndex, data=["1 day"]),
|
1642 |
+
partial(RangeIndex, data=range(1)),
|
1643 |
+
partial(IntervalIndex, data=[pd.Interval(0, 1)]),
|
1644 |
+
partial(Index, data=["a"], dtype=object),
|
1645 |
+
partial(MultiIndex, levels=[1], codes=[0]),
|
1646 |
+
],
|
1647 |
+
)
|
1648 |
+
def test_index_subclass_constructor_wrong_kwargs(klass):
|
1649 |
+
# GH #19348
|
1650 |
+
with pytest.raises(TypeError, match="unexpected keyword argument"):
|
1651 |
+
klass(foo="bar")
|
1652 |
+
|
1653 |
+
|
1654 |
+
def test_deprecated_fastpath():
|
1655 |
+
msg = "[Uu]nexpected keyword argument"
|
1656 |
+
with pytest.raises(TypeError, match=msg):
|
1657 |
+
Index(np.array(["a", "b"], dtype=object), name="test", fastpath=True)
|
1658 |
+
|
1659 |
+
with pytest.raises(TypeError, match=msg):
|
1660 |
+
Index(np.array([1, 2, 3], dtype="int64"), name="test", fastpath=True)
|
1661 |
+
|
1662 |
+
with pytest.raises(TypeError, match=msg):
|
1663 |
+
RangeIndex(0, 5, 2, name="test", fastpath=True)
|
1664 |
+
|
1665 |
+
with pytest.raises(TypeError, match=msg):
|
1666 |
+
CategoricalIndex(["a", "b", "c"], name="test", fastpath=True)
|
1667 |
+
|
1668 |
+
|
1669 |
+
def test_shape_of_invalid_index():
|
1670 |
+
# Pre-2.0, it was possible to create "invalid" index objects backed by
|
1671 |
+
# a multi-dimensional array (see https://github.com/pandas-dev/pandas/issues/27125
|
1672 |
+
# about this). However, as long as this is not solved in general,this test ensures
|
1673 |
+
# that the returned shape is consistent with this underlying array for
|
1674 |
+
# compat with matplotlib (see https://github.com/pandas-dev/pandas/issues/27775)
|
1675 |
+
idx = Index([0, 1, 2, 3])
|
1676 |
+
with pytest.raises(ValueError, match="Multi-dimensional indexing"):
|
1677 |
+
# GH#30588 multi-dimensional indexing deprecated
|
1678 |
+
idx[:, None]
|
1679 |
+
|
1680 |
+
|
1681 |
+
@pytest.mark.parametrize("dtype", [None, np.int64, np.uint64, np.float64])
|
1682 |
+
def test_validate_1d_input(dtype):
|
1683 |
+
# GH#27125 check that we do not have >1-dimensional input
|
1684 |
+
msg = "Index data must be 1-dimensional"
|
1685 |
+
|
1686 |
+
arr = np.arange(8).reshape(2, 2, 2)
|
1687 |
+
with pytest.raises(ValueError, match=msg):
|
1688 |
+
Index(arr, dtype=dtype)
|
1689 |
+
|
1690 |
+
df = DataFrame(arr.reshape(4, 2))
|
1691 |
+
with pytest.raises(ValueError, match=msg):
|
1692 |
+
Index(df, dtype=dtype)
|
1693 |
+
|
1694 |
+
# GH#13601 trying to assign a multi-dimensional array to an index is not allowed
|
1695 |
+
ser = Series(0, range(4))
|
1696 |
+
with pytest.raises(ValueError, match=msg):
|
1697 |
+
ser.index = np.array([[2, 3]] * 4, dtype=dtype)
|
1698 |
+
|
1699 |
+
|
1700 |
+
@pytest.mark.parametrize(
|
1701 |
+
"klass, extra_kwargs",
|
1702 |
+
[
|
1703 |
+
[Index, {}],
|
1704 |
+
*[[lambda x: Index(x, dtype=dtyp), {}] for dtyp in tm.ALL_REAL_NUMPY_DTYPES],
|
1705 |
+
[DatetimeIndex, {}],
|
1706 |
+
[TimedeltaIndex, {}],
|
1707 |
+
[PeriodIndex, {"freq": "Y"}],
|
1708 |
+
],
|
1709 |
+
)
|
1710 |
+
def test_construct_from_memoryview(klass, extra_kwargs):
|
1711 |
+
# GH 13120
|
1712 |
+
result = klass(memoryview(np.arange(2000, 2005)), **extra_kwargs)
|
1713 |
+
expected = klass(list(range(2000, 2005)), **extra_kwargs)
|
1714 |
+
tm.assert_index_equal(result, expected, exact=True)
|
1715 |
+
|
1716 |
+
|
1717 |
+
@pytest.mark.parametrize("op", [operator.lt, operator.gt])
|
1718 |
+
def test_nan_comparison_same_object(op):
|
1719 |
+
# GH#47105
|
1720 |
+
idx = Index([np.nan])
|
1721 |
+
expected = np.array([False])
|
1722 |
+
|
1723 |
+
result = op(idx, idx)
|
1724 |
+
tm.assert_numpy_array_equal(result, expected)
|
1725 |
+
|
1726 |
+
result = op(idx, idx.copy())
|
1727 |
+
tm.assert_numpy_array_equal(result, expected)
|
1728 |
+
|
1729 |
+
|
1730 |
+
@td.skip_if_no("pyarrow")
|
1731 |
+
def test_is_monotonic_pyarrow_list_type():
|
1732 |
+
# GH 57333
|
1733 |
+
import pyarrow as pa
|
1734 |
+
|
1735 |
+
idx = Index([[1], [2, 3]], dtype=pd.ArrowDtype(pa.list_(pa.int64())))
|
1736 |
+
assert not idx.is_monotonic_increasing
|
1737 |
+
assert not idx.is_monotonic_decreasing
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/test_common.py
ADDED
@@ -0,0 +1,511 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Collection of tests asserting things that should be true for
|
3 |
+
any index subclass except for MultiIndex. Makes use of the `index_flat`
|
4 |
+
fixture defined in pandas/conftest.py.
|
5 |
+
"""
|
6 |
+
from copy import (
|
7 |
+
copy,
|
8 |
+
deepcopy,
|
9 |
+
)
|
10 |
+
import re
|
11 |
+
|
12 |
+
import numpy as np
|
13 |
+
import pytest
|
14 |
+
|
15 |
+
from pandas.compat import IS64
|
16 |
+
from pandas.compat.numpy import np_version_gte1p25
|
17 |
+
|
18 |
+
from pandas.core.dtypes.common import (
|
19 |
+
is_integer_dtype,
|
20 |
+
is_numeric_dtype,
|
21 |
+
)
|
22 |
+
|
23 |
+
import pandas as pd
|
24 |
+
from pandas import (
|
25 |
+
CategoricalIndex,
|
26 |
+
MultiIndex,
|
27 |
+
PeriodIndex,
|
28 |
+
RangeIndex,
|
29 |
+
)
|
30 |
+
import pandas._testing as tm
|
31 |
+
|
32 |
+
|
33 |
+
class TestCommon:
|
34 |
+
@pytest.mark.parametrize("name", [None, "new_name"])
|
35 |
+
def test_to_frame(self, name, index_flat, using_copy_on_write):
|
36 |
+
# see GH#15230, GH#22580
|
37 |
+
idx = index_flat
|
38 |
+
|
39 |
+
if name:
|
40 |
+
idx_name = name
|
41 |
+
else:
|
42 |
+
idx_name = idx.name or 0
|
43 |
+
|
44 |
+
df = idx.to_frame(name=idx_name)
|
45 |
+
|
46 |
+
assert df.index is idx
|
47 |
+
assert len(df.columns) == 1
|
48 |
+
assert df.columns[0] == idx_name
|
49 |
+
if not using_copy_on_write:
|
50 |
+
assert df[idx_name].values is not idx.values
|
51 |
+
|
52 |
+
df = idx.to_frame(index=False, name=idx_name)
|
53 |
+
assert df.index is not idx
|
54 |
+
|
55 |
+
def test_droplevel(self, index_flat):
|
56 |
+
# GH 21115
|
57 |
+
# MultiIndex is tested separately in test_multi.py
|
58 |
+
index = index_flat
|
59 |
+
|
60 |
+
assert index.droplevel([]).equals(index)
|
61 |
+
|
62 |
+
for level in [index.name, [index.name]]:
|
63 |
+
if isinstance(index.name, tuple) and level is index.name:
|
64 |
+
# GH 21121 : droplevel with tuple name
|
65 |
+
continue
|
66 |
+
msg = (
|
67 |
+
"Cannot remove 1 levels from an index with 1 levels: at least one "
|
68 |
+
"level must be left."
|
69 |
+
)
|
70 |
+
with pytest.raises(ValueError, match=msg):
|
71 |
+
index.droplevel(level)
|
72 |
+
|
73 |
+
for level in "wrong", ["wrong"]:
|
74 |
+
with pytest.raises(
|
75 |
+
KeyError,
|
76 |
+
match=r"'Requested level \(wrong\) does not match index name \(None\)'",
|
77 |
+
):
|
78 |
+
index.droplevel(level)
|
79 |
+
|
80 |
+
def test_constructor_non_hashable_name(self, index_flat):
|
81 |
+
# GH 20527
|
82 |
+
index = index_flat
|
83 |
+
|
84 |
+
message = "Index.name must be a hashable type"
|
85 |
+
renamed = [["1"]]
|
86 |
+
|
87 |
+
# With .rename()
|
88 |
+
with pytest.raises(TypeError, match=message):
|
89 |
+
index.rename(name=renamed)
|
90 |
+
|
91 |
+
# With .set_names()
|
92 |
+
with pytest.raises(TypeError, match=message):
|
93 |
+
index.set_names(names=renamed)
|
94 |
+
|
95 |
+
def test_constructor_unwraps_index(self, index_flat):
|
96 |
+
a = index_flat
|
97 |
+
# Passing dtype is necessary for Index([True, False], dtype=object)
|
98 |
+
# case.
|
99 |
+
b = type(a)(a, dtype=a.dtype)
|
100 |
+
tm.assert_equal(a._data, b._data)
|
101 |
+
|
102 |
+
def test_to_flat_index(self, index_flat):
|
103 |
+
# 22866
|
104 |
+
index = index_flat
|
105 |
+
|
106 |
+
result = index.to_flat_index()
|
107 |
+
tm.assert_index_equal(result, index)
|
108 |
+
|
109 |
+
def test_set_name_methods(self, index_flat):
|
110 |
+
# MultiIndex tested separately
|
111 |
+
index = index_flat
|
112 |
+
new_name = "This is the new name for this index"
|
113 |
+
|
114 |
+
original_name = index.name
|
115 |
+
new_ind = index.set_names([new_name])
|
116 |
+
assert new_ind.name == new_name
|
117 |
+
assert index.name == original_name
|
118 |
+
res = index.rename(new_name, inplace=True)
|
119 |
+
|
120 |
+
# should return None
|
121 |
+
assert res is None
|
122 |
+
assert index.name == new_name
|
123 |
+
assert index.names == [new_name]
|
124 |
+
with pytest.raises(ValueError, match="Level must be None"):
|
125 |
+
index.set_names("a", level=0)
|
126 |
+
|
127 |
+
# rename in place just leaves tuples and other containers alone
|
128 |
+
name = ("A", "B")
|
129 |
+
index.rename(name, inplace=True)
|
130 |
+
assert index.name == name
|
131 |
+
assert index.names == [name]
|
132 |
+
|
133 |
+
@pytest.mark.xfail
|
134 |
+
def test_set_names_single_label_no_level(self, index_flat):
|
135 |
+
with pytest.raises(TypeError, match="list-like"):
|
136 |
+
# should still fail even if it would be the right length
|
137 |
+
index_flat.set_names("a")
|
138 |
+
|
139 |
+
def test_copy_and_deepcopy(self, index_flat):
|
140 |
+
index = index_flat
|
141 |
+
|
142 |
+
for func in (copy, deepcopy):
|
143 |
+
idx_copy = func(index)
|
144 |
+
assert idx_copy is not index
|
145 |
+
assert idx_copy.equals(index)
|
146 |
+
|
147 |
+
new_copy = index.copy(deep=True, name="banana")
|
148 |
+
assert new_copy.name == "banana"
|
149 |
+
|
150 |
+
def test_copy_name(self, index_flat):
|
151 |
+
# GH#12309: Check that the "name" argument
|
152 |
+
# passed at initialization is honored.
|
153 |
+
index = index_flat
|
154 |
+
|
155 |
+
first = type(index)(index, copy=True, name="mario")
|
156 |
+
second = type(first)(first, copy=False)
|
157 |
+
|
158 |
+
# Even though "copy=False", we want a new object.
|
159 |
+
assert first is not second
|
160 |
+
tm.assert_index_equal(first, second)
|
161 |
+
|
162 |
+
# Not using tm.assert_index_equal() since names differ.
|
163 |
+
assert index.equals(first)
|
164 |
+
|
165 |
+
assert first.name == "mario"
|
166 |
+
assert second.name == "mario"
|
167 |
+
|
168 |
+
# TODO: belongs in series arithmetic tests?
|
169 |
+
s1 = pd.Series(2, index=first)
|
170 |
+
s2 = pd.Series(3, index=second[:-1])
|
171 |
+
# See GH#13365
|
172 |
+
s3 = s1 * s2
|
173 |
+
assert s3.index.name == "mario"
|
174 |
+
|
175 |
+
def test_copy_name2(self, index_flat):
|
176 |
+
# GH#35592
|
177 |
+
index = index_flat
|
178 |
+
|
179 |
+
assert index.copy(name="mario").name == "mario"
|
180 |
+
|
181 |
+
with pytest.raises(ValueError, match="Length of new names must be 1, got 2"):
|
182 |
+
index.copy(name=["mario", "luigi"])
|
183 |
+
|
184 |
+
msg = f"{type(index).__name__}.name must be a hashable type"
|
185 |
+
with pytest.raises(TypeError, match=msg):
|
186 |
+
index.copy(name=[["mario"]])
|
187 |
+
|
188 |
+
def test_unique_level(self, index_flat):
|
189 |
+
# don't test a MultiIndex here (as its tested separated)
|
190 |
+
index = index_flat
|
191 |
+
|
192 |
+
# GH 17896
|
193 |
+
expected = index.drop_duplicates()
|
194 |
+
for level in [0, index.name, None]:
|
195 |
+
result = index.unique(level=level)
|
196 |
+
tm.assert_index_equal(result, expected)
|
197 |
+
|
198 |
+
msg = "Too many levels: Index has only 1 level, not 4"
|
199 |
+
with pytest.raises(IndexError, match=msg):
|
200 |
+
index.unique(level=3)
|
201 |
+
|
202 |
+
msg = (
|
203 |
+
rf"Requested level \(wrong\) does not match index name "
|
204 |
+
rf"\({re.escape(index.name.__repr__())}\)"
|
205 |
+
)
|
206 |
+
with pytest.raises(KeyError, match=msg):
|
207 |
+
index.unique(level="wrong")
|
208 |
+
|
209 |
+
def test_unique(self, index_flat):
|
210 |
+
# MultiIndex tested separately
|
211 |
+
index = index_flat
|
212 |
+
if not len(index):
|
213 |
+
pytest.skip("Skip check for empty Index and MultiIndex")
|
214 |
+
|
215 |
+
idx = index[[0] * 5]
|
216 |
+
idx_unique = index[[0]]
|
217 |
+
|
218 |
+
# We test against `idx_unique`, so first we make sure it's unique
|
219 |
+
# and doesn't contain nans.
|
220 |
+
assert idx_unique.is_unique is True
|
221 |
+
try:
|
222 |
+
assert idx_unique.hasnans is False
|
223 |
+
except NotImplementedError:
|
224 |
+
pass
|
225 |
+
|
226 |
+
result = idx.unique()
|
227 |
+
tm.assert_index_equal(result, idx_unique)
|
228 |
+
|
229 |
+
# nans:
|
230 |
+
if not index._can_hold_na:
|
231 |
+
pytest.skip("Skip na-check if index cannot hold na")
|
232 |
+
|
233 |
+
vals = index._values[[0] * 5]
|
234 |
+
vals[0] = np.nan
|
235 |
+
|
236 |
+
vals_unique = vals[:2]
|
237 |
+
idx_nan = index._shallow_copy(vals)
|
238 |
+
idx_unique_nan = index._shallow_copy(vals_unique)
|
239 |
+
assert idx_unique_nan.is_unique is True
|
240 |
+
|
241 |
+
assert idx_nan.dtype == index.dtype
|
242 |
+
assert idx_unique_nan.dtype == index.dtype
|
243 |
+
|
244 |
+
expected = idx_unique_nan
|
245 |
+
for pos, i in enumerate([idx_nan, idx_unique_nan]):
|
246 |
+
result = i.unique()
|
247 |
+
tm.assert_index_equal(result, expected)
|
248 |
+
|
249 |
+
@pytest.mark.filterwarnings("ignore:Period with BDay freq:FutureWarning")
|
250 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
251 |
+
def test_searchsorted_monotonic(self, index_flat, request):
|
252 |
+
# GH17271
|
253 |
+
index = index_flat
|
254 |
+
# not implemented for tuple searches in MultiIndex
|
255 |
+
# or Intervals searches in IntervalIndex
|
256 |
+
if isinstance(index, pd.IntervalIndex):
|
257 |
+
mark = pytest.mark.xfail(
|
258 |
+
reason="IntervalIndex.searchsorted does not support Interval arg",
|
259 |
+
raises=NotImplementedError,
|
260 |
+
)
|
261 |
+
request.applymarker(mark)
|
262 |
+
|
263 |
+
# nothing to test if the index is empty
|
264 |
+
if index.empty:
|
265 |
+
pytest.skip("Skip check for empty Index")
|
266 |
+
value = index[0]
|
267 |
+
|
268 |
+
# determine the expected results (handle dupes for 'right')
|
269 |
+
expected_left, expected_right = 0, (index == value).argmin()
|
270 |
+
if expected_right == 0:
|
271 |
+
# all values are the same, expected_right should be length
|
272 |
+
expected_right = len(index)
|
273 |
+
|
274 |
+
# test _searchsorted_monotonic in all cases
|
275 |
+
# test searchsorted only for increasing
|
276 |
+
if index.is_monotonic_increasing:
|
277 |
+
ssm_left = index._searchsorted_monotonic(value, side="left")
|
278 |
+
assert expected_left == ssm_left
|
279 |
+
|
280 |
+
ssm_right = index._searchsorted_monotonic(value, side="right")
|
281 |
+
assert expected_right == ssm_right
|
282 |
+
|
283 |
+
ss_left = index.searchsorted(value, side="left")
|
284 |
+
assert expected_left == ss_left
|
285 |
+
|
286 |
+
ss_right = index.searchsorted(value, side="right")
|
287 |
+
assert expected_right == ss_right
|
288 |
+
|
289 |
+
elif index.is_monotonic_decreasing:
|
290 |
+
ssm_left = index._searchsorted_monotonic(value, side="left")
|
291 |
+
assert expected_left == ssm_left
|
292 |
+
|
293 |
+
ssm_right = index._searchsorted_monotonic(value, side="right")
|
294 |
+
assert expected_right == ssm_right
|
295 |
+
else:
|
296 |
+
# non-monotonic should raise.
|
297 |
+
msg = "index must be monotonic increasing or decreasing"
|
298 |
+
with pytest.raises(ValueError, match=msg):
|
299 |
+
index._searchsorted_monotonic(value, side="left")
|
300 |
+
|
301 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
302 |
+
def test_drop_duplicates(self, index_flat, keep):
|
303 |
+
# MultiIndex is tested separately
|
304 |
+
index = index_flat
|
305 |
+
if isinstance(index, RangeIndex):
|
306 |
+
pytest.skip(
|
307 |
+
"RangeIndex is tested in test_drop_duplicates_no_duplicates "
|
308 |
+
"as it cannot hold duplicates"
|
309 |
+
)
|
310 |
+
if len(index) == 0:
|
311 |
+
pytest.skip(
|
312 |
+
"empty index is tested in test_drop_duplicates_no_duplicates "
|
313 |
+
"as it cannot hold duplicates"
|
314 |
+
)
|
315 |
+
|
316 |
+
# make unique index
|
317 |
+
holder = type(index)
|
318 |
+
unique_values = list(set(index))
|
319 |
+
dtype = index.dtype if is_numeric_dtype(index) else None
|
320 |
+
unique_idx = holder(unique_values, dtype=dtype)
|
321 |
+
|
322 |
+
# make duplicated index
|
323 |
+
n = len(unique_idx)
|
324 |
+
duplicated_selection = np.random.default_rng(2).choice(n, int(n * 1.5))
|
325 |
+
idx = holder(unique_idx.values[duplicated_selection])
|
326 |
+
|
327 |
+
# Series.duplicated is tested separately
|
328 |
+
expected_duplicated = (
|
329 |
+
pd.Series(duplicated_selection).duplicated(keep=keep).values
|
330 |
+
)
|
331 |
+
tm.assert_numpy_array_equal(idx.duplicated(keep=keep), expected_duplicated)
|
332 |
+
|
333 |
+
# Series.drop_duplicates is tested separately
|
334 |
+
expected_dropped = holder(pd.Series(idx).drop_duplicates(keep=keep))
|
335 |
+
tm.assert_index_equal(idx.drop_duplicates(keep=keep), expected_dropped)
|
336 |
+
|
337 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
338 |
+
def test_drop_duplicates_no_duplicates(self, index_flat):
|
339 |
+
# MultiIndex is tested separately
|
340 |
+
index = index_flat
|
341 |
+
|
342 |
+
# make unique index
|
343 |
+
if isinstance(index, RangeIndex):
|
344 |
+
# RangeIndex cannot have duplicates
|
345 |
+
unique_idx = index
|
346 |
+
else:
|
347 |
+
holder = type(index)
|
348 |
+
unique_values = list(set(index))
|
349 |
+
dtype = index.dtype if is_numeric_dtype(index) else None
|
350 |
+
unique_idx = holder(unique_values, dtype=dtype)
|
351 |
+
|
352 |
+
# check on unique index
|
353 |
+
expected_duplicated = np.array([False] * len(unique_idx), dtype="bool")
|
354 |
+
tm.assert_numpy_array_equal(unique_idx.duplicated(), expected_duplicated)
|
355 |
+
result_dropped = unique_idx.drop_duplicates()
|
356 |
+
tm.assert_index_equal(result_dropped, unique_idx)
|
357 |
+
# validate shallow copy
|
358 |
+
assert result_dropped is not unique_idx
|
359 |
+
|
360 |
+
def test_drop_duplicates_inplace(self, index):
|
361 |
+
msg = r"drop_duplicates\(\) got an unexpected keyword argument"
|
362 |
+
with pytest.raises(TypeError, match=msg):
|
363 |
+
index.drop_duplicates(inplace=True)
|
364 |
+
|
365 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
366 |
+
def test_has_duplicates(self, index_flat):
|
367 |
+
# MultiIndex tested separately in:
|
368 |
+
# tests/indexes/multi/test_unique_and_duplicates.
|
369 |
+
index = index_flat
|
370 |
+
holder = type(index)
|
371 |
+
if not len(index) or isinstance(index, RangeIndex):
|
372 |
+
# MultiIndex tested separately in:
|
373 |
+
# tests/indexes/multi/test_unique_and_duplicates.
|
374 |
+
# RangeIndex is unique by definition.
|
375 |
+
pytest.skip("Skip check for empty Index, MultiIndex, and RangeIndex")
|
376 |
+
|
377 |
+
idx = holder([index[0]] * 5)
|
378 |
+
assert idx.is_unique is False
|
379 |
+
assert idx.has_duplicates is True
|
380 |
+
|
381 |
+
@pytest.mark.parametrize(
|
382 |
+
"dtype",
|
383 |
+
["int64", "uint64", "float64", "category", "datetime64[ns]", "timedelta64[ns]"],
|
384 |
+
)
|
385 |
+
def test_astype_preserves_name(self, index, dtype):
|
386 |
+
# https://github.com/pandas-dev/pandas/issues/32013
|
387 |
+
if isinstance(index, MultiIndex):
|
388 |
+
index.names = ["idx" + str(i) for i in range(index.nlevels)]
|
389 |
+
else:
|
390 |
+
index.name = "idx"
|
391 |
+
|
392 |
+
warn = None
|
393 |
+
if index.dtype.kind == "c" and dtype in ["float64", "int64", "uint64"]:
|
394 |
+
# imaginary components discarded
|
395 |
+
if np_version_gte1p25:
|
396 |
+
warn = np.exceptions.ComplexWarning
|
397 |
+
else:
|
398 |
+
warn = np.ComplexWarning
|
399 |
+
|
400 |
+
is_pyarrow_str = str(index.dtype) == "string[pyarrow]" and dtype == "category"
|
401 |
+
try:
|
402 |
+
# Some of these conversions cannot succeed so we use a try / except
|
403 |
+
with tm.assert_produces_warning(
|
404 |
+
warn,
|
405 |
+
raise_on_extra_warnings=is_pyarrow_str,
|
406 |
+
check_stacklevel=False,
|
407 |
+
):
|
408 |
+
result = index.astype(dtype)
|
409 |
+
except (ValueError, TypeError, NotImplementedError, SystemError):
|
410 |
+
return
|
411 |
+
|
412 |
+
if isinstance(index, MultiIndex):
|
413 |
+
assert result.names == index.names
|
414 |
+
else:
|
415 |
+
assert result.name == index.name
|
416 |
+
|
417 |
+
def test_hasnans_isnans(self, index_flat):
|
418 |
+
# GH#11343, added tests for hasnans / isnans
|
419 |
+
index = index_flat
|
420 |
+
|
421 |
+
# cases in indices doesn't include NaN
|
422 |
+
idx = index.copy(deep=True)
|
423 |
+
expected = np.array([False] * len(idx), dtype=bool)
|
424 |
+
tm.assert_numpy_array_equal(idx._isnan, expected)
|
425 |
+
assert idx.hasnans is False
|
426 |
+
|
427 |
+
idx = index.copy(deep=True)
|
428 |
+
values = idx._values
|
429 |
+
|
430 |
+
if len(index) == 0:
|
431 |
+
return
|
432 |
+
elif is_integer_dtype(index.dtype):
|
433 |
+
return
|
434 |
+
elif index.dtype == bool:
|
435 |
+
# values[1] = np.nan below casts to True!
|
436 |
+
return
|
437 |
+
|
438 |
+
values[1] = np.nan
|
439 |
+
|
440 |
+
idx = type(index)(values)
|
441 |
+
|
442 |
+
expected = np.array([False] * len(idx), dtype=bool)
|
443 |
+
expected[1] = True
|
444 |
+
tm.assert_numpy_array_equal(idx._isnan, expected)
|
445 |
+
assert idx.hasnans is True
|
446 |
+
|
447 |
+
|
448 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
449 |
+
@pytest.mark.parametrize("na_position", [None, "middle"])
|
450 |
+
def test_sort_values_invalid_na_position(index_with_missing, na_position):
|
451 |
+
with pytest.raises(ValueError, match=f"invalid na_position: {na_position}"):
|
452 |
+
index_with_missing.sort_values(na_position=na_position)
|
453 |
+
|
454 |
+
|
455 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
456 |
+
@pytest.mark.parametrize("na_position", ["first", "last"])
|
457 |
+
def test_sort_values_with_missing(index_with_missing, na_position, request):
|
458 |
+
# GH 35584. Test that sort_values works with missing values,
|
459 |
+
# sort non-missing and place missing according to na_position
|
460 |
+
|
461 |
+
if isinstance(index_with_missing, CategoricalIndex):
|
462 |
+
request.applymarker(
|
463 |
+
pytest.mark.xfail(
|
464 |
+
reason="missing value sorting order not well-defined", strict=False
|
465 |
+
)
|
466 |
+
)
|
467 |
+
|
468 |
+
missing_count = np.sum(index_with_missing.isna())
|
469 |
+
not_na_vals = index_with_missing[index_with_missing.notna()].values
|
470 |
+
sorted_values = np.sort(not_na_vals)
|
471 |
+
if na_position == "first":
|
472 |
+
sorted_values = np.concatenate([[None] * missing_count, sorted_values])
|
473 |
+
else:
|
474 |
+
sorted_values = np.concatenate([sorted_values, [None] * missing_count])
|
475 |
+
|
476 |
+
# Explicitly pass dtype needed for Index backed by EA e.g. IntegerArray
|
477 |
+
expected = type(index_with_missing)(sorted_values, dtype=index_with_missing.dtype)
|
478 |
+
|
479 |
+
result = index_with_missing.sort_values(na_position=na_position)
|
480 |
+
tm.assert_index_equal(result, expected)
|
481 |
+
|
482 |
+
|
483 |
+
def test_ndarray_compat_properties(index):
|
484 |
+
if isinstance(index, PeriodIndex) and not IS64:
|
485 |
+
pytest.skip("Overflow")
|
486 |
+
idx = index
|
487 |
+
assert idx.T.equals(idx)
|
488 |
+
assert idx.transpose().equals(idx)
|
489 |
+
|
490 |
+
values = idx.values
|
491 |
+
|
492 |
+
assert idx.shape == values.shape
|
493 |
+
assert idx.ndim == values.ndim
|
494 |
+
assert idx.size == values.size
|
495 |
+
|
496 |
+
if not isinstance(index, (RangeIndex, MultiIndex)):
|
497 |
+
# These two are not backed by an ndarray
|
498 |
+
assert idx.nbytes == values.nbytes
|
499 |
+
|
500 |
+
# test for validity
|
501 |
+
idx.nbytes
|
502 |
+
idx.values.nbytes
|
503 |
+
|
504 |
+
|
505 |
+
def test_compare_read_only_array():
|
506 |
+
# GH#57130
|
507 |
+
arr = np.array([], dtype=object)
|
508 |
+
arr.flags.writeable = False
|
509 |
+
idx = pd.Index(arr)
|
510 |
+
result = idx > 69
|
511 |
+
assert result.dtype == bool
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/test_datetimelike.py
ADDED
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" generic datetimelike tests """
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
import pytest
|
5 |
+
|
6 |
+
import pandas as pd
|
7 |
+
import pandas._testing as tm
|
8 |
+
|
9 |
+
|
10 |
+
class TestDatetimeLike:
|
11 |
+
@pytest.fixture(
|
12 |
+
params=[
|
13 |
+
pd.period_range("20130101", periods=5, freq="D"),
|
14 |
+
pd.TimedeltaIndex(
|
15 |
+
[
|
16 |
+
"0 days 01:00:00",
|
17 |
+
"1 days 01:00:00",
|
18 |
+
"2 days 01:00:00",
|
19 |
+
"3 days 01:00:00",
|
20 |
+
"4 days 01:00:00",
|
21 |
+
],
|
22 |
+
dtype="timedelta64[ns]",
|
23 |
+
freq="D",
|
24 |
+
),
|
25 |
+
pd.DatetimeIndex(
|
26 |
+
["2013-01-01", "2013-01-02", "2013-01-03", "2013-01-04", "2013-01-05"],
|
27 |
+
dtype="datetime64[ns]",
|
28 |
+
freq="D",
|
29 |
+
),
|
30 |
+
]
|
31 |
+
)
|
32 |
+
def simple_index(self, request):
|
33 |
+
return request.param
|
34 |
+
|
35 |
+
def test_isin(self, simple_index):
|
36 |
+
index = simple_index[:4]
|
37 |
+
result = index.isin(index)
|
38 |
+
assert result.all()
|
39 |
+
|
40 |
+
result = index.isin(list(index))
|
41 |
+
assert result.all()
|
42 |
+
|
43 |
+
result = index.isin([index[2], 5])
|
44 |
+
expected = np.array([False, False, True, False])
|
45 |
+
tm.assert_numpy_array_equal(result, expected)
|
46 |
+
|
47 |
+
def test_argsort_matches_array(self, simple_index):
|
48 |
+
idx = simple_index
|
49 |
+
idx = idx.insert(1, pd.NaT)
|
50 |
+
|
51 |
+
result = idx.argsort()
|
52 |
+
expected = idx._data.argsort()
|
53 |
+
tm.assert_numpy_array_equal(result, expected)
|
54 |
+
|
55 |
+
def test_can_hold_identifiers(self, simple_index):
|
56 |
+
idx = simple_index
|
57 |
+
key = idx[0]
|
58 |
+
assert idx._can_hold_identifiers_and_holds_name(key) is False
|
59 |
+
|
60 |
+
def test_shift_identity(self, simple_index):
|
61 |
+
idx = simple_index
|
62 |
+
tm.assert_index_equal(idx, idx.shift(0))
|
63 |
+
|
64 |
+
def test_shift_empty(self, simple_index):
|
65 |
+
# GH#14811
|
66 |
+
idx = simple_index[:0]
|
67 |
+
tm.assert_index_equal(idx, idx.shift(1))
|
68 |
+
|
69 |
+
def test_str(self, simple_index):
|
70 |
+
# test the string repr
|
71 |
+
idx = simple_index.copy()
|
72 |
+
idx.name = "foo"
|
73 |
+
assert f"length={len(idx)}" not in str(idx)
|
74 |
+
assert "'foo'" in str(idx)
|
75 |
+
assert type(idx).__name__ in str(idx)
|
76 |
+
|
77 |
+
if hasattr(idx, "tz"):
|
78 |
+
if idx.tz is not None:
|
79 |
+
assert idx.tz in str(idx)
|
80 |
+
if isinstance(idx, pd.PeriodIndex):
|
81 |
+
assert f"dtype='period[{idx.freqstr}]'" in str(idx)
|
82 |
+
else:
|
83 |
+
assert f"freq='{idx.freqstr}'" in str(idx)
|
84 |
+
|
85 |
+
def test_view(self, simple_index):
|
86 |
+
idx = simple_index
|
87 |
+
|
88 |
+
idx_view = idx.view("i8")
|
89 |
+
result = type(simple_index)(idx)
|
90 |
+
tm.assert_index_equal(result, idx)
|
91 |
+
|
92 |
+
msg = "Passing a type in .*Index.view is deprecated"
|
93 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
94 |
+
idx_view = idx.view(type(simple_index))
|
95 |
+
result = type(simple_index)(idx)
|
96 |
+
tm.assert_index_equal(result, idx_view)
|
97 |
+
|
98 |
+
def test_map_callable(self, simple_index):
|
99 |
+
index = simple_index
|
100 |
+
expected = index + index.freq
|
101 |
+
result = index.map(lambda x: x + index.freq)
|
102 |
+
tm.assert_index_equal(result, expected)
|
103 |
+
|
104 |
+
# map to NaT
|
105 |
+
result = index.map(lambda x: pd.NaT if x == index[0] else x)
|
106 |
+
expected = pd.Index([pd.NaT] + index[1:].tolist())
|
107 |
+
tm.assert_index_equal(result, expected)
|
108 |
+
|
109 |
+
@pytest.mark.parametrize(
|
110 |
+
"mapper",
|
111 |
+
[
|
112 |
+
lambda values, index: {i: e for e, i in zip(values, index)},
|
113 |
+
lambda values, index: pd.Series(values, index, dtype=object),
|
114 |
+
],
|
115 |
+
)
|
116 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
117 |
+
def test_map_dictlike(self, mapper, simple_index):
|
118 |
+
index = simple_index
|
119 |
+
expected = index + index.freq
|
120 |
+
|
121 |
+
# don't compare the freqs
|
122 |
+
if isinstance(expected, (pd.DatetimeIndex, pd.TimedeltaIndex)):
|
123 |
+
expected = expected._with_freq(None)
|
124 |
+
|
125 |
+
result = index.map(mapper(expected, index))
|
126 |
+
tm.assert_index_equal(result, expected)
|
127 |
+
|
128 |
+
expected = pd.Index([pd.NaT] + index[1:].tolist())
|
129 |
+
result = index.map(mapper(expected, index))
|
130 |
+
tm.assert_index_equal(result, expected)
|
131 |
+
|
132 |
+
# empty map; these map to np.nan because we cannot know
|
133 |
+
# to re-infer things
|
134 |
+
expected = pd.Index([np.nan] * len(index))
|
135 |
+
result = index.map(mapper([], []))
|
136 |
+
tm.assert_index_equal(result, expected)
|
137 |
+
|
138 |
+
def test_getitem_preserves_freq(self, simple_index):
|
139 |
+
index = simple_index
|
140 |
+
assert index.freq is not None
|
141 |
+
|
142 |
+
result = index[:]
|
143 |
+
assert result.freq == index.freq
|
144 |
+
|
145 |
+
def test_where_cast_str(self, simple_index):
|
146 |
+
index = simple_index
|
147 |
+
|
148 |
+
mask = np.ones(len(index), dtype=bool)
|
149 |
+
mask[-1] = False
|
150 |
+
|
151 |
+
result = index.where(mask, str(index[0]))
|
152 |
+
expected = index.where(mask, index[0])
|
153 |
+
tm.assert_index_equal(result, expected)
|
154 |
+
|
155 |
+
result = index.where(mask, [str(index[0])])
|
156 |
+
tm.assert_index_equal(result, expected)
|
157 |
+
|
158 |
+
expected = index.astype(object).where(mask, "foo")
|
159 |
+
result = index.where(mask, "foo")
|
160 |
+
tm.assert_index_equal(result, expected)
|
161 |
+
|
162 |
+
result = index.where(mask, ["foo"])
|
163 |
+
tm.assert_index_equal(result, expected)
|
164 |
+
|
165 |
+
@pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
|
166 |
+
def test_diff(self, unit):
|
167 |
+
# GH 55080
|
168 |
+
dti = pd.to_datetime([10, 20, 30], unit=unit).as_unit(unit)
|
169 |
+
result = dti.diff(1)
|
170 |
+
expected = pd.to_timedelta([pd.NaT, 10, 10], unit=unit).as_unit(unit)
|
171 |
+
tm.assert_index_equal(result, expected)
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/test_engines.py
ADDED
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
import pytest
|
5 |
+
|
6 |
+
from pandas._libs import index as libindex
|
7 |
+
|
8 |
+
import pandas as pd
|
9 |
+
|
10 |
+
|
11 |
+
@pytest.fixture(
|
12 |
+
params=[
|
13 |
+
(libindex.Int64Engine, np.int64),
|
14 |
+
(libindex.Int32Engine, np.int32),
|
15 |
+
(libindex.Int16Engine, np.int16),
|
16 |
+
(libindex.Int8Engine, np.int8),
|
17 |
+
(libindex.UInt64Engine, np.uint64),
|
18 |
+
(libindex.UInt32Engine, np.uint32),
|
19 |
+
(libindex.UInt16Engine, np.uint16),
|
20 |
+
(libindex.UInt8Engine, np.uint8),
|
21 |
+
(libindex.Float64Engine, np.float64),
|
22 |
+
(libindex.Float32Engine, np.float32),
|
23 |
+
],
|
24 |
+
ids=lambda x: x[0].__name__,
|
25 |
+
)
|
26 |
+
def numeric_indexing_engine_type_and_dtype(request):
|
27 |
+
return request.param
|
28 |
+
|
29 |
+
|
30 |
+
class TestDatetimeEngine:
|
31 |
+
@pytest.mark.parametrize(
|
32 |
+
"scalar",
|
33 |
+
[
|
34 |
+
pd.Timedelta(pd.Timestamp("2016-01-01").asm8.view("m8[ns]")),
|
35 |
+
pd.Timestamp("2016-01-01")._value,
|
36 |
+
pd.Timestamp("2016-01-01").to_pydatetime(),
|
37 |
+
pd.Timestamp("2016-01-01").to_datetime64(),
|
38 |
+
],
|
39 |
+
)
|
40 |
+
def test_not_contains_requires_timestamp(self, scalar):
|
41 |
+
dti1 = pd.date_range("2016-01-01", periods=3)
|
42 |
+
dti2 = dti1.insert(1, pd.NaT) # non-monotonic
|
43 |
+
dti3 = dti1.insert(3, dti1[0]) # non-unique
|
44 |
+
dti4 = pd.date_range("2016-01-01", freq="ns", periods=2_000_000)
|
45 |
+
dti5 = dti4.insert(0, dti4[0]) # over size threshold, not unique
|
46 |
+
|
47 |
+
msg = "|".join([re.escape(str(scalar)), re.escape(repr(scalar))])
|
48 |
+
for dti in [dti1, dti2, dti3, dti4, dti5]:
|
49 |
+
with pytest.raises(TypeError, match=msg):
|
50 |
+
scalar in dti._engine
|
51 |
+
|
52 |
+
with pytest.raises(KeyError, match=msg):
|
53 |
+
dti._engine.get_loc(scalar)
|
54 |
+
|
55 |
+
|
56 |
+
class TestTimedeltaEngine:
|
57 |
+
@pytest.mark.parametrize(
|
58 |
+
"scalar",
|
59 |
+
[
|
60 |
+
pd.Timestamp(pd.Timedelta(days=42).asm8.view("datetime64[ns]")),
|
61 |
+
pd.Timedelta(days=42)._value,
|
62 |
+
pd.Timedelta(days=42).to_pytimedelta(),
|
63 |
+
pd.Timedelta(days=42).to_timedelta64(),
|
64 |
+
],
|
65 |
+
)
|
66 |
+
def test_not_contains_requires_timedelta(self, scalar):
|
67 |
+
tdi1 = pd.timedelta_range("42 days", freq="9h", periods=1234)
|
68 |
+
tdi2 = tdi1.insert(1, pd.NaT) # non-monotonic
|
69 |
+
tdi3 = tdi1.insert(3, tdi1[0]) # non-unique
|
70 |
+
tdi4 = pd.timedelta_range("42 days", freq="ns", periods=2_000_000)
|
71 |
+
tdi5 = tdi4.insert(0, tdi4[0]) # over size threshold, not unique
|
72 |
+
|
73 |
+
msg = "|".join([re.escape(str(scalar)), re.escape(repr(scalar))])
|
74 |
+
for tdi in [tdi1, tdi2, tdi3, tdi4, tdi5]:
|
75 |
+
with pytest.raises(TypeError, match=msg):
|
76 |
+
scalar in tdi._engine
|
77 |
+
|
78 |
+
with pytest.raises(KeyError, match=msg):
|
79 |
+
tdi._engine.get_loc(scalar)
|
80 |
+
|
81 |
+
|
82 |
+
class TestNumericEngine:
|
83 |
+
def test_is_monotonic(self, numeric_indexing_engine_type_and_dtype):
|
84 |
+
engine_type, dtype = numeric_indexing_engine_type_and_dtype
|
85 |
+
num = 1000
|
86 |
+
arr = np.array([1] * num + [2] * num + [3] * num, dtype=dtype)
|
87 |
+
|
88 |
+
# monotonic increasing
|
89 |
+
engine = engine_type(arr)
|
90 |
+
assert engine.is_monotonic_increasing is True
|
91 |
+
assert engine.is_monotonic_decreasing is False
|
92 |
+
|
93 |
+
# monotonic decreasing
|
94 |
+
engine = engine_type(arr[::-1])
|
95 |
+
assert engine.is_monotonic_increasing is False
|
96 |
+
assert engine.is_monotonic_decreasing is True
|
97 |
+
|
98 |
+
# neither monotonic increasing or decreasing
|
99 |
+
arr = np.array([1] * num + [2] * num + [1] * num, dtype=dtype)
|
100 |
+
engine = engine_type(arr[::-1])
|
101 |
+
assert engine.is_monotonic_increasing is False
|
102 |
+
assert engine.is_monotonic_decreasing is False
|
103 |
+
|
104 |
+
def test_is_unique(self, numeric_indexing_engine_type_and_dtype):
|
105 |
+
engine_type, dtype = numeric_indexing_engine_type_and_dtype
|
106 |
+
|
107 |
+
# unique
|
108 |
+
arr = np.array([1, 3, 2], dtype=dtype)
|
109 |
+
engine = engine_type(arr)
|
110 |
+
assert engine.is_unique is True
|
111 |
+
|
112 |
+
# not unique
|
113 |
+
arr = np.array([1, 2, 1], dtype=dtype)
|
114 |
+
engine = engine_type(arr)
|
115 |
+
assert engine.is_unique is False
|
116 |
+
|
117 |
+
def test_get_loc(self, numeric_indexing_engine_type_and_dtype):
|
118 |
+
engine_type, dtype = numeric_indexing_engine_type_and_dtype
|
119 |
+
|
120 |
+
# unique
|
121 |
+
arr = np.array([1, 2, 3], dtype=dtype)
|
122 |
+
engine = engine_type(arr)
|
123 |
+
assert engine.get_loc(2) == 1
|
124 |
+
|
125 |
+
# monotonic
|
126 |
+
num = 1000
|
127 |
+
arr = np.array([1] * num + [2] * num + [3] * num, dtype=dtype)
|
128 |
+
engine = engine_type(arr)
|
129 |
+
assert engine.get_loc(2) == slice(1000, 2000)
|
130 |
+
|
131 |
+
# not monotonic
|
132 |
+
arr = np.array([1, 2, 3] * num, dtype=dtype)
|
133 |
+
engine = engine_type(arr)
|
134 |
+
expected = np.array([False, True, False] * num, dtype=bool)
|
135 |
+
result = engine.get_loc(2)
|
136 |
+
assert (result == expected).all()
|
137 |
+
|
138 |
+
|
139 |
+
class TestObjectEngine:
|
140 |
+
engine_type = libindex.ObjectEngine
|
141 |
+
dtype = np.object_
|
142 |
+
values = list("abc")
|
143 |
+
|
144 |
+
def test_is_monotonic(self):
|
145 |
+
num = 1000
|
146 |
+
arr = np.array(["a"] * num + ["a"] * num + ["c"] * num, dtype=self.dtype)
|
147 |
+
|
148 |
+
# monotonic increasing
|
149 |
+
engine = self.engine_type(arr)
|
150 |
+
assert engine.is_monotonic_increasing is True
|
151 |
+
assert engine.is_monotonic_decreasing is False
|
152 |
+
|
153 |
+
# monotonic decreasing
|
154 |
+
engine = self.engine_type(arr[::-1])
|
155 |
+
assert engine.is_monotonic_increasing is False
|
156 |
+
assert engine.is_monotonic_decreasing is True
|
157 |
+
|
158 |
+
# neither monotonic increasing or decreasing
|
159 |
+
arr = np.array(["a"] * num + ["b"] * num + ["a"] * num, dtype=self.dtype)
|
160 |
+
engine = self.engine_type(arr[::-1])
|
161 |
+
assert engine.is_monotonic_increasing is False
|
162 |
+
assert engine.is_monotonic_decreasing is False
|
163 |
+
|
164 |
+
def test_is_unique(self):
|
165 |
+
# unique
|
166 |
+
arr = np.array(self.values, dtype=self.dtype)
|
167 |
+
engine = self.engine_type(arr)
|
168 |
+
assert engine.is_unique is True
|
169 |
+
|
170 |
+
# not unique
|
171 |
+
arr = np.array(["a", "b", "a"], dtype=self.dtype)
|
172 |
+
engine = self.engine_type(arr)
|
173 |
+
assert engine.is_unique is False
|
174 |
+
|
175 |
+
def test_get_loc(self):
|
176 |
+
# unique
|
177 |
+
arr = np.array(self.values, dtype=self.dtype)
|
178 |
+
engine = self.engine_type(arr)
|
179 |
+
assert engine.get_loc("b") == 1
|
180 |
+
|
181 |
+
# monotonic
|
182 |
+
num = 1000
|
183 |
+
arr = np.array(["a"] * num + ["b"] * num + ["c"] * num, dtype=self.dtype)
|
184 |
+
engine = self.engine_type(arr)
|
185 |
+
assert engine.get_loc("b") == slice(1000, 2000)
|
186 |
+
|
187 |
+
# not monotonic
|
188 |
+
arr = np.array(self.values * num, dtype=self.dtype)
|
189 |
+
engine = self.engine_type(arr)
|
190 |
+
expected = np.array([False, True, False] * num, dtype=bool)
|
191 |
+
result = engine.get_loc("b")
|
192 |
+
assert (result == expected).all()
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/test_frozen.py
ADDED
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
|
3 |
+
import pytest
|
4 |
+
|
5 |
+
from pandas.core.indexes.frozen import FrozenList
|
6 |
+
|
7 |
+
|
8 |
+
@pytest.fixture
|
9 |
+
def lst():
|
10 |
+
return [1, 2, 3, 4, 5]
|
11 |
+
|
12 |
+
|
13 |
+
@pytest.fixture
|
14 |
+
def container(lst):
|
15 |
+
return FrozenList(lst)
|
16 |
+
|
17 |
+
|
18 |
+
@pytest.fixture
|
19 |
+
def unicode_container():
|
20 |
+
return FrozenList(["\u05d0", "\u05d1", "c"])
|
21 |
+
|
22 |
+
|
23 |
+
class TestFrozenList:
|
24 |
+
def check_mutable_error(self, *args, **kwargs):
|
25 |
+
# Pass whatever function you normally would to pytest.raises
|
26 |
+
# (after the Exception kind).
|
27 |
+
mutable_regex = re.compile("does not support mutable operations")
|
28 |
+
msg = "'(_s)?re.(SRE_)?Pattern' object is not callable"
|
29 |
+
with pytest.raises(TypeError, match=msg):
|
30 |
+
mutable_regex(*args, **kwargs)
|
31 |
+
|
32 |
+
def test_no_mutable_funcs(self, container):
|
33 |
+
def setitem():
|
34 |
+
container[0] = 5
|
35 |
+
|
36 |
+
self.check_mutable_error(setitem)
|
37 |
+
|
38 |
+
def setslice():
|
39 |
+
container[1:2] = 3
|
40 |
+
|
41 |
+
self.check_mutable_error(setslice)
|
42 |
+
|
43 |
+
def delitem():
|
44 |
+
del container[0]
|
45 |
+
|
46 |
+
self.check_mutable_error(delitem)
|
47 |
+
|
48 |
+
def delslice():
|
49 |
+
del container[0:3]
|
50 |
+
|
51 |
+
self.check_mutable_error(delslice)
|
52 |
+
|
53 |
+
mutable_methods = ("extend", "pop", "remove", "insert")
|
54 |
+
|
55 |
+
for meth in mutable_methods:
|
56 |
+
self.check_mutable_error(getattr(container, meth))
|
57 |
+
|
58 |
+
def test_slicing_maintains_type(self, container, lst):
|
59 |
+
result = container[1:2]
|
60 |
+
expected = lst[1:2]
|
61 |
+
self.check_result(result, expected)
|
62 |
+
|
63 |
+
def check_result(self, result, expected):
|
64 |
+
assert isinstance(result, FrozenList)
|
65 |
+
assert result == expected
|
66 |
+
|
67 |
+
def test_string_methods_dont_fail(self, container):
|
68 |
+
repr(container)
|
69 |
+
str(container)
|
70 |
+
bytes(container)
|
71 |
+
|
72 |
+
def test_tricky_container(self, unicode_container):
|
73 |
+
repr(unicode_container)
|
74 |
+
str(unicode_container)
|
75 |
+
|
76 |
+
def test_add(self, container, lst):
|
77 |
+
result = container + (1, 2, 3)
|
78 |
+
expected = FrozenList(lst + [1, 2, 3])
|
79 |
+
self.check_result(result, expected)
|
80 |
+
|
81 |
+
result = (1, 2, 3) + container
|
82 |
+
expected = FrozenList([1, 2, 3] + lst)
|
83 |
+
self.check_result(result, expected)
|
84 |
+
|
85 |
+
def test_iadd(self, container, lst):
|
86 |
+
q = r = container
|
87 |
+
|
88 |
+
q += [5]
|
89 |
+
self.check_result(q, lst + [5])
|
90 |
+
|
91 |
+
# Other shouldn't be mutated.
|
92 |
+
self.check_result(r, lst)
|
93 |
+
|
94 |
+
def test_union(self, container, lst):
|
95 |
+
result = container.union((1, 2, 3))
|
96 |
+
expected = FrozenList(lst + [1, 2, 3])
|
97 |
+
self.check_result(result, expected)
|
98 |
+
|
99 |
+
def test_difference(self, container):
|
100 |
+
result = container.difference([2])
|
101 |
+
expected = FrozenList([1, 3, 4, 5])
|
102 |
+
self.check_result(result, expected)
|
103 |
+
|
104 |
+
def test_difference_dupe(self):
|
105 |
+
result = FrozenList([1, 2, 3, 2]).difference([2])
|
106 |
+
expected = FrozenList([1, 3])
|
107 |
+
self.check_result(result, expected)
|
108 |
+
|
109 |
+
def test_tricky_container_to_bytes_raises(self, unicode_container):
|
110 |
+
# GH 26447
|
111 |
+
msg = "^'str' object cannot be interpreted as an integer$"
|
112 |
+
with pytest.raises(TypeError, match=msg):
|
113 |
+
bytes(unicode_container)
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/test_index_new.py
ADDED
@@ -0,0 +1,432 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Tests for the Index constructor conducting inference.
|
3 |
+
"""
|
4 |
+
from datetime import (
|
5 |
+
datetime,
|
6 |
+
timedelta,
|
7 |
+
timezone,
|
8 |
+
)
|
9 |
+
from decimal import Decimal
|
10 |
+
|
11 |
+
import numpy as np
|
12 |
+
import pytest
|
13 |
+
|
14 |
+
from pandas._libs.tslibs.timezones import maybe_get_tz
|
15 |
+
|
16 |
+
from pandas import (
|
17 |
+
NA,
|
18 |
+
Categorical,
|
19 |
+
CategoricalIndex,
|
20 |
+
DatetimeIndex,
|
21 |
+
Index,
|
22 |
+
IntervalIndex,
|
23 |
+
MultiIndex,
|
24 |
+
NaT,
|
25 |
+
PeriodIndex,
|
26 |
+
Series,
|
27 |
+
TimedeltaIndex,
|
28 |
+
Timestamp,
|
29 |
+
array,
|
30 |
+
date_range,
|
31 |
+
period_range,
|
32 |
+
timedelta_range,
|
33 |
+
)
|
34 |
+
import pandas._testing as tm
|
35 |
+
|
36 |
+
|
37 |
+
class TestIndexConstructorInference:
|
38 |
+
def test_object_all_bools(self):
|
39 |
+
# GH#49594 match Series behavior on ndarray[object] of all bools
|
40 |
+
arr = np.array([True, False], dtype=object)
|
41 |
+
res = Index(arr)
|
42 |
+
assert res.dtype == object
|
43 |
+
|
44 |
+
# since the point is matching Series behavior, let's double check
|
45 |
+
assert Series(arr).dtype == object
|
46 |
+
|
47 |
+
def test_object_all_complex(self):
|
48 |
+
# GH#49594 match Series behavior on ndarray[object] of all complex
|
49 |
+
arr = np.array([complex(1), complex(2)], dtype=object)
|
50 |
+
res = Index(arr)
|
51 |
+
assert res.dtype == object
|
52 |
+
|
53 |
+
# since the point is matching Series behavior, let's double check
|
54 |
+
assert Series(arr).dtype == object
|
55 |
+
|
56 |
+
@pytest.mark.parametrize("val", [NaT, None, np.nan, float("nan")])
|
57 |
+
def test_infer_nat(self, val):
|
58 |
+
# GH#49340 all NaT/None/nan and at least 1 NaT -> datetime64[ns],
|
59 |
+
# matching Series behavior
|
60 |
+
values = [NaT, val]
|
61 |
+
|
62 |
+
idx = Index(values)
|
63 |
+
assert idx.dtype == "datetime64[ns]" and idx.isna().all()
|
64 |
+
|
65 |
+
idx = Index(values[::-1])
|
66 |
+
assert idx.dtype == "datetime64[ns]" and idx.isna().all()
|
67 |
+
|
68 |
+
idx = Index(np.array(values, dtype=object))
|
69 |
+
assert idx.dtype == "datetime64[ns]" and idx.isna().all()
|
70 |
+
|
71 |
+
idx = Index(np.array(values, dtype=object)[::-1])
|
72 |
+
assert idx.dtype == "datetime64[ns]" and idx.isna().all()
|
73 |
+
|
74 |
+
@pytest.mark.parametrize("na_value", [None, np.nan])
|
75 |
+
@pytest.mark.parametrize("vtype", [list, tuple, iter])
|
76 |
+
def test_construction_list_tuples_nan(self, na_value, vtype):
|
77 |
+
# GH#18505 : valid tuples containing NaN
|
78 |
+
values = [(1, "two"), (3.0, na_value)]
|
79 |
+
result = Index(vtype(values))
|
80 |
+
expected = MultiIndex.from_tuples(values)
|
81 |
+
tm.assert_index_equal(result, expected)
|
82 |
+
|
83 |
+
@pytest.mark.parametrize(
|
84 |
+
"dtype",
|
85 |
+
[int, "int64", "int32", "int16", "int8", "uint64", "uint32", "uint16", "uint8"],
|
86 |
+
)
|
87 |
+
def test_constructor_int_dtype_float(self, dtype):
|
88 |
+
# GH#18400
|
89 |
+
expected = Index([0, 1, 2, 3], dtype=dtype)
|
90 |
+
result = Index([0.0, 1.0, 2.0, 3.0], dtype=dtype)
|
91 |
+
tm.assert_index_equal(result, expected)
|
92 |
+
|
93 |
+
@pytest.mark.parametrize("cast_index", [True, False])
|
94 |
+
@pytest.mark.parametrize(
|
95 |
+
"vals", [[True, False, True], np.array([True, False, True], dtype=bool)]
|
96 |
+
)
|
97 |
+
def test_constructor_dtypes_to_object(self, cast_index, vals):
|
98 |
+
if cast_index:
|
99 |
+
index = Index(vals, dtype=bool)
|
100 |
+
else:
|
101 |
+
index = Index(vals)
|
102 |
+
|
103 |
+
assert type(index) is Index
|
104 |
+
assert index.dtype == bool
|
105 |
+
|
106 |
+
def test_constructor_categorical_to_object(self):
|
107 |
+
# GH#32167 Categorical data and dtype=object should return object-dtype
|
108 |
+
ci = CategoricalIndex(range(5))
|
109 |
+
result = Index(ci, dtype=object)
|
110 |
+
assert not isinstance(result, CategoricalIndex)
|
111 |
+
|
112 |
+
def test_constructor_infer_periodindex(self):
|
113 |
+
xp = period_range("2012-1-1", freq="M", periods=3)
|
114 |
+
rs = Index(xp)
|
115 |
+
tm.assert_index_equal(rs, xp)
|
116 |
+
assert isinstance(rs, PeriodIndex)
|
117 |
+
|
118 |
+
def test_from_list_of_periods(self):
|
119 |
+
rng = period_range("1/1/2000", periods=20, freq="D")
|
120 |
+
periods = list(rng)
|
121 |
+
|
122 |
+
result = Index(periods)
|
123 |
+
assert isinstance(result, PeriodIndex)
|
124 |
+
|
125 |
+
@pytest.mark.parametrize("pos", [0, 1])
|
126 |
+
@pytest.mark.parametrize(
|
127 |
+
"klass,dtype,ctor",
|
128 |
+
[
|
129 |
+
(DatetimeIndex, "datetime64[ns]", np.datetime64("nat")),
|
130 |
+
(TimedeltaIndex, "timedelta64[ns]", np.timedelta64("nat")),
|
131 |
+
],
|
132 |
+
)
|
133 |
+
def test_constructor_infer_nat_dt_like(
|
134 |
+
self, pos, klass, dtype, ctor, nulls_fixture, request
|
135 |
+
):
|
136 |
+
if isinstance(nulls_fixture, Decimal):
|
137 |
+
# We dont cast these to datetime64/timedelta64
|
138 |
+
pytest.skip(
|
139 |
+
f"We don't cast {type(nulls_fixture).__name__} to "
|
140 |
+
"datetime64/timedelta64"
|
141 |
+
)
|
142 |
+
|
143 |
+
expected = klass([NaT, NaT])
|
144 |
+
assert expected.dtype == dtype
|
145 |
+
data = [ctor]
|
146 |
+
data.insert(pos, nulls_fixture)
|
147 |
+
|
148 |
+
warn = None
|
149 |
+
if nulls_fixture is NA:
|
150 |
+
expected = Index([NA, NaT])
|
151 |
+
mark = pytest.mark.xfail(reason="Broken with np.NaT ctor; see GH 31884")
|
152 |
+
request.applymarker(mark)
|
153 |
+
# GH#35942 numpy will emit a DeprecationWarning within the
|
154 |
+
# assert_index_equal calls. Since we can't do anything
|
155 |
+
# about it until GH#31884 is fixed, we suppress that warning.
|
156 |
+
warn = DeprecationWarning
|
157 |
+
|
158 |
+
result = Index(data)
|
159 |
+
|
160 |
+
with tm.assert_produces_warning(warn):
|
161 |
+
tm.assert_index_equal(result, expected)
|
162 |
+
|
163 |
+
result = Index(np.array(data, dtype=object))
|
164 |
+
|
165 |
+
with tm.assert_produces_warning(warn):
|
166 |
+
tm.assert_index_equal(result, expected)
|
167 |
+
|
168 |
+
@pytest.mark.parametrize("swap_objs", [True, False])
|
169 |
+
def test_constructor_mixed_nat_objs_infers_object(self, swap_objs):
|
170 |
+
# mixed np.datetime64/timedelta64 nat results in object
|
171 |
+
data = [np.datetime64("nat"), np.timedelta64("nat")]
|
172 |
+
if swap_objs:
|
173 |
+
data = data[::-1]
|
174 |
+
|
175 |
+
expected = Index(data, dtype=object)
|
176 |
+
tm.assert_index_equal(Index(data), expected)
|
177 |
+
tm.assert_index_equal(Index(np.array(data, dtype=object)), expected)
|
178 |
+
|
179 |
+
@pytest.mark.parametrize("swap_objs", [True, False])
|
180 |
+
def test_constructor_datetime_and_datetime64(self, swap_objs):
|
181 |
+
data = [Timestamp(2021, 6, 8, 9, 42), np.datetime64("now")]
|
182 |
+
if swap_objs:
|
183 |
+
data = data[::-1]
|
184 |
+
expected = DatetimeIndex(data)
|
185 |
+
|
186 |
+
tm.assert_index_equal(Index(data), expected)
|
187 |
+
tm.assert_index_equal(Index(np.array(data, dtype=object)), expected)
|
188 |
+
|
189 |
+
def test_constructor_datetimes_mixed_tzs(self):
|
190 |
+
# https://github.com/pandas-dev/pandas/pull/55793/files#r1383719998
|
191 |
+
tz = maybe_get_tz("US/Central")
|
192 |
+
dt1 = datetime(2020, 1, 1, tzinfo=tz)
|
193 |
+
dt2 = datetime(2020, 1, 1, tzinfo=timezone.utc)
|
194 |
+
result = Index([dt1, dt2])
|
195 |
+
expected = Index([dt1, dt2], dtype=object)
|
196 |
+
tm.assert_index_equal(result, expected)
|
197 |
+
|
198 |
+
|
199 |
+
class TestDtypeEnforced:
|
200 |
+
# check we don't silently ignore the dtype keyword
|
201 |
+
|
202 |
+
def test_constructor_object_dtype_with_ea_data(self, any_numeric_ea_dtype):
|
203 |
+
# GH#45206
|
204 |
+
arr = array([0], dtype=any_numeric_ea_dtype)
|
205 |
+
|
206 |
+
idx = Index(arr, dtype=object)
|
207 |
+
assert idx.dtype == object
|
208 |
+
|
209 |
+
@pytest.mark.parametrize("dtype", [object, "float64", "uint64", "category"])
|
210 |
+
def test_constructor_range_values_mismatched_dtype(self, dtype):
|
211 |
+
rng = Index(range(5))
|
212 |
+
|
213 |
+
result = Index(rng, dtype=dtype)
|
214 |
+
assert result.dtype == dtype
|
215 |
+
|
216 |
+
result = Index(range(5), dtype=dtype)
|
217 |
+
assert result.dtype == dtype
|
218 |
+
|
219 |
+
@pytest.mark.parametrize("dtype", [object, "float64", "uint64", "category"])
|
220 |
+
def test_constructor_categorical_values_mismatched_non_ea_dtype(self, dtype):
|
221 |
+
cat = Categorical([1, 2, 3])
|
222 |
+
|
223 |
+
result = Index(cat, dtype=dtype)
|
224 |
+
assert result.dtype == dtype
|
225 |
+
|
226 |
+
def test_constructor_categorical_values_mismatched_dtype(self):
|
227 |
+
dti = date_range("2016-01-01", periods=3)
|
228 |
+
cat = Categorical(dti)
|
229 |
+
result = Index(cat, dti.dtype)
|
230 |
+
tm.assert_index_equal(result, dti)
|
231 |
+
|
232 |
+
dti2 = dti.tz_localize("Asia/Tokyo")
|
233 |
+
cat2 = Categorical(dti2)
|
234 |
+
result = Index(cat2, dti2.dtype)
|
235 |
+
tm.assert_index_equal(result, dti2)
|
236 |
+
|
237 |
+
ii = IntervalIndex.from_breaks(range(5))
|
238 |
+
cat3 = Categorical(ii)
|
239 |
+
result = Index(cat3, dtype=ii.dtype)
|
240 |
+
tm.assert_index_equal(result, ii)
|
241 |
+
|
242 |
+
def test_constructor_ea_values_mismatched_categorical_dtype(self):
|
243 |
+
dti = date_range("2016-01-01", periods=3)
|
244 |
+
result = Index(dti, dtype="category")
|
245 |
+
expected = CategoricalIndex(dti)
|
246 |
+
tm.assert_index_equal(result, expected)
|
247 |
+
|
248 |
+
dti2 = date_range("2016-01-01", periods=3, tz="US/Pacific")
|
249 |
+
result = Index(dti2, dtype="category")
|
250 |
+
expected = CategoricalIndex(dti2)
|
251 |
+
tm.assert_index_equal(result, expected)
|
252 |
+
|
253 |
+
def test_constructor_period_values_mismatched_dtype(self):
|
254 |
+
pi = period_range("2016-01-01", periods=3, freq="D")
|
255 |
+
result = Index(pi, dtype="category")
|
256 |
+
expected = CategoricalIndex(pi)
|
257 |
+
tm.assert_index_equal(result, expected)
|
258 |
+
|
259 |
+
def test_constructor_timedelta64_values_mismatched_dtype(self):
|
260 |
+
# check we don't silently ignore the dtype keyword
|
261 |
+
tdi = timedelta_range("4 Days", periods=5)
|
262 |
+
result = Index(tdi, dtype="category")
|
263 |
+
expected = CategoricalIndex(tdi)
|
264 |
+
tm.assert_index_equal(result, expected)
|
265 |
+
|
266 |
+
def test_constructor_interval_values_mismatched_dtype(self):
|
267 |
+
dti = date_range("2016-01-01", periods=3)
|
268 |
+
ii = IntervalIndex.from_breaks(dti)
|
269 |
+
result = Index(ii, dtype="category")
|
270 |
+
expected = CategoricalIndex(ii)
|
271 |
+
tm.assert_index_equal(result, expected)
|
272 |
+
|
273 |
+
def test_constructor_datetime64_values_mismatched_period_dtype(self):
|
274 |
+
dti = date_range("2016-01-01", periods=3)
|
275 |
+
result = Index(dti, dtype="Period[D]")
|
276 |
+
expected = dti.to_period("D")
|
277 |
+
tm.assert_index_equal(result, expected)
|
278 |
+
|
279 |
+
@pytest.mark.parametrize("dtype", ["int64", "uint64"])
|
280 |
+
def test_constructor_int_dtype_nan_raises(self, dtype):
|
281 |
+
# see GH#15187
|
282 |
+
data = [np.nan]
|
283 |
+
msg = "cannot convert"
|
284 |
+
with pytest.raises(ValueError, match=msg):
|
285 |
+
Index(data, dtype=dtype)
|
286 |
+
|
287 |
+
@pytest.mark.parametrize(
|
288 |
+
"vals",
|
289 |
+
[
|
290 |
+
[1, 2, 3],
|
291 |
+
np.array([1, 2, 3]),
|
292 |
+
np.array([1, 2, 3], dtype=int),
|
293 |
+
# below should coerce
|
294 |
+
[1.0, 2.0, 3.0],
|
295 |
+
np.array([1.0, 2.0, 3.0], dtype=float),
|
296 |
+
],
|
297 |
+
)
|
298 |
+
def test_constructor_dtypes_to_int(self, vals, any_int_numpy_dtype):
|
299 |
+
dtype = any_int_numpy_dtype
|
300 |
+
index = Index(vals, dtype=dtype)
|
301 |
+
assert index.dtype == dtype
|
302 |
+
|
303 |
+
@pytest.mark.parametrize(
|
304 |
+
"vals",
|
305 |
+
[
|
306 |
+
[1, 2, 3],
|
307 |
+
[1.0, 2.0, 3.0],
|
308 |
+
np.array([1.0, 2.0, 3.0]),
|
309 |
+
np.array([1, 2, 3], dtype=int),
|
310 |
+
np.array([1.0, 2.0, 3.0], dtype=float),
|
311 |
+
],
|
312 |
+
)
|
313 |
+
def test_constructor_dtypes_to_float(self, vals, float_numpy_dtype):
|
314 |
+
dtype = float_numpy_dtype
|
315 |
+
index = Index(vals, dtype=dtype)
|
316 |
+
assert index.dtype == dtype
|
317 |
+
|
318 |
+
@pytest.mark.parametrize(
|
319 |
+
"vals",
|
320 |
+
[
|
321 |
+
[1, 2, 3],
|
322 |
+
np.array([1, 2, 3], dtype=int),
|
323 |
+
np.array(["2011-01-01", "2011-01-02"], dtype="datetime64[ns]"),
|
324 |
+
[datetime(2011, 1, 1), datetime(2011, 1, 2)],
|
325 |
+
],
|
326 |
+
)
|
327 |
+
def test_constructor_dtypes_to_categorical(self, vals):
|
328 |
+
index = Index(vals, dtype="category")
|
329 |
+
assert isinstance(index, CategoricalIndex)
|
330 |
+
|
331 |
+
@pytest.mark.parametrize("cast_index", [True, False])
|
332 |
+
@pytest.mark.parametrize(
|
333 |
+
"vals",
|
334 |
+
[
|
335 |
+
Index(np.array([np.datetime64("2011-01-01"), np.datetime64("2011-01-02")])),
|
336 |
+
Index([datetime(2011, 1, 1), datetime(2011, 1, 2)]),
|
337 |
+
],
|
338 |
+
)
|
339 |
+
def test_constructor_dtypes_to_datetime(self, cast_index, vals):
|
340 |
+
if cast_index:
|
341 |
+
index = Index(vals, dtype=object)
|
342 |
+
assert isinstance(index, Index)
|
343 |
+
assert index.dtype == object
|
344 |
+
else:
|
345 |
+
index = Index(vals)
|
346 |
+
assert isinstance(index, DatetimeIndex)
|
347 |
+
|
348 |
+
@pytest.mark.parametrize("cast_index", [True, False])
|
349 |
+
@pytest.mark.parametrize(
|
350 |
+
"vals",
|
351 |
+
[
|
352 |
+
np.array([np.timedelta64(1, "D"), np.timedelta64(1, "D")]),
|
353 |
+
[timedelta(1), timedelta(1)],
|
354 |
+
],
|
355 |
+
)
|
356 |
+
def test_constructor_dtypes_to_timedelta(self, cast_index, vals):
|
357 |
+
if cast_index:
|
358 |
+
index = Index(vals, dtype=object)
|
359 |
+
assert isinstance(index, Index)
|
360 |
+
assert index.dtype == object
|
361 |
+
else:
|
362 |
+
index = Index(vals)
|
363 |
+
assert isinstance(index, TimedeltaIndex)
|
364 |
+
|
365 |
+
def test_pass_timedeltaindex_to_index(self):
|
366 |
+
rng = timedelta_range("1 days", "10 days")
|
367 |
+
idx = Index(rng, dtype=object)
|
368 |
+
|
369 |
+
expected = Index(rng.to_pytimedelta(), dtype=object)
|
370 |
+
|
371 |
+
tm.assert_numpy_array_equal(idx.values, expected.values)
|
372 |
+
|
373 |
+
def test_pass_datetimeindex_to_index(self):
|
374 |
+
# GH#1396
|
375 |
+
rng = date_range("1/1/2000", "3/1/2000")
|
376 |
+
idx = Index(rng, dtype=object)
|
377 |
+
|
378 |
+
expected = Index(rng.to_pydatetime(), dtype=object)
|
379 |
+
|
380 |
+
tm.assert_numpy_array_equal(idx.values, expected.values)
|
381 |
+
|
382 |
+
|
383 |
+
class TestIndexConstructorUnwrapping:
|
384 |
+
# Test passing different arraylike values to pd.Index
|
385 |
+
|
386 |
+
@pytest.mark.parametrize("klass", [Index, DatetimeIndex])
|
387 |
+
def test_constructor_from_series_dt64(self, klass):
|
388 |
+
stamps = [Timestamp("20110101"), Timestamp("20120101"), Timestamp("20130101")]
|
389 |
+
expected = DatetimeIndex(stamps)
|
390 |
+
ser = Series(stamps)
|
391 |
+
result = klass(ser)
|
392 |
+
tm.assert_index_equal(result, expected)
|
393 |
+
|
394 |
+
def test_constructor_no_pandas_array(self):
|
395 |
+
ser = Series([1, 2, 3])
|
396 |
+
result = Index(ser.array)
|
397 |
+
expected = Index([1, 2, 3])
|
398 |
+
tm.assert_index_equal(result, expected)
|
399 |
+
|
400 |
+
@pytest.mark.parametrize(
|
401 |
+
"array",
|
402 |
+
[
|
403 |
+
np.arange(5),
|
404 |
+
np.array(["a", "b", "c"]),
|
405 |
+
date_range("2000-01-01", periods=3).values,
|
406 |
+
],
|
407 |
+
)
|
408 |
+
def test_constructor_ndarray_like(self, array):
|
409 |
+
# GH#5460#issuecomment-44474502
|
410 |
+
# it should be possible to convert any object that satisfies the numpy
|
411 |
+
# ndarray interface directly into an Index
|
412 |
+
class ArrayLike:
|
413 |
+
def __init__(self, array) -> None:
|
414 |
+
self.array = array
|
415 |
+
|
416 |
+
def __array__(self, dtype=None, copy=None) -> np.ndarray:
|
417 |
+
return self.array
|
418 |
+
|
419 |
+
expected = Index(array)
|
420 |
+
result = Index(ArrayLike(array))
|
421 |
+
tm.assert_index_equal(result, expected)
|
422 |
+
|
423 |
+
|
424 |
+
class TestIndexConstructionErrors:
|
425 |
+
def test_constructor_overflow_int64(self):
|
426 |
+
# see GH#15832
|
427 |
+
msg = (
|
428 |
+
"The elements provided in the data cannot "
|
429 |
+
"all be casted to the dtype int64"
|
430 |
+
)
|
431 |
+
with pytest.raises(OverflowError, match=msg):
|
432 |
+
Index([np.iinfo(np.uint64).max - 1], dtype="int64")
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/test_indexing.py
ADDED
@@ -0,0 +1,357 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
test_indexing tests the following Index methods:
|
3 |
+
__getitem__
|
4 |
+
get_loc
|
5 |
+
get_value
|
6 |
+
__contains__
|
7 |
+
take
|
8 |
+
where
|
9 |
+
get_indexer
|
10 |
+
get_indexer_for
|
11 |
+
slice_locs
|
12 |
+
asof_locs
|
13 |
+
|
14 |
+
The corresponding tests.indexes.[index_type].test_indexing files
|
15 |
+
contain tests for the corresponding methods specific to those Index subclasses.
|
16 |
+
"""
|
17 |
+
import numpy as np
|
18 |
+
import pytest
|
19 |
+
|
20 |
+
from pandas.errors import InvalidIndexError
|
21 |
+
|
22 |
+
from pandas.core.dtypes.common import (
|
23 |
+
is_float_dtype,
|
24 |
+
is_scalar,
|
25 |
+
)
|
26 |
+
|
27 |
+
from pandas import (
|
28 |
+
NA,
|
29 |
+
DatetimeIndex,
|
30 |
+
Index,
|
31 |
+
IntervalIndex,
|
32 |
+
MultiIndex,
|
33 |
+
NaT,
|
34 |
+
PeriodIndex,
|
35 |
+
TimedeltaIndex,
|
36 |
+
)
|
37 |
+
import pandas._testing as tm
|
38 |
+
|
39 |
+
|
40 |
+
class TestTake:
|
41 |
+
def test_take_invalid_kwargs(self, index):
|
42 |
+
indices = [1, 2]
|
43 |
+
|
44 |
+
msg = r"take\(\) got an unexpected keyword argument 'foo'"
|
45 |
+
with pytest.raises(TypeError, match=msg):
|
46 |
+
index.take(indices, foo=2)
|
47 |
+
|
48 |
+
msg = "the 'out' parameter is not supported"
|
49 |
+
with pytest.raises(ValueError, match=msg):
|
50 |
+
index.take(indices, out=indices)
|
51 |
+
|
52 |
+
msg = "the 'mode' parameter is not supported"
|
53 |
+
with pytest.raises(ValueError, match=msg):
|
54 |
+
index.take(indices, mode="clip")
|
55 |
+
|
56 |
+
def test_take(self, index):
|
57 |
+
indexer = [4, 3, 0, 2]
|
58 |
+
if len(index) < 5:
|
59 |
+
pytest.skip("Test doesn't make sense since not enough elements")
|
60 |
+
|
61 |
+
result = index.take(indexer)
|
62 |
+
expected = index[indexer]
|
63 |
+
assert result.equals(expected)
|
64 |
+
|
65 |
+
if not isinstance(index, (DatetimeIndex, PeriodIndex, TimedeltaIndex)):
|
66 |
+
# GH 10791
|
67 |
+
msg = r"'(.*Index)' object has no attribute 'freq'"
|
68 |
+
with pytest.raises(AttributeError, match=msg):
|
69 |
+
index.freq
|
70 |
+
|
71 |
+
def test_take_indexer_type(self):
|
72 |
+
# GH#42875
|
73 |
+
integer_index = Index([0, 1, 2, 3])
|
74 |
+
scalar_index = 1
|
75 |
+
msg = "Expected indices to be array-like"
|
76 |
+
with pytest.raises(TypeError, match=msg):
|
77 |
+
integer_index.take(scalar_index)
|
78 |
+
|
79 |
+
def test_take_minus1_without_fill(self, index):
|
80 |
+
# -1 does not get treated as NA unless allow_fill=True is passed
|
81 |
+
if len(index) == 0:
|
82 |
+
# Test is not applicable
|
83 |
+
pytest.skip("Test doesn't make sense for empty index")
|
84 |
+
|
85 |
+
result = index.take([0, 0, -1])
|
86 |
+
|
87 |
+
expected = index.take([0, 0, len(index) - 1])
|
88 |
+
tm.assert_index_equal(result, expected)
|
89 |
+
|
90 |
+
|
91 |
+
class TestContains:
|
92 |
+
@pytest.mark.parametrize(
|
93 |
+
"index,val",
|
94 |
+
[
|
95 |
+
(Index([0, 1, 2]), 2),
|
96 |
+
(Index([0, 1, "2"]), "2"),
|
97 |
+
(Index([0, 1, 2, np.inf, 4]), 4),
|
98 |
+
(Index([0, 1, 2, np.nan, 4]), 4),
|
99 |
+
(Index([0, 1, 2, np.inf]), np.inf),
|
100 |
+
(Index([0, 1, 2, np.nan]), np.nan),
|
101 |
+
],
|
102 |
+
)
|
103 |
+
def test_index_contains(self, index, val):
|
104 |
+
assert val in index
|
105 |
+
|
106 |
+
@pytest.mark.parametrize(
|
107 |
+
"index,val",
|
108 |
+
[
|
109 |
+
(Index([0, 1, 2]), "2"),
|
110 |
+
(Index([0, 1, "2"]), 2),
|
111 |
+
(Index([0, 1, 2, np.inf]), 4),
|
112 |
+
(Index([0, 1, 2, np.nan]), 4),
|
113 |
+
(Index([0, 1, 2, np.inf]), np.nan),
|
114 |
+
(Index([0, 1, 2, np.nan]), np.inf),
|
115 |
+
# Checking if np.inf in int64 Index should not cause an OverflowError
|
116 |
+
# Related to GH 16957
|
117 |
+
(Index([0, 1, 2], dtype=np.int64), np.inf),
|
118 |
+
(Index([0, 1, 2], dtype=np.int64), np.nan),
|
119 |
+
(Index([0, 1, 2], dtype=np.uint64), np.inf),
|
120 |
+
(Index([0, 1, 2], dtype=np.uint64), np.nan),
|
121 |
+
],
|
122 |
+
)
|
123 |
+
def test_index_not_contains(self, index, val):
|
124 |
+
assert val not in index
|
125 |
+
|
126 |
+
@pytest.mark.parametrize(
|
127 |
+
"index,val", [(Index([0, 1, "2"]), 0), (Index([0, 1, "2"]), "2")]
|
128 |
+
)
|
129 |
+
def test_mixed_index_contains(self, index, val):
|
130 |
+
# GH#19860
|
131 |
+
assert val in index
|
132 |
+
|
133 |
+
@pytest.mark.parametrize(
|
134 |
+
"index,val", [(Index([0, 1, "2"]), "1"), (Index([0, 1, "2"]), 2)]
|
135 |
+
)
|
136 |
+
def test_mixed_index_not_contains(self, index, val):
|
137 |
+
# GH#19860
|
138 |
+
assert val not in index
|
139 |
+
|
140 |
+
def test_contains_with_float_index(self, any_real_numpy_dtype):
|
141 |
+
# GH#22085
|
142 |
+
dtype = any_real_numpy_dtype
|
143 |
+
data = [0, 1, 2, 3] if not is_float_dtype(dtype) else [0.1, 1.1, 2.2, 3.3]
|
144 |
+
index = Index(data, dtype=dtype)
|
145 |
+
|
146 |
+
if not is_float_dtype(index.dtype):
|
147 |
+
assert 1.1 not in index
|
148 |
+
assert 1.0 in index
|
149 |
+
assert 1 in index
|
150 |
+
else:
|
151 |
+
assert 1.1 in index
|
152 |
+
assert 1.0 not in index
|
153 |
+
assert 1 not in index
|
154 |
+
|
155 |
+
def test_contains_requires_hashable_raises(self, index):
|
156 |
+
if isinstance(index, MultiIndex):
|
157 |
+
return # TODO: do we want this to raise?
|
158 |
+
|
159 |
+
msg = "unhashable type: 'list'"
|
160 |
+
with pytest.raises(TypeError, match=msg):
|
161 |
+
[] in index
|
162 |
+
|
163 |
+
msg = "|".join(
|
164 |
+
[
|
165 |
+
r"unhashable type: 'dict'",
|
166 |
+
r"must be real number, not dict",
|
167 |
+
r"an integer is required",
|
168 |
+
r"\{\}",
|
169 |
+
r"pandas\._libs\.interval\.IntervalTree' is not iterable",
|
170 |
+
]
|
171 |
+
)
|
172 |
+
with pytest.raises(TypeError, match=msg):
|
173 |
+
{} in index._engine
|
174 |
+
|
175 |
+
|
176 |
+
class TestGetLoc:
|
177 |
+
def test_get_loc_non_hashable(self, index):
|
178 |
+
with pytest.raises(InvalidIndexError, match="[0, 1]"):
|
179 |
+
index.get_loc([0, 1])
|
180 |
+
|
181 |
+
def test_get_loc_non_scalar_hashable(self, index):
|
182 |
+
# GH52877
|
183 |
+
from enum import Enum
|
184 |
+
|
185 |
+
class E(Enum):
|
186 |
+
X1 = "x1"
|
187 |
+
|
188 |
+
assert not is_scalar(E.X1)
|
189 |
+
|
190 |
+
exc = KeyError
|
191 |
+
msg = "<E.X1: 'x1'>"
|
192 |
+
if isinstance(
|
193 |
+
index,
|
194 |
+
(
|
195 |
+
DatetimeIndex,
|
196 |
+
TimedeltaIndex,
|
197 |
+
PeriodIndex,
|
198 |
+
IntervalIndex,
|
199 |
+
),
|
200 |
+
):
|
201 |
+
# TODO: make these more consistent?
|
202 |
+
exc = InvalidIndexError
|
203 |
+
msg = "E.X1"
|
204 |
+
with pytest.raises(exc, match=msg):
|
205 |
+
index.get_loc(E.X1)
|
206 |
+
|
207 |
+
def test_get_loc_generator(self, index):
|
208 |
+
exc = KeyError
|
209 |
+
if isinstance(
|
210 |
+
index,
|
211 |
+
(
|
212 |
+
DatetimeIndex,
|
213 |
+
TimedeltaIndex,
|
214 |
+
PeriodIndex,
|
215 |
+
IntervalIndex,
|
216 |
+
MultiIndex,
|
217 |
+
),
|
218 |
+
):
|
219 |
+
# TODO: make these more consistent?
|
220 |
+
exc = InvalidIndexError
|
221 |
+
with pytest.raises(exc, match="generator object"):
|
222 |
+
# MultiIndex specifically checks for generator; others for scalar
|
223 |
+
index.get_loc(x for x in range(5))
|
224 |
+
|
225 |
+
def test_get_loc_masked_duplicated_na(self):
|
226 |
+
# GH#48411
|
227 |
+
idx = Index([1, 2, NA, NA], dtype="Int64")
|
228 |
+
result = idx.get_loc(NA)
|
229 |
+
expected = np.array([False, False, True, True])
|
230 |
+
tm.assert_numpy_array_equal(result, expected)
|
231 |
+
|
232 |
+
|
233 |
+
class TestGetIndexer:
|
234 |
+
def test_get_indexer_base(self, index):
|
235 |
+
if index._index_as_unique:
|
236 |
+
expected = np.arange(index.size, dtype=np.intp)
|
237 |
+
actual = index.get_indexer(index)
|
238 |
+
tm.assert_numpy_array_equal(expected, actual)
|
239 |
+
else:
|
240 |
+
msg = "Reindexing only valid with uniquely valued Index objects"
|
241 |
+
with pytest.raises(InvalidIndexError, match=msg):
|
242 |
+
index.get_indexer(index)
|
243 |
+
|
244 |
+
with pytest.raises(ValueError, match="Invalid fill method"):
|
245 |
+
index.get_indexer(index, method="invalid")
|
246 |
+
|
247 |
+
def test_get_indexer_consistency(self, index):
|
248 |
+
# See GH#16819
|
249 |
+
|
250 |
+
if index._index_as_unique:
|
251 |
+
indexer = index.get_indexer(index[0:2])
|
252 |
+
assert isinstance(indexer, np.ndarray)
|
253 |
+
assert indexer.dtype == np.intp
|
254 |
+
else:
|
255 |
+
msg = "Reindexing only valid with uniquely valued Index objects"
|
256 |
+
with pytest.raises(InvalidIndexError, match=msg):
|
257 |
+
index.get_indexer(index[0:2])
|
258 |
+
|
259 |
+
indexer, _ = index.get_indexer_non_unique(index[0:2])
|
260 |
+
assert isinstance(indexer, np.ndarray)
|
261 |
+
assert indexer.dtype == np.intp
|
262 |
+
|
263 |
+
def test_get_indexer_masked_duplicated_na(self):
|
264 |
+
# GH#48411
|
265 |
+
idx = Index([1, 2, NA, NA], dtype="Int64")
|
266 |
+
result = idx.get_indexer_for(Index([1, NA], dtype="Int64"))
|
267 |
+
expected = np.array([0, 2, 3], dtype=result.dtype)
|
268 |
+
tm.assert_numpy_array_equal(result, expected)
|
269 |
+
|
270 |
+
|
271 |
+
class TestConvertSliceIndexer:
|
272 |
+
def test_convert_almost_null_slice(self, index):
|
273 |
+
# slice with None at both ends, but not step
|
274 |
+
|
275 |
+
key = slice(None, None, "foo")
|
276 |
+
|
277 |
+
if isinstance(index, IntervalIndex):
|
278 |
+
msg = "label-based slicing with step!=1 is not supported for IntervalIndex"
|
279 |
+
with pytest.raises(ValueError, match=msg):
|
280 |
+
index._convert_slice_indexer(key, "loc")
|
281 |
+
else:
|
282 |
+
msg = "'>=' not supported between instances of 'str' and 'int'"
|
283 |
+
with pytest.raises(TypeError, match=msg):
|
284 |
+
index._convert_slice_indexer(key, "loc")
|
285 |
+
|
286 |
+
|
287 |
+
class TestPutmask:
|
288 |
+
def test_putmask_with_wrong_mask(self, index):
|
289 |
+
# GH#18368
|
290 |
+
if not len(index):
|
291 |
+
pytest.skip("Test doesn't make sense for empty index")
|
292 |
+
|
293 |
+
fill = index[0]
|
294 |
+
|
295 |
+
msg = "putmask: mask and data must be the same size"
|
296 |
+
with pytest.raises(ValueError, match=msg):
|
297 |
+
index.putmask(np.ones(len(index) + 1, np.bool_), fill)
|
298 |
+
|
299 |
+
with pytest.raises(ValueError, match=msg):
|
300 |
+
index.putmask(np.ones(len(index) - 1, np.bool_), fill)
|
301 |
+
|
302 |
+
with pytest.raises(ValueError, match=msg):
|
303 |
+
index.putmask("foo", fill)
|
304 |
+
|
305 |
+
|
306 |
+
@pytest.mark.parametrize(
|
307 |
+
"idx", [Index([1, 2, 3]), Index([0.1, 0.2, 0.3]), Index(["a", "b", "c"])]
|
308 |
+
)
|
309 |
+
def test_getitem_deprecated_float(idx):
|
310 |
+
# https://github.com/pandas-dev/pandas/issues/34191
|
311 |
+
|
312 |
+
msg = "Indexing with a float is no longer supported"
|
313 |
+
with pytest.raises(IndexError, match=msg):
|
314 |
+
idx[1.0]
|
315 |
+
|
316 |
+
|
317 |
+
@pytest.mark.parametrize(
|
318 |
+
"idx,target,expected",
|
319 |
+
[
|
320 |
+
([np.nan, "var1", np.nan], [np.nan], np.array([0, 2], dtype=np.intp)),
|
321 |
+
(
|
322 |
+
[np.nan, "var1", np.nan],
|
323 |
+
[np.nan, "var1"],
|
324 |
+
np.array([0, 2, 1], dtype=np.intp),
|
325 |
+
),
|
326 |
+
(
|
327 |
+
np.array([np.nan, "var1", np.nan], dtype=object),
|
328 |
+
[np.nan],
|
329 |
+
np.array([0, 2], dtype=np.intp),
|
330 |
+
),
|
331 |
+
(
|
332 |
+
DatetimeIndex(["2020-08-05", NaT, NaT]),
|
333 |
+
[NaT],
|
334 |
+
np.array([1, 2], dtype=np.intp),
|
335 |
+
),
|
336 |
+
(["a", "b", "a", np.nan], [np.nan], np.array([3], dtype=np.intp)),
|
337 |
+
(
|
338 |
+
np.array(["b", np.nan, float("NaN"), "b"], dtype=object),
|
339 |
+
Index([np.nan], dtype=object),
|
340 |
+
np.array([1, 2], dtype=np.intp),
|
341 |
+
),
|
342 |
+
],
|
343 |
+
)
|
344 |
+
def test_get_indexer_non_unique_multiple_nans(idx, target, expected):
|
345 |
+
# GH 35392
|
346 |
+
axis = Index(idx)
|
347 |
+
actual = axis.get_indexer_for(target)
|
348 |
+
tm.assert_numpy_array_equal(actual, expected)
|
349 |
+
|
350 |
+
|
351 |
+
def test_get_indexer_non_unique_nans_in_object_dtype_target(nulls_fixture):
|
352 |
+
idx = Index([1.0, 2.0])
|
353 |
+
target = Index([1, nulls_fixture], dtype="object")
|
354 |
+
|
355 |
+
result_idx, result_missing = idx.get_indexer_non_unique(target)
|
356 |
+
tm.assert_numpy_array_equal(result_idx, np.array([0, -1], dtype=np.intp))
|
357 |
+
tm.assert_numpy_array_equal(result_missing, np.array([1], dtype=np.intp))
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/test_numpy_compat.py
ADDED
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas import (
|
5 |
+
CategoricalIndex,
|
6 |
+
DatetimeIndex,
|
7 |
+
Index,
|
8 |
+
PeriodIndex,
|
9 |
+
TimedeltaIndex,
|
10 |
+
isna,
|
11 |
+
)
|
12 |
+
import pandas._testing as tm
|
13 |
+
from pandas.api.types import (
|
14 |
+
is_complex_dtype,
|
15 |
+
is_numeric_dtype,
|
16 |
+
)
|
17 |
+
from pandas.core.arrays import BooleanArray
|
18 |
+
from pandas.core.indexes.datetimelike import DatetimeIndexOpsMixin
|
19 |
+
|
20 |
+
|
21 |
+
def test_numpy_ufuncs_out(index):
|
22 |
+
result = index == index
|
23 |
+
|
24 |
+
out = np.empty(index.shape, dtype=bool)
|
25 |
+
np.equal(index, index, out=out)
|
26 |
+
tm.assert_numpy_array_equal(out, result)
|
27 |
+
|
28 |
+
if not index._is_multi:
|
29 |
+
# same thing on the ExtensionArray
|
30 |
+
out = np.empty(index.shape, dtype=bool)
|
31 |
+
np.equal(index.array, index.array, out=out)
|
32 |
+
tm.assert_numpy_array_equal(out, result)
|
33 |
+
|
34 |
+
|
35 |
+
@pytest.mark.parametrize(
|
36 |
+
"func",
|
37 |
+
[
|
38 |
+
np.exp,
|
39 |
+
np.exp2,
|
40 |
+
np.expm1,
|
41 |
+
np.log,
|
42 |
+
np.log2,
|
43 |
+
np.log10,
|
44 |
+
np.log1p,
|
45 |
+
np.sqrt,
|
46 |
+
np.sin,
|
47 |
+
np.cos,
|
48 |
+
np.tan,
|
49 |
+
np.arcsin,
|
50 |
+
np.arccos,
|
51 |
+
np.arctan,
|
52 |
+
np.sinh,
|
53 |
+
np.cosh,
|
54 |
+
np.tanh,
|
55 |
+
np.arcsinh,
|
56 |
+
np.arccosh,
|
57 |
+
np.arctanh,
|
58 |
+
np.deg2rad,
|
59 |
+
np.rad2deg,
|
60 |
+
],
|
61 |
+
ids=lambda x: x.__name__,
|
62 |
+
)
|
63 |
+
def test_numpy_ufuncs_basic(index, func):
|
64 |
+
# test ufuncs of numpy, see:
|
65 |
+
# https://numpy.org/doc/stable/reference/ufuncs.html
|
66 |
+
|
67 |
+
if isinstance(index, DatetimeIndexOpsMixin):
|
68 |
+
with tm.external_error_raised((TypeError, AttributeError)):
|
69 |
+
with np.errstate(all="ignore"):
|
70 |
+
func(index)
|
71 |
+
elif is_numeric_dtype(index) and not (
|
72 |
+
is_complex_dtype(index) and func in [np.deg2rad, np.rad2deg]
|
73 |
+
):
|
74 |
+
# coerces to float (e.g. np.sin)
|
75 |
+
with np.errstate(all="ignore"):
|
76 |
+
result = func(index)
|
77 |
+
arr_result = func(index.values)
|
78 |
+
if arr_result.dtype == np.float16:
|
79 |
+
arr_result = arr_result.astype(np.float32)
|
80 |
+
exp = Index(arr_result, name=index.name)
|
81 |
+
|
82 |
+
tm.assert_index_equal(result, exp)
|
83 |
+
if isinstance(index.dtype, np.dtype) and is_numeric_dtype(index):
|
84 |
+
if is_complex_dtype(index):
|
85 |
+
assert result.dtype == index.dtype
|
86 |
+
elif index.dtype in ["bool", "int8", "uint8"]:
|
87 |
+
assert result.dtype in ["float16", "float32"]
|
88 |
+
elif index.dtype in ["int16", "uint16", "float32"]:
|
89 |
+
assert result.dtype == "float32"
|
90 |
+
else:
|
91 |
+
assert result.dtype == "float64"
|
92 |
+
else:
|
93 |
+
# e.g. np.exp with Int64 -> Float64
|
94 |
+
assert type(result) is Index
|
95 |
+
# raise AttributeError or TypeError
|
96 |
+
elif len(index) == 0:
|
97 |
+
pass
|
98 |
+
else:
|
99 |
+
with tm.external_error_raised((TypeError, AttributeError)):
|
100 |
+
with np.errstate(all="ignore"):
|
101 |
+
func(index)
|
102 |
+
|
103 |
+
|
104 |
+
@pytest.mark.parametrize(
|
105 |
+
"func", [np.isfinite, np.isinf, np.isnan, np.signbit], ids=lambda x: x.__name__
|
106 |
+
)
|
107 |
+
def test_numpy_ufuncs_other(index, func):
|
108 |
+
# test ufuncs of numpy, see:
|
109 |
+
# https://numpy.org/doc/stable/reference/ufuncs.html
|
110 |
+
if isinstance(index, (DatetimeIndex, TimedeltaIndex)):
|
111 |
+
if func in (np.isfinite, np.isinf, np.isnan):
|
112 |
+
# numpy 1.18 changed isinf and isnan to not raise on dt64/td64
|
113 |
+
result = func(index)
|
114 |
+
assert isinstance(result, np.ndarray)
|
115 |
+
|
116 |
+
out = np.empty(index.shape, dtype=bool)
|
117 |
+
func(index, out=out)
|
118 |
+
tm.assert_numpy_array_equal(out, result)
|
119 |
+
else:
|
120 |
+
with tm.external_error_raised(TypeError):
|
121 |
+
func(index)
|
122 |
+
|
123 |
+
elif isinstance(index, PeriodIndex):
|
124 |
+
with tm.external_error_raised(TypeError):
|
125 |
+
func(index)
|
126 |
+
|
127 |
+
elif is_numeric_dtype(index) and not (
|
128 |
+
is_complex_dtype(index) and func is np.signbit
|
129 |
+
):
|
130 |
+
# Results in bool array
|
131 |
+
result = func(index)
|
132 |
+
if not isinstance(index.dtype, np.dtype):
|
133 |
+
# e.g. Int64 we expect to get BooleanArray back
|
134 |
+
assert isinstance(result, BooleanArray)
|
135 |
+
else:
|
136 |
+
assert isinstance(result, np.ndarray)
|
137 |
+
|
138 |
+
out = np.empty(index.shape, dtype=bool)
|
139 |
+
func(index, out=out)
|
140 |
+
|
141 |
+
if not isinstance(index.dtype, np.dtype):
|
142 |
+
tm.assert_numpy_array_equal(out, result._data)
|
143 |
+
else:
|
144 |
+
tm.assert_numpy_array_equal(out, result)
|
145 |
+
|
146 |
+
elif len(index) == 0:
|
147 |
+
pass
|
148 |
+
else:
|
149 |
+
with tm.external_error_raised(TypeError):
|
150 |
+
func(index)
|
151 |
+
|
152 |
+
|
153 |
+
@pytest.mark.parametrize("func", [np.maximum, np.minimum])
|
154 |
+
def test_numpy_ufuncs_reductions(index, func, request):
|
155 |
+
# TODO: overlap with tests.series.test_ufunc.test_reductions
|
156 |
+
if len(index) == 0:
|
157 |
+
pytest.skip("Test doesn't make sense for empty index.")
|
158 |
+
|
159 |
+
if isinstance(index, CategoricalIndex) and index.dtype.ordered is False:
|
160 |
+
with pytest.raises(TypeError, match="is not ordered for"):
|
161 |
+
func.reduce(index)
|
162 |
+
return
|
163 |
+
else:
|
164 |
+
result = func.reduce(index)
|
165 |
+
|
166 |
+
if func is np.maximum:
|
167 |
+
expected = index.max(skipna=False)
|
168 |
+
else:
|
169 |
+
expected = index.min(skipna=False)
|
170 |
+
# TODO: do we have cases both with and without NAs?
|
171 |
+
|
172 |
+
assert type(result) is type(expected)
|
173 |
+
if isna(result):
|
174 |
+
assert isna(expected)
|
175 |
+
else:
|
176 |
+
assert result == expected
|
177 |
+
|
178 |
+
|
179 |
+
@pytest.mark.parametrize("func", [np.bitwise_and, np.bitwise_or, np.bitwise_xor])
|
180 |
+
def test_numpy_ufuncs_bitwise(func):
|
181 |
+
# https://github.com/pandas-dev/pandas/issues/46769
|
182 |
+
idx1 = Index([1, 2, 3, 4], dtype="int64")
|
183 |
+
idx2 = Index([3, 4, 5, 6], dtype="int64")
|
184 |
+
|
185 |
+
with tm.assert_produces_warning(None):
|
186 |
+
result = func(idx1, idx2)
|
187 |
+
|
188 |
+
expected = Index(func(idx1.values, idx2.values))
|
189 |
+
tm.assert_index_equal(result, expected)
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/test_old_base.py
ADDED
@@ -0,0 +1,1061 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
from datetime import datetime
|
4 |
+
import weakref
|
5 |
+
|
6 |
+
import numpy as np
|
7 |
+
import pytest
|
8 |
+
|
9 |
+
from pandas._config import using_pyarrow_string_dtype
|
10 |
+
|
11 |
+
from pandas._libs.tslibs import Timestamp
|
12 |
+
|
13 |
+
from pandas.core.dtypes.common import (
|
14 |
+
is_integer_dtype,
|
15 |
+
is_numeric_dtype,
|
16 |
+
)
|
17 |
+
from pandas.core.dtypes.dtypes import CategoricalDtype
|
18 |
+
|
19 |
+
import pandas as pd
|
20 |
+
from pandas import (
|
21 |
+
CategoricalIndex,
|
22 |
+
DatetimeIndex,
|
23 |
+
DatetimeTZDtype,
|
24 |
+
Index,
|
25 |
+
IntervalIndex,
|
26 |
+
MultiIndex,
|
27 |
+
PeriodIndex,
|
28 |
+
RangeIndex,
|
29 |
+
Series,
|
30 |
+
TimedeltaIndex,
|
31 |
+
isna,
|
32 |
+
period_range,
|
33 |
+
)
|
34 |
+
import pandas._testing as tm
|
35 |
+
import pandas.core.algorithms as algos
|
36 |
+
from pandas.core.arrays import BaseMaskedArray
|
37 |
+
|
38 |
+
|
39 |
+
class TestBase:
|
40 |
+
@pytest.fixture(
|
41 |
+
params=[
|
42 |
+
RangeIndex(start=0, stop=20, step=2),
|
43 |
+
Index(np.arange(5, dtype=np.float64)),
|
44 |
+
Index(np.arange(5, dtype=np.float32)),
|
45 |
+
Index(np.arange(5, dtype=np.uint64)),
|
46 |
+
Index(range(0, 20, 2), dtype=np.int64),
|
47 |
+
Index(range(0, 20, 2), dtype=np.int32),
|
48 |
+
Index(range(0, 20, 2), dtype=np.int16),
|
49 |
+
Index(range(0, 20, 2), dtype=np.int8),
|
50 |
+
Index(list("abcde")),
|
51 |
+
Index([0, "a", 1, "b", 2, "c"]),
|
52 |
+
period_range("20130101", periods=5, freq="D"),
|
53 |
+
TimedeltaIndex(
|
54 |
+
[
|
55 |
+
"0 days 01:00:00",
|
56 |
+
"1 days 01:00:00",
|
57 |
+
"2 days 01:00:00",
|
58 |
+
"3 days 01:00:00",
|
59 |
+
"4 days 01:00:00",
|
60 |
+
],
|
61 |
+
dtype="timedelta64[ns]",
|
62 |
+
freq="D",
|
63 |
+
),
|
64 |
+
DatetimeIndex(
|
65 |
+
["2013-01-01", "2013-01-02", "2013-01-03", "2013-01-04", "2013-01-05"],
|
66 |
+
dtype="datetime64[ns]",
|
67 |
+
freq="D",
|
68 |
+
),
|
69 |
+
IntervalIndex.from_breaks(range(11), closed="right"),
|
70 |
+
]
|
71 |
+
)
|
72 |
+
def simple_index(self, request):
|
73 |
+
return request.param
|
74 |
+
|
75 |
+
def test_pickle_compat_construction(self, simple_index):
|
76 |
+
# need an object to create with
|
77 |
+
if isinstance(simple_index, RangeIndex):
|
78 |
+
pytest.skip("RangeIndex() is a valid constructor")
|
79 |
+
msg = "|".join(
|
80 |
+
[
|
81 |
+
r"Index\(\.\.\.\) must be called with a collection of some "
|
82 |
+
r"kind, None was passed",
|
83 |
+
r"DatetimeIndex\(\) must be called with a collection of some "
|
84 |
+
r"kind, None was passed",
|
85 |
+
r"TimedeltaIndex\(\) must be called with a collection of some "
|
86 |
+
r"kind, None was passed",
|
87 |
+
r"__new__\(\) missing 1 required positional argument: 'data'",
|
88 |
+
r"__new__\(\) takes at least 2 arguments \(1 given\)",
|
89 |
+
]
|
90 |
+
)
|
91 |
+
with pytest.raises(TypeError, match=msg):
|
92 |
+
type(simple_index)()
|
93 |
+
|
94 |
+
def test_shift(self, simple_index):
|
95 |
+
# GH8083 test the base class for shift
|
96 |
+
if isinstance(simple_index, (DatetimeIndex, TimedeltaIndex, PeriodIndex)):
|
97 |
+
pytest.skip("Tested in test_ops/test_arithmetic")
|
98 |
+
idx = simple_index
|
99 |
+
msg = (
|
100 |
+
f"This method is only implemented for DatetimeIndex, PeriodIndex and "
|
101 |
+
f"TimedeltaIndex; Got type {type(idx).__name__}"
|
102 |
+
)
|
103 |
+
with pytest.raises(NotImplementedError, match=msg):
|
104 |
+
idx.shift(1)
|
105 |
+
with pytest.raises(NotImplementedError, match=msg):
|
106 |
+
idx.shift(1, 2)
|
107 |
+
|
108 |
+
def test_constructor_name_unhashable(self, simple_index):
|
109 |
+
# GH#29069 check that name is hashable
|
110 |
+
# See also same-named test in tests.series.test_constructors
|
111 |
+
idx = simple_index
|
112 |
+
with pytest.raises(TypeError, match="Index.name must be a hashable type"):
|
113 |
+
type(idx)(idx, name=[])
|
114 |
+
|
115 |
+
def test_create_index_existing_name(self, simple_index):
|
116 |
+
# GH11193, when an existing index is passed, and a new name is not
|
117 |
+
# specified, the new index should inherit the previous object name
|
118 |
+
expected = simple_index.copy()
|
119 |
+
if not isinstance(expected, MultiIndex):
|
120 |
+
expected.name = "foo"
|
121 |
+
result = Index(expected)
|
122 |
+
tm.assert_index_equal(result, expected)
|
123 |
+
|
124 |
+
result = Index(expected, name="bar")
|
125 |
+
expected.name = "bar"
|
126 |
+
tm.assert_index_equal(result, expected)
|
127 |
+
else:
|
128 |
+
expected.names = ["foo", "bar"]
|
129 |
+
result = Index(expected)
|
130 |
+
tm.assert_index_equal(
|
131 |
+
result,
|
132 |
+
Index(
|
133 |
+
Index(
|
134 |
+
[
|
135 |
+
("foo", "one"),
|
136 |
+
("foo", "two"),
|
137 |
+
("bar", "one"),
|
138 |
+
("baz", "two"),
|
139 |
+
("qux", "one"),
|
140 |
+
("qux", "two"),
|
141 |
+
],
|
142 |
+
dtype="object",
|
143 |
+
),
|
144 |
+
names=["foo", "bar"],
|
145 |
+
),
|
146 |
+
)
|
147 |
+
|
148 |
+
result = Index(expected, names=["A", "B"])
|
149 |
+
tm.assert_index_equal(
|
150 |
+
result,
|
151 |
+
Index(
|
152 |
+
Index(
|
153 |
+
[
|
154 |
+
("foo", "one"),
|
155 |
+
("foo", "two"),
|
156 |
+
("bar", "one"),
|
157 |
+
("baz", "two"),
|
158 |
+
("qux", "one"),
|
159 |
+
("qux", "two"),
|
160 |
+
],
|
161 |
+
dtype="object",
|
162 |
+
),
|
163 |
+
names=["A", "B"],
|
164 |
+
),
|
165 |
+
)
|
166 |
+
|
167 |
+
def test_numeric_compat(self, simple_index):
|
168 |
+
idx = simple_index
|
169 |
+
# Check that this doesn't cover MultiIndex case, if/when it does,
|
170 |
+
# we can remove multi.test_compat.test_numeric_compat
|
171 |
+
assert not isinstance(idx, MultiIndex)
|
172 |
+
if type(idx) is Index:
|
173 |
+
pytest.skip("Not applicable for Index")
|
174 |
+
if is_numeric_dtype(simple_index.dtype) or isinstance(
|
175 |
+
simple_index, TimedeltaIndex
|
176 |
+
):
|
177 |
+
pytest.skip("Tested elsewhere.")
|
178 |
+
|
179 |
+
typ = type(idx._data).__name__
|
180 |
+
cls = type(idx).__name__
|
181 |
+
lmsg = "|".join(
|
182 |
+
[
|
183 |
+
rf"unsupported operand type\(s\) for \*: '{typ}' and 'int'",
|
184 |
+
"cannot perform (__mul__|__truediv__|__floordiv__) with "
|
185 |
+
f"this index type: ({cls}|{typ})",
|
186 |
+
]
|
187 |
+
)
|
188 |
+
with pytest.raises(TypeError, match=lmsg):
|
189 |
+
idx * 1
|
190 |
+
rmsg = "|".join(
|
191 |
+
[
|
192 |
+
rf"unsupported operand type\(s\) for \*: 'int' and '{typ}'",
|
193 |
+
"cannot perform (__rmul__|__rtruediv__|__rfloordiv__) with "
|
194 |
+
f"this index type: ({cls}|{typ})",
|
195 |
+
]
|
196 |
+
)
|
197 |
+
with pytest.raises(TypeError, match=rmsg):
|
198 |
+
1 * idx
|
199 |
+
|
200 |
+
div_err = lmsg.replace("*", "/")
|
201 |
+
with pytest.raises(TypeError, match=div_err):
|
202 |
+
idx / 1
|
203 |
+
div_err = rmsg.replace("*", "/")
|
204 |
+
with pytest.raises(TypeError, match=div_err):
|
205 |
+
1 / idx
|
206 |
+
|
207 |
+
floordiv_err = lmsg.replace("*", "//")
|
208 |
+
with pytest.raises(TypeError, match=floordiv_err):
|
209 |
+
idx // 1
|
210 |
+
floordiv_err = rmsg.replace("*", "//")
|
211 |
+
with pytest.raises(TypeError, match=floordiv_err):
|
212 |
+
1 // idx
|
213 |
+
|
214 |
+
def test_logical_compat(self, simple_index):
|
215 |
+
if simple_index.dtype in (object, "string"):
|
216 |
+
pytest.skip("Tested elsewhere.")
|
217 |
+
idx = simple_index
|
218 |
+
if idx.dtype.kind in "iufcbm":
|
219 |
+
assert idx.all() == idx._values.all()
|
220 |
+
assert idx.all() == idx.to_series().all()
|
221 |
+
assert idx.any() == idx._values.any()
|
222 |
+
assert idx.any() == idx.to_series().any()
|
223 |
+
else:
|
224 |
+
msg = "cannot perform (any|all)"
|
225 |
+
if isinstance(idx, IntervalIndex):
|
226 |
+
msg = (
|
227 |
+
r"'IntervalArray' with dtype interval\[.*\] does "
|
228 |
+
"not support reduction '(any|all)'"
|
229 |
+
)
|
230 |
+
with pytest.raises(TypeError, match=msg):
|
231 |
+
idx.all()
|
232 |
+
with pytest.raises(TypeError, match=msg):
|
233 |
+
idx.any()
|
234 |
+
|
235 |
+
def test_repr_roundtrip(self, simple_index):
|
236 |
+
if isinstance(simple_index, IntervalIndex):
|
237 |
+
pytest.skip(f"Not a valid repr for {type(simple_index).__name__}")
|
238 |
+
idx = simple_index
|
239 |
+
tm.assert_index_equal(eval(repr(idx)), idx)
|
240 |
+
|
241 |
+
def test_repr_max_seq_item_setting(self, simple_index):
|
242 |
+
# GH10182
|
243 |
+
if isinstance(simple_index, IntervalIndex):
|
244 |
+
pytest.skip(f"Not a valid repr for {type(simple_index).__name__}")
|
245 |
+
idx = simple_index
|
246 |
+
idx = idx.repeat(50)
|
247 |
+
with pd.option_context("display.max_seq_items", None):
|
248 |
+
repr(idx)
|
249 |
+
assert "..." not in str(idx)
|
250 |
+
|
251 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
252 |
+
def test_ensure_copied_data(self, index):
|
253 |
+
# Check the "copy" argument of each Index.__new__ is honoured
|
254 |
+
# GH12309
|
255 |
+
init_kwargs = {}
|
256 |
+
if isinstance(index, PeriodIndex):
|
257 |
+
# Needs "freq" specification:
|
258 |
+
init_kwargs["freq"] = index.freq
|
259 |
+
elif isinstance(index, (RangeIndex, MultiIndex, CategoricalIndex)):
|
260 |
+
pytest.skip(
|
261 |
+
"RangeIndex cannot be initialized from data, "
|
262 |
+
"MultiIndex and CategoricalIndex are tested separately"
|
263 |
+
)
|
264 |
+
elif index.dtype == object and index.inferred_type == "boolean":
|
265 |
+
init_kwargs["dtype"] = index.dtype
|
266 |
+
|
267 |
+
index_type = type(index)
|
268 |
+
result = index_type(index.values, copy=True, **init_kwargs)
|
269 |
+
if isinstance(index.dtype, DatetimeTZDtype):
|
270 |
+
result = result.tz_localize("UTC").tz_convert(index.tz)
|
271 |
+
if isinstance(index, (DatetimeIndex, TimedeltaIndex)):
|
272 |
+
index = index._with_freq(None)
|
273 |
+
|
274 |
+
tm.assert_index_equal(index, result)
|
275 |
+
|
276 |
+
if isinstance(index, PeriodIndex):
|
277 |
+
# .values an object array of Period, thus copied
|
278 |
+
depr_msg = "The 'ordinal' keyword in PeriodIndex is deprecated"
|
279 |
+
with tm.assert_produces_warning(FutureWarning, match=depr_msg):
|
280 |
+
result = index_type(ordinal=index.asi8, copy=False, **init_kwargs)
|
281 |
+
tm.assert_numpy_array_equal(index.asi8, result.asi8, check_same="same")
|
282 |
+
elif isinstance(index, IntervalIndex):
|
283 |
+
# checked in test_interval.py
|
284 |
+
pass
|
285 |
+
elif type(index) is Index and not isinstance(index.dtype, np.dtype):
|
286 |
+
result = index_type(index.values, copy=False, **init_kwargs)
|
287 |
+
tm.assert_index_equal(result, index)
|
288 |
+
|
289 |
+
if isinstance(index._values, BaseMaskedArray):
|
290 |
+
assert np.shares_memory(index._values._data, result._values._data)
|
291 |
+
tm.assert_numpy_array_equal(
|
292 |
+
index._values._data, result._values._data, check_same="same"
|
293 |
+
)
|
294 |
+
assert np.shares_memory(index._values._mask, result._values._mask)
|
295 |
+
tm.assert_numpy_array_equal(
|
296 |
+
index._values._mask, result._values._mask, check_same="same"
|
297 |
+
)
|
298 |
+
elif index.dtype == "string[python]":
|
299 |
+
assert np.shares_memory(index._values._ndarray, result._values._ndarray)
|
300 |
+
tm.assert_numpy_array_equal(
|
301 |
+
index._values._ndarray, result._values._ndarray, check_same="same"
|
302 |
+
)
|
303 |
+
elif index.dtype in ("string[pyarrow]", "string[pyarrow_numpy]"):
|
304 |
+
assert tm.shares_memory(result._values, index._values)
|
305 |
+
else:
|
306 |
+
raise NotImplementedError(index.dtype)
|
307 |
+
else:
|
308 |
+
result = index_type(index.values, copy=False, **init_kwargs)
|
309 |
+
tm.assert_numpy_array_equal(index.values, result.values, check_same="same")
|
310 |
+
|
311 |
+
def test_memory_usage(self, index):
|
312 |
+
index._engine.clear_mapping()
|
313 |
+
result = index.memory_usage()
|
314 |
+
if index.empty:
|
315 |
+
# we report 0 for no-length
|
316 |
+
assert result == 0
|
317 |
+
return
|
318 |
+
|
319 |
+
# non-zero length
|
320 |
+
index.get_loc(index[0])
|
321 |
+
result2 = index.memory_usage()
|
322 |
+
result3 = index.memory_usage(deep=True)
|
323 |
+
|
324 |
+
# RangeIndex, IntervalIndex
|
325 |
+
# don't have engines
|
326 |
+
# Index[EA] has engine but it does not have a Hashtable .mapping
|
327 |
+
if not isinstance(index, (RangeIndex, IntervalIndex)) and not (
|
328 |
+
type(index) is Index and not isinstance(index.dtype, np.dtype)
|
329 |
+
):
|
330 |
+
assert result2 > result
|
331 |
+
|
332 |
+
if index.inferred_type == "object":
|
333 |
+
assert result3 > result2
|
334 |
+
|
335 |
+
def test_argsort(self, index):
|
336 |
+
if isinstance(index, CategoricalIndex):
|
337 |
+
pytest.skip(f"{type(self).__name__} separately tested")
|
338 |
+
|
339 |
+
result = index.argsort()
|
340 |
+
expected = np.array(index).argsort()
|
341 |
+
tm.assert_numpy_array_equal(result, expected, check_dtype=False)
|
342 |
+
|
343 |
+
def test_numpy_argsort(self, index):
|
344 |
+
result = np.argsort(index)
|
345 |
+
expected = index.argsort()
|
346 |
+
tm.assert_numpy_array_equal(result, expected)
|
347 |
+
|
348 |
+
result = np.argsort(index, kind="mergesort")
|
349 |
+
expected = index.argsort(kind="mergesort")
|
350 |
+
tm.assert_numpy_array_equal(result, expected)
|
351 |
+
|
352 |
+
# these are the only two types that perform
|
353 |
+
# pandas compatibility input validation - the
|
354 |
+
# rest already perform separate (or no) such
|
355 |
+
# validation via their 'values' attribute as
|
356 |
+
# defined in pandas.core.indexes/base.py - they
|
357 |
+
# cannot be changed at the moment due to
|
358 |
+
# backwards compatibility concerns
|
359 |
+
if isinstance(index, (CategoricalIndex, RangeIndex)):
|
360 |
+
msg = "the 'axis' parameter is not supported"
|
361 |
+
with pytest.raises(ValueError, match=msg):
|
362 |
+
np.argsort(index, axis=1)
|
363 |
+
|
364 |
+
msg = "the 'order' parameter is not supported"
|
365 |
+
with pytest.raises(ValueError, match=msg):
|
366 |
+
np.argsort(index, order=("a", "b"))
|
367 |
+
|
368 |
+
def test_repeat(self, simple_index):
|
369 |
+
rep = 2
|
370 |
+
idx = simple_index.copy()
|
371 |
+
new_index_cls = idx._constructor
|
372 |
+
expected = new_index_cls(idx.values.repeat(rep), name=idx.name)
|
373 |
+
tm.assert_index_equal(idx.repeat(rep), expected)
|
374 |
+
|
375 |
+
idx = simple_index
|
376 |
+
rep = np.arange(len(idx))
|
377 |
+
expected = new_index_cls(idx.values.repeat(rep), name=idx.name)
|
378 |
+
tm.assert_index_equal(idx.repeat(rep), expected)
|
379 |
+
|
380 |
+
def test_numpy_repeat(self, simple_index):
|
381 |
+
rep = 2
|
382 |
+
idx = simple_index
|
383 |
+
expected = idx.repeat(rep)
|
384 |
+
tm.assert_index_equal(np.repeat(idx, rep), expected)
|
385 |
+
|
386 |
+
msg = "the 'axis' parameter is not supported"
|
387 |
+
with pytest.raises(ValueError, match=msg):
|
388 |
+
np.repeat(idx, rep, axis=0)
|
389 |
+
|
390 |
+
def test_where(self, listlike_box, simple_index):
|
391 |
+
if isinstance(simple_index, (IntervalIndex, PeriodIndex)) or is_numeric_dtype(
|
392 |
+
simple_index.dtype
|
393 |
+
):
|
394 |
+
pytest.skip("Tested elsewhere.")
|
395 |
+
klass = listlike_box
|
396 |
+
|
397 |
+
idx = simple_index
|
398 |
+
if isinstance(idx, (DatetimeIndex, TimedeltaIndex)):
|
399 |
+
# where does not preserve freq
|
400 |
+
idx = idx._with_freq(None)
|
401 |
+
|
402 |
+
cond = [True] * len(idx)
|
403 |
+
result = idx.where(klass(cond))
|
404 |
+
expected = idx
|
405 |
+
tm.assert_index_equal(result, expected)
|
406 |
+
|
407 |
+
cond = [False] + [True] * len(idx[1:])
|
408 |
+
expected = Index([idx._na_value] + idx[1:].tolist(), dtype=idx.dtype)
|
409 |
+
result = idx.where(klass(cond))
|
410 |
+
tm.assert_index_equal(result, expected)
|
411 |
+
|
412 |
+
def test_insert_base(self, index):
|
413 |
+
trimmed = index[1:4]
|
414 |
+
|
415 |
+
if not len(index):
|
416 |
+
pytest.skip("Not applicable for empty index")
|
417 |
+
|
418 |
+
# test 0th element
|
419 |
+
warn = None
|
420 |
+
if index.dtype == object and index.inferred_type == "boolean":
|
421 |
+
# GH#51363
|
422 |
+
warn = FutureWarning
|
423 |
+
msg = "The behavior of Index.insert with object-dtype is deprecated"
|
424 |
+
with tm.assert_produces_warning(warn, match=msg):
|
425 |
+
result = trimmed.insert(0, index[0])
|
426 |
+
assert index[0:4].equals(result)
|
427 |
+
|
428 |
+
@pytest.mark.skipif(
|
429 |
+
using_pyarrow_string_dtype(),
|
430 |
+
reason="completely different behavior, tested elsewher",
|
431 |
+
)
|
432 |
+
def test_insert_out_of_bounds(self, index):
|
433 |
+
# TypeError/IndexError matches what np.insert raises in these cases
|
434 |
+
|
435 |
+
if len(index) > 0:
|
436 |
+
err = TypeError
|
437 |
+
else:
|
438 |
+
err = IndexError
|
439 |
+
if len(index) == 0:
|
440 |
+
# 0 vs 0.5 in error message varies with numpy version
|
441 |
+
msg = "index (0|0.5) is out of bounds for axis 0 with size 0"
|
442 |
+
else:
|
443 |
+
msg = "slice indices must be integers or None or have an __index__ method"
|
444 |
+
with pytest.raises(err, match=msg):
|
445 |
+
index.insert(0.5, "foo")
|
446 |
+
|
447 |
+
msg = "|".join(
|
448 |
+
[
|
449 |
+
r"index -?\d+ is out of bounds for axis 0 with size \d+",
|
450 |
+
"loc must be an integer between",
|
451 |
+
]
|
452 |
+
)
|
453 |
+
with pytest.raises(IndexError, match=msg):
|
454 |
+
index.insert(len(index) + 1, 1)
|
455 |
+
|
456 |
+
with pytest.raises(IndexError, match=msg):
|
457 |
+
index.insert(-len(index) - 1, 1)
|
458 |
+
|
459 |
+
def test_delete_base(self, index):
|
460 |
+
if not len(index):
|
461 |
+
pytest.skip("Not applicable for empty index")
|
462 |
+
|
463 |
+
if isinstance(index, RangeIndex):
|
464 |
+
# tested in class
|
465 |
+
pytest.skip(f"{type(self).__name__} tested elsewhere")
|
466 |
+
|
467 |
+
expected = index[1:]
|
468 |
+
result = index.delete(0)
|
469 |
+
assert result.equals(expected)
|
470 |
+
assert result.name == expected.name
|
471 |
+
|
472 |
+
expected = index[:-1]
|
473 |
+
result = index.delete(-1)
|
474 |
+
assert result.equals(expected)
|
475 |
+
assert result.name == expected.name
|
476 |
+
|
477 |
+
length = len(index)
|
478 |
+
msg = f"index {length} is out of bounds for axis 0 with size {length}"
|
479 |
+
with pytest.raises(IndexError, match=msg):
|
480 |
+
index.delete(length)
|
481 |
+
|
482 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
483 |
+
def test_equals(self, index):
|
484 |
+
if isinstance(index, IntervalIndex):
|
485 |
+
pytest.skip(f"{type(index).__name__} tested elsewhere")
|
486 |
+
|
487 |
+
is_ea_idx = type(index) is Index and not isinstance(index.dtype, np.dtype)
|
488 |
+
|
489 |
+
assert index.equals(index)
|
490 |
+
assert index.equals(index.copy())
|
491 |
+
if not is_ea_idx:
|
492 |
+
# doesn't hold for e.g. IntegerDtype
|
493 |
+
assert index.equals(index.astype(object))
|
494 |
+
|
495 |
+
assert not index.equals(list(index))
|
496 |
+
assert not index.equals(np.array(index))
|
497 |
+
|
498 |
+
# Cannot pass in non-int64 dtype to RangeIndex
|
499 |
+
if not isinstance(index, RangeIndex) and not is_ea_idx:
|
500 |
+
same_values = Index(index, dtype=object)
|
501 |
+
assert index.equals(same_values)
|
502 |
+
assert same_values.equals(index)
|
503 |
+
|
504 |
+
if index.nlevels == 1:
|
505 |
+
# do not test MultiIndex
|
506 |
+
assert not index.equals(Series(index))
|
507 |
+
|
508 |
+
def test_equals_op(self, simple_index):
|
509 |
+
# GH9947, GH10637
|
510 |
+
index_a = simple_index
|
511 |
+
|
512 |
+
n = len(index_a)
|
513 |
+
index_b = index_a[0:-1]
|
514 |
+
index_c = index_a[0:-1].append(index_a[-2:-1])
|
515 |
+
index_d = index_a[0:1]
|
516 |
+
|
517 |
+
msg = "Lengths must match|could not be broadcast"
|
518 |
+
with pytest.raises(ValueError, match=msg):
|
519 |
+
index_a == index_b
|
520 |
+
expected1 = np.array([True] * n)
|
521 |
+
expected2 = np.array([True] * (n - 1) + [False])
|
522 |
+
tm.assert_numpy_array_equal(index_a == index_a, expected1)
|
523 |
+
tm.assert_numpy_array_equal(index_a == index_c, expected2)
|
524 |
+
|
525 |
+
# test comparisons with numpy arrays
|
526 |
+
array_a = np.array(index_a)
|
527 |
+
array_b = np.array(index_a[0:-1])
|
528 |
+
array_c = np.array(index_a[0:-1].append(index_a[-2:-1]))
|
529 |
+
array_d = np.array(index_a[0:1])
|
530 |
+
with pytest.raises(ValueError, match=msg):
|
531 |
+
index_a == array_b
|
532 |
+
tm.assert_numpy_array_equal(index_a == array_a, expected1)
|
533 |
+
tm.assert_numpy_array_equal(index_a == array_c, expected2)
|
534 |
+
|
535 |
+
# test comparisons with Series
|
536 |
+
series_a = Series(array_a)
|
537 |
+
series_b = Series(array_b)
|
538 |
+
series_c = Series(array_c)
|
539 |
+
series_d = Series(array_d)
|
540 |
+
with pytest.raises(ValueError, match=msg):
|
541 |
+
index_a == series_b
|
542 |
+
|
543 |
+
tm.assert_numpy_array_equal(index_a == series_a, expected1)
|
544 |
+
tm.assert_numpy_array_equal(index_a == series_c, expected2)
|
545 |
+
|
546 |
+
# cases where length is 1 for one of them
|
547 |
+
with pytest.raises(ValueError, match="Lengths must match"):
|
548 |
+
index_a == index_d
|
549 |
+
with pytest.raises(ValueError, match="Lengths must match"):
|
550 |
+
index_a == series_d
|
551 |
+
with pytest.raises(ValueError, match="Lengths must match"):
|
552 |
+
index_a == array_d
|
553 |
+
msg = "Can only compare identically-labeled Series objects"
|
554 |
+
with pytest.raises(ValueError, match=msg):
|
555 |
+
series_a == series_d
|
556 |
+
with pytest.raises(ValueError, match="Lengths must match"):
|
557 |
+
series_a == array_d
|
558 |
+
|
559 |
+
# comparing with a scalar should broadcast; note that we are excluding
|
560 |
+
# MultiIndex because in this case each item in the index is a tuple of
|
561 |
+
# length 2, and therefore is considered an array of length 2 in the
|
562 |
+
# comparison instead of a scalar
|
563 |
+
if not isinstance(index_a, MultiIndex):
|
564 |
+
expected3 = np.array([False] * (len(index_a) - 2) + [True, False])
|
565 |
+
# assuming the 2nd to last item is unique in the data
|
566 |
+
item = index_a[-2]
|
567 |
+
tm.assert_numpy_array_equal(index_a == item, expected3)
|
568 |
+
tm.assert_series_equal(series_a == item, Series(expected3))
|
569 |
+
|
570 |
+
def test_format(self, simple_index):
|
571 |
+
# GH35439
|
572 |
+
if is_numeric_dtype(simple_index.dtype) or isinstance(
|
573 |
+
simple_index, DatetimeIndex
|
574 |
+
):
|
575 |
+
pytest.skip("Tested elsewhere.")
|
576 |
+
idx = simple_index
|
577 |
+
expected = [str(x) for x in idx]
|
578 |
+
msg = r"Index\.format is deprecated"
|
579 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
580 |
+
assert idx.format() == expected
|
581 |
+
|
582 |
+
def test_format_empty(self, simple_index):
|
583 |
+
# GH35712
|
584 |
+
if isinstance(simple_index, (PeriodIndex, RangeIndex)):
|
585 |
+
pytest.skip("Tested elsewhere")
|
586 |
+
empty_idx = type(simple_index)([])
|
587 |
+
msg = r"Index\.format is deprecated"
|
588 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
589 |
+
assert empty_idx.format() == []
|
590 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
591 |
+
assert empty_idx.format(name=True) == [""]
|
592 |
+
|
593 |
+
def test_fillna(self, index):
|
594 |
+
# GH 11343
|
595 |
+
if len(index) == 0:
|
596 |
+
pytest.skip("Not relevant for empty index")
|
597 |
+
elif index.dtype == bool:
|
598 |
+
pytest.skip(f"{index.dtype} cannot hold NAs")
|
599 |
+
elif isinstance(index, Index) and is_integer_dtype(index.dtype):
|
600 |
+
pytest.skip(f"Not relevant for Index with {index.dtype}")
|
601 |
+
elif isinstance(index, MultiIndex):
|
602 |
+
idx = index.copy(deep=True)
|
603 |
+
msg = "isna is not defined for MultiIndex"
|
604 |
+
with pytest.raises(NotImplementedError, match=msg):
|
605 |
+
idx.fillna(idx[0])
|
606 |
+
else:
|
607 |
+
idx = index.copy(deep=True)
|
608 |
+
result = idx.fillna(idx[0])
|
609 |
+
tm.assert_index_equal(result, idx)
|
610 |
+
assert result is not idx
|
611 |
+
|
612 |
+
msg = "'value' must be a scalar, passed: "
|
613 |
+
with pytest.raises(TypeError, match=msg):
|
614 |
+
idx.fillna([idx[0]])
|
615 |
+
|
616 |
+
idx = index.copy(deep=True)
|
617 |
+
values = idx._values
|
618 |
+
|
619 |
+
values[1] = np.nan
|
620 |
+
|
621 |
+
idx = type(index)(values)
|
622 |
+
|
623 |
+
msg = "does not support 'downcast'"
|
624 |
+
msg2 = r"The 'downcast' keyword in .*Index\.fillna is deprecated"
|
625 |
+
with tm.assert_produces_warning(FutureWarning, match=msg2):
|
626 |
+
with pytest.raises(NotImplementedError, match=msg):
|
627 |
+
# For now at least, we only raise if there are NAs present
|
628 |
+
idx.fillna(idx[0], downcast="infer")
|
629 |
+
|
630 |
+
expected = np.array([False] * len(idx), dtype=bool)
|
631 |
+
expected[1] = True
|
632 |
+
tm.assert_numpy_array_equal(idx._isnan, expected)
|
633 |
+
assert idx.hasnans is True
|
634 |
+
|
635 |
+
def test_nulls(self, index):
|
636 |
+
# this is really a smoke test for the methods
|
637 |
+
# as these are adequately tested for function elsewhere
|
638 |
+
if len(index) == 0:
|
639 |
+
tm.assert_numpy_array_equal(index.isna(), np.array([], dtype=bool))
|
640 |
+
elif isinstance(index, MultiIndex):
|
641 |
+
idx = index.copy()
|
642 |
+
msg = "isna is not defined for MultiIndex"
|
643 |
+
with pytest.raises(NotImplementedError, match=msg):
|
644 |
+
idx.isna()
|
645 |
+
elif not index.hasnans:
|
646 |
+
tm.assert_numpy_array_equal(index.isna(), np.zeros(len(index), dtype=bool))
|
647 |
+
tm.assert_numpy_array_equal(index.notna(), np.ones(len(index), dtype=bool))
|
648 |
+
else:
|
649 |
+
result = isna(index)
|
650 |
+
tm.assert_numpy_array_equal(index.isna(), result)
|
651 |
+
tm.assert_numpy_array_equal(index.notna(), ~result)
|
652 |
+
|
653 |
+
def test_empty(self, simple_index):
|
654 |
+
# GH 15270
|
655 |
+
idx = simple_index
|
656 |
+
assert not idx.empty
|
657 |
+
assert idx[:0].empty
|
658 |
+
|
659 |
+
def test_join_self_unique(self, join_type, simple_index):
|
660 |
+
idx = simple_index
|
661 |
+
if idx.is_unique:
|
662 |
+
joined = idx.join(idx, how=join_type)
|
663 |
+
expected = simple_index
|
664 |
+
if join_type == "outer":
|
665 |
+
expected = algos.safe_sort(expected)
|
666 |
+
tm.assert_index_equal(joined, expected)
|
667 |
+
|
668 |
+
def test_map(self, simple_index):
|
669 |
+
# callable
|
670 |
+
if isinstance(simple_index, (TimedeltaIndex, PeriodIndex)):
|
671 |
+
pytest.skip("Tested elsewhere.")
|
672 |
+
idx = simple_index
|
673 |
+
|
674 |
+
result = idx.map(lambda x: x)
|
675 |
+
# RangeIndex are equivalent to the similar Index with int64 dtype
|
676 |
+
tm.assert_index_equal(result, idx, exact="equiv")
|
677 |
+
|
678 |
+
@pytest.mark.parametrize(
|
679 |
+
"mapper",
|
680 |
+
[
|
681 |
+
lambda values, index: {i: e for e, i in zip(values, index)},
|
682 |
+
lambda values, index: Series(values, index),
|
683 |
+
],
|
684 |
+
)
|
685 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
686 |
+
def test_map_dictlike(self, mapper, simple_index, request):
|
687 |
+
idx = simple_index
|
688 |
+
if isinstance(idx, (DatetimeIndex, TimedeltaIndex, PeriodIndex)):
|
689 |
+
pytest.skip("Tested elsewhere.")
|
690 |
+
|
691 |
+
identity = mapper(idx.values, idx)
|
692 |
+
|
693 |
+
result = idx.map(identity)
|
694 |
+
# RangeIndex are equivalent to the similar Index with int64 dtype
|
695 |
+
tm.assert_index_equal(result, idx, exact="equiv")
|
696 |
+
|
697 |
+
# empty mappable
|
698 |
+
dtype = None
|
699 |
+
if idx.dtype.kind == "f":
|
700 |
+
dtype = idx.dtype
|
701 |
+
|
702 |
+
expected = Index([np.nan] * len(idx), dtype=dtype)
|
703 |
+
result = idx.map(mapper(expected, idx))
|
704 |
+
tm.assert_index_equal(result, expected)
|
705 |
+
|
706 |
+
def test_map_str(self, simple_index):
|
707 |
+
# GH 31202
|
708 |
+
if isinstance(simple_index, CategoricalIndex):
|
709 |
+
pytest.skip("See test_map.py")
|
710 |
+
idx = simple_index
|
711 |
+
result = idx.map(str)
|
712 |
+
expected = Index([str(x) for x in idx])
|
713 |
+
tm.assert_index_equal(result, expected)
|
714 |
+
|
715 |
+
@pytest.mark.parametrize("copy", [True, False])
|
716 |
+
@pytest.mark.parametrize("name", [None, "foo"])
|
717 |
+
@pytest.mark.parametrize("ordered", [True, False])
|
718 |
+
def test_astype_category(self, copy, name, ordered, simple_index):
|
719 |
+
# GH 18630
|
720 |
+
idx = simple_index
|
721 |
+
if name:
|
722 |
+
idx = idx.rename(name)
|
723 |
+
|
724 |
+
# standard categories
|
725 |
+
dtype = CategoricalDtype(ordered=ordered)
|
726 |
+
result = idx.astype(dtype, copy=copy)
|
727 |
+
expected = CategoricalIndex(idx, name=name, ordered=ordered)
|
728 |
+
tm.assert_index_equal(result, expected, exact=True)
|
729 |
+
|
730 |
+
# non-standard categories
|
731 |
+
dtype = CategoricalDtype(idx.unique().tolist()[:-1], ordered)
|
732 |
+
result = idx.astype(dtype, copy=copy)
|
733 |
+
expected = CategoricalIndex(idx, name=name, dtype=dtype)
|
734 |
+
tm.assert_index_equal(result, expected, exact=True)
|
735 |
+
|
736 |
+
if ordered is False:
|
737 |
+
# dtype='category' defaults to ordered=False, so only test once
|
738 |
+
result = idx.astype("category", copy=copy)
|
739 |
+
expected = CategoricalIndex(idx, name=name)
|
740 |
+
tm.assert_index_equal(result, expected, exact=True)
|
741 |
+
|
742 |
+
def test_is_unique(self, simple_index):
|
743 |
+
# initialize a unique index
|
744 |
+
index = simple_index.drop_duplicates()
|
745 |
+
assert index.is_unique is True
|
746 |
+
|
747 |
+
# empty index should be unique
|
748 |
+
index_empty = index[:0]
|
749 |
+
assert index_empty.is_unique is True
|
750 |
+
|
751 |
+
# test basic dupes
|
752 |
+
index_dup = index.insert(0, index[0])
|
753 |
+
assert index_dup.is_unique is False
|
754 |
+
|
755 |
+
# single NA should be unique
|
756 |
+
index_na = index.insert(0, np.nan)
|
757 |
+
assert index_na.is_unique is True
|
758 |
+
|
759 |
+
# multiple NA should not be unique
|
760 |
+
index_na_dup = index_na.insert(0, np.nan)
|
761 |
+
assert index_na_dup.is_unique is False
|
762 |
+
|
763 |
+
@pytest.mark.arm_slow
|
764 |
+
def test_engine_reference_cycle(self, simple_index):
|
765 |
+
# GH27585
|
766 |
+
index = simple_index.copy()
|
767 |
+
ref = weakref.ref(index)
|
768 |
+
index._engine
|
769 |
+
del index
|
770 |
+
assert ref() is None
|
771 |
+
|
772 |
+
def test_getitem_2d_deprecated(self, simple_index):
|
773 |
+
# GH#30588, GH#31479
|
774 |
+
if isinstance(simple_index, IntervalIndex):
|
775 |
+
pytest.skip("Tested elsewhere")
|
776 |
+
idx = simple_index
|
777 |
+
msg = "Multi-dimensional indexing|too many|only"
|
778 |
+
with pytest.raises((ValueError, IndexError), match=msg):
|
779 |
+
idx[:, None]
|
780 |
+
|
781 |
+
if not isinstance(idx, RangeIndex):
|
782 |
+
# GH#44051 RangeIndex already raised pre-2.0 with a different message
|
783 |
+
with pytest.raises((ValueError, IndexError), match=msg):
|
784 |
+
idx[True]
|
785 |
+
with pytest.raises((ValueError, IndexError), match=msg):
|
786 |
+
idx[False]
|
787 |
+
else:
|
788 |
+
msg = "only integers, slices"
|
789 |
+
with pytest.raises(IndexError, match=msg):
|
790 |
+
idx[True]
|
791 |
+
with pytest.raises(IndexError, match=msg):
|
792 |
+
idx[False]
|
793 |
+
|
794 |
+
def test_copy_shares_cache(self, simple_index):
|
795 |
+
# GH32898, GH36840
|
796 |
+
idx = simple_index
|
797 |
+
idx.get_loc(idx[0]) # populates the _cache.
|
798 |
+
copy = idx.copy()
|
799 |
+
|
800 |
+
assert copy._cache is idx._cache
|
801 |
+
|
802 |
+
def test_shallow_copy_shares_cache(self, simple_index):
|
803 |
+
# GH32669, GH36840
|
804 |
+
idx = simple_index
|
805 |
+
idx.get_loc(idx[0]) # populates the _cache.
|
806 |
+
shallow_copy = idx._view()
|
807 |
+
|
808 |
+
assert shallow_copy._cache is idx._cache
|
809 |
+
|
810 |
+
shallow_copy = idx._shallow_copy(idx._data)
|
811 |
+
assert shallow_copy._cache is not idx._cache
|
812 |
+
assert shallow_copy._cache == {}
|
813 |
+
|
814 |
+
def test_index_groupby(self, simple_index):
|
815 |
+
idx = simple_index[:5]
|
816 |
+
to_groupby = np.array([1, 2, np.nan, 2, 1])
|
817 |
+
tm.assert_dict_equal(
|
818 |
+
idx.groupby(to_groupby), {1.0: idx[[0, 4]], 2.0: idx[[1, 3]]}
|
819 |
+
)
|
820 |
+
|
821 |
+
to_groupby = DatetimeIndex(
|
822 |
+
[
|
823 |
+
datetime(2011, 11, 1),
|
824 |
+
datetime(2011, 12, 1),
|
825 |
+
pd.NaT,
|
826 |
+
datetime(2011, 12, 1),
|
827 |
+
datetime(2011, 11, 1),
|
828 |
+
],
|
829 |
+
tz="UTC",
|
830 |
+
).values
|
831 |
+
|
832 |
+
ex_keys = [Timestamp("2011-11-01"), Timestamp("2011-12-01")]
|
833 |
+
expected = {ex_keys[0]: idx[[0, 4]], ex_keys[1]: idx[[1, 3]]}
|
834 |
+
tm.assert_dict_equal(idx.groupby(to_groupby), expected)
|
835 |
+
|
836 |
+
def test_append_preserves_dtype(self, simple_index):
|
837 |
+
# In particular Index with dtype float32
|
838 |
+
index = simple_index
|
839 |
+
N = len(index)
|
840 |
+
|
841 |
+
result = index.append(index)
|
842 |
+
assert result.dtype == index.dtype
|
843 |
+
tm.assert_index_equal(result[:N], index, check_exact=True)
|
844 |
+
tm.assert_index_equal(result[N:], index, check_exact=True)
|
845 |
+
|
846 |
+
alt = index.take(list(range(N)) * 2)
|
847 |
+
tm.assert_index_equal(result, alt, check_exact=True)
|
848 |
+
|
849 |
+
def test_inv(self, simple_index, using_infer_string):
|
850 |
+
idx = simple_index
|
851 |
+
|
852 |
+
if idx.dtype.kind in ["i", "u"]:
|
853 |
+
res = ~idx
|
854 |
+
expected = Index(~idx.values, name=idx.name)
|
855 |
+
tm.assert_index_equal(res, expected)
|
856 |
+
|
857 |
+
# check that we are matching Series behavior
|
858 |
+
res2 = ~Series(idx)
|
859 |
+
tm.assert_series_equal(res2, Series(expected))
|
860 |
+
else:
|
861 |
+
if idx.dtype.kind == "f":
|
862 |
+
err = TypeError
|
863 |
+
msg = "ufunc 'invert' not supported for the input types"
|
864 |
+
elif using_infer_string and idx.dtype == "string":
|
865 |
+
import pyarrow as pa
|
866 |
+
|
867 |
+
err = pa.lib.ArrowNotImplementedError
|
868 |
+
msg = "has no kernel"
|
869 |
+
else:
|
870 |
+
err = TypeError
|
871 |
+
msg = "bad operand"
|
872 |
+
with pytest.raises(err, match=msg):
|
873 |
+
~idx
|
874 |
+
|
875 |
+
# check that we get the same behavior with Series
|
876 |
+
with pytest.raises(err, match=msg):
|
877 |
+
~Series(idx)
|
878 |
+
|
879 |
+
def test_is_boolean_is_deprecated(self, simple_index):
|
880 |
+
# GH50042
|
881 |
+
idx = simple_index
|
882 |
+
with tm.assert_produces_warning(FutureWarning):
|
883 |
+
idx.is_boolean()
|
884 |
+
|
885 |
+
def test_is_floating_is_deprecated(self, simple_index):
|
886 |
+
# GH50042
|
887 |
+
idx = simple_index
|
888 |
+
with tm.assert_produces_warning(FutureWarning):
|
889 |
+
idx.is_floating()
|
890 |
+
|
891 |
+
def test_is_integer_is_deprecated(self, simple_index):
|
892 |
+
# GH50042
|
893 |
+
idx = simple_index
|
894 |
+
with tm.assert_produces_warning(FutureWarning):
|
895 |
+
idx.is_integer()
|
896 |
+
|
897 |
+
def test_holds_integer_deprecated(self, simple_index):
|
898 |
+
# GH50243
|
899 |
+
idx = simple_index
|
900 |
+
msg = f"{type(idx).__name__}.holds_integer is deprecated. "
|
901 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
902 |
+
idx.holds_integer()
|
903 |
+
|
904 |
+
def test_is_numeric_is_deprecated(self, simple_index):
|
905 |
+
# GH50042
|
906 |
+
idx = simple_index
|
907 |
+
with tm.assert_produces_warning(
|
908 |
+
FutureWarning,
|
909 |
+
match=f"{type(idx).__name__}.is_numeric is deprecated. ",
|
910 |
+
):
|
911 |
+
idx.is_numeric()
|
912 |
+
|
913 |
+
def test_is_categorical_is_deprecated(self, simple_index):
|
914 |
+
# GH50042
|
915 |
+
idx = simple_index
|
916 |
+
with tm.assert_produces_warning(
|
917 |
+
FutureWarning,
|
918 |
+
match=r"Use pandas\.api\.types\.is_categorical_dtype instead",
|
919 |
+
):
|
920 |
+
idx.is_categorical()
|
921 |
+
|
922 |
+
def test_is_interval_is_deprecated(self, simple_index):
|
923 |
+
# GH50042
|
924 |
+
idx = simple_index
|
925 |
+
with tm.assert_produces_warning(FutureWarning):
|
926 |
+
idx.is_interval()
|
927 |
+
|
928 |
+
def test_is_object_is_deprecated(self, simple_index):
|
929 |
+
# GH50042
|
930 |
+
idx = simple_index
|
931 |
+
with tm.assert_produces_warning(FutureWarning):
|
932 |
+
idx.is_object()
|
933 |
+
|
934 |
+
|
935 |
+
class TestNumericBase:
|
936 |
+
@pytest.fixture(
|
937 |
+
params=[
|
938 |
+
RangeIndex(start=0, stop=20, step=2),
|
939 |
+
Index(np.arange(5, dtype=np.float64)),
|
940 |
+
Index(np.arange(5, dtype=np.float32)),
|
941 |
+
Index(np.arange(5, dtype=np.uint64)),
|
942 |
+
Index(range(0, 20, 2), dtype=np.int64),
|
943 |
+
Index(range(0, 20, 2), dtype=np.int32),
|
944 |
+
Index(range(0, 20, 2), dtype=np.int16),
|
945 |
+
Index(range(0, 20, 2), dtype=np.int8),
|
946 |
+
]
|
947 |
+
)
|
948 |
+
def simple_index(self, request):
|
949 |
+
return request.param
|
950 |
+
|
951 |
+
def test_constructor_unwraps_index(self, simple_index):
|
952 |
+
if isinstance(simple_index, RangeIndex):
|
953 |
+
pytest.skip("Tested elsewhere.")
|
954 |
+
index_cls = type(simple_index)
|
955 |
+
dtype = simple_index.dtype
|
956 |
+
|
957 |
+
idx = Index([1, 2], dtype=dtype)
|
958 |
+
result = index_cls(idx)
|
959 |
+
expected = np.array([1, 2], dtype=idx.dtype)
|
960 |
+
tm.assert_numpy_array_equal(result._data, expected)
|
961 |
+
|
962 |
+
def test_can_hold_identifiers(self, simple_index):
|
963 |
+
idx = simple_index
|
964 |
+
key = idx[0]
|
965 |
+
assert idx._can_hold_identifiers_and_holds_name(key) is False
|
966 |
+
|
967 |
+
def test_view(self, simple_index):
|
968 |
+
if isinstance(simple_index, RangeIndex):
|
969 |
+
pytest.skip("Tested elsewhere.")
|
970 |
+
index_cls = type(simple_index)
|
971 |
+
dtype = simple_index.dtype
|
972 |
+
|
973 |
+
idx = index_cls([], dtype=dtype, name="Foo")
|
974 |
+
idx_view = idx.view()
|
975 |
+
assert idx_view.name == "Foo"
|
976 |
+
|
977 |
+
idx_view = idx.view(dtype)
|
978 |
+
tm.assert_index_equal(idx, index_cls(idx_view, name="Foo"), exact=True)
|
979 |
+
|
980 |
+
msg = "Passing a type in .*Index.view is deprecated"
|
981 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
982 |
+
idx_view = idx.view(index_cls)
|
983 |
+
tm.assert_index_equal(idx, index_cls(idx_view, name="Foo"), exact=True)
|
984 |
+
|
985 |
+
def test_format(self, simple_index):
|
986 |
+
# GH35439
|
987 |
+
if isinstance(simple_index, DatetimeIndex):
|
988 |
+
pytest.skip("Tested elsewhere")
|
989 |
+
idx = simple_index
|
990 |
+
max_width = max(len(str(x)) for x in idx)
|
991 |
+
expected = [str(x).ljust(max_width) for x in idx]
|
992 |
+
msg = r"Index\.format is deprecated"
|
993 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
994 |
+
assert idx.format() == expected
|
995 |
+
|
996 |
+
def test_insert_non_na(self, simple_index):
|
997 |
+
# GH#43921 inserting an element that we know we can hold should
|
998 |
+
# not change dtype or type (except for RangeIndex)
|
999 |
+
index = simple_index
|
1000 |
+
|
1001 |
+
result = index.insert(0, index[0])
|
1002 |
+
|
1003 |
+
expected = Index([index[0]] + list(index), dtype=index.dtype)
|
1004 |
+
tm.assert_index_equal(result, expected, exact=True)
|
1005 |
+
|
1006 |
+
def test_insert_na(self, nulls_fixture, simple_index):
|
1007 |
+
# GH 18295 (test missing)
|
1008 |
+
index = simple_index
|
1009 |
+
na_val = nulls_fixture
|
1010 |
+
|
1011 |
+
if na_val is pd.NaT:
|
1012 |
+
expected = Index([index[0], pd.NaT] + list(index[1:]), dtype=object)
|
1013 |
+
else:
|
1014 |
+
expected = Index([index[0], np.nan] + list(index[1:]))
|
1015 |
+
# GH#43921 we preserve float dtype
|
1016 |
+
if index.dtype.kind == "f":
|
1017 |
+
expected = Index(expected, dtype=index.dtype)
|
1018 |
+
|
1019 |
+
result = index.insert(1, na_val)
|
1020 |
+
tm.assert_index_equal(result, expected, exact=True)
|
1021 |
+
|
1022 |
+
def test_arithmetic_explicit_conversions(self, simple_index):
|
1023 |
+
# GH 8608
|
1024 |
+
# add/sub are overridden explicitly for Float/Int Index
|
1025 |
+
index_cls = type(simple_index)
|
1026 |
+
if index_cls is RangeIndex:
|
1027 |
+
idx = RangeIndex(5)
|
1028 |
+
else:
|
1029 |
+
idx = index_cls(np.arange(5, dtype="int64"))
|
1030 |
+
|
1031 |
+
# float conversions
|
1032 |
+
arr = np.arange(5, dtype="int64") * 3.2
|
1033 |
+
expected = Index(arr, dtype=np.float64)
|
1034 |
+
fidx = idx * 3.2
|
1035 |
+
tm.assert_index_equal(fidx, expected)
|
1036 |
+
fidx = 3.2 * idx
|
1037 |
+
tm.assert_index_equal(fidx, expected)
|
1038 |
+
|
1039 |
+
# interops with numpy arrays
|
1040 |
+
expected = Index(arr, dtype=np.float64)
|
1041 |
+
a = np.zeros(5, dtype="float64")
|
1042 |
+
result = fidx - a
|
1043 |
+
tm.assert_index_equal(result, expected)
|
1044 |
+
|
1045 |
+
expected = Index(-arr, dtype=np.float64)
|
1046 |
+
a = np.zeros(5, dtype="float64")
|
1047 |
+
result = a - fidx
|
1048 |
+
tm.assert_index_equal(result, expected)
|
1049 |
+
|
1050 |
+
@pytest.mark.parametrize("complex_dtype", [np.complex64, np.complex128])
|
1051 |
+
def test_astype_to_complex(self, complex_dtype, simple_index):
|
1052 |
+
result = simple_index.astype(complex_dtype)
|
1053 |
+
|
1054 |
+
assert type(result) is Index and result.dtype == complex_dtype
|
1055 |
+
|
1056 |
+
def test_cast_string(self, simple_index):
|
1057 |
+
if isinstance(simple_index, RangeIndex):
|
1058 |
+
pytest.skip("casting of strings not relevant for RangeIndex")
|
1059 |
+
result = type(simple_index)(["0", "1", "2"], dtype=simple_index.dtype)
|
1060 |
+
expected = type(simple_index)([0, 1, 2], dtype=simple_index.dtype)
|
1061 |
+
tm.assert_index_equal(result, expected)
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/test_setops.py
ADDED
@@ -0,0 +1,959 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
The tests in this package are to ensure the proper resultant dtypes of
|
3 |
+
set operations.
|
4 |
+
"""
|
5 |
+
from datetime import datetime
|
6 |
+
import operator
|
7 |
+
|
8 |
+
import numpy as np
|
9 |
+
import pytest
|
10 |
+
|
11 |
+
from pandas._libs import lib
|
12 |
+
|
13 |
+
from pandas.core.dtypes.cast import find_common_type
|
14 |
+
|
15 |
+
from pandas import (
|
16 |
+
CategoricalDtype,
|
17 |
+
CategoricalIndex,
|
18 |
+
DatetimeTZDtype,
|
19 |
+
Index,
|
20 |
+
MultiIndex,
|
21 |
+
PeriodDtype,
|
22 |
+
RangeIndex,
|
23 |
+
Series,
|
24 |
+
Timestamp,
|
25 |
+
)
|
26 |
+
import pandas._testing as tm
|
27 |
+
from pandas.api.types import (
|
28 |
+
is_signed_integer_dtype,
|
29 |
+
pandas_dtype,
|
30 |
+
)
|
31 |
+
|
32 |
+
|
33 |
+
def equal_contents(arr1, arr2) -> bool:
|
34 |
+
"""
|
35 |
+
Checks if the set of unique elements of arr1 and arr2 are equivalent.
|
36 |
+
"""
|
37 |
+
return frozenset(arr1) == frozenset(arr2)
|
38 |
+
|
39 |
+
|
40 |
+
@pytest.fixture(
|
41 |
+
params=tm.ALL_REAL_NUMPY_DTYPES
|
42 |
+
+ [
|
43 |
+
"object",
|
44 |
+
"category",
|
45 |
+
"datetime64[ns]",
|
46 |
+
"timedelta64[ns]",
|
47 |
+
]
|
48 |
+
)
|
49 |
+
def any_dtype_for_small_pos_integer_indexes(request):
|
50 |
+
"""
|
51 |
+
Dtypes that can be given to an Index with small positive integers.
|
52 |
+
|
53 |
+
This means that for any dtype `x` in the params list, `Index([1, 2, 3], dtype=x)` is
|
54 |
+
valid and gives the correct Index (sub-)class.
|
55 |
+
"""
|
56 |
+
return request.param
|
57 |
+
|
58 |
+
|
59 |
+
def test_union_same_types(index):
|
60 |
+
# Union with a non-unique, non-monotonic index raises error
|
61 |
+
# Only needed for bool index factory
|
62 |
+
idx1 = index.sort_values()
|
63 |
+
idx2 = index.sort_values()
|
64 |
+
assert idx1.union(idx2).dtype == idx1.dtype
|
65 |
+
|
66 |
+
|
67 |
+
def test_union_different_types(index_flat, index_flat2, request):
|
68 |
+
# This test only considers combinations of indices
|
69 |
+
# GH 23525
|
70 |
+
idx1 = index_flat
|
71 |
+
idx2 = index_flat2
|
72 |
+
|
73 |
+
if (
|
74 |
+
not idx1.is_unique
|
75 |
+
and not idx2.is_unique
|
76 |
+
and idx1.dtype.kind == "i"
|
77 |
+
and idx2.dtype.kind == "b"
|
78 |
+
) or (
|
79 |
+
not idx2.is_unique
|
80 |
+
and not idx1.is_unique
|
81 |
+
and idx2.dtype.kind == "i"
|
82 |
+
and idx1.dtype.kind == "b"
|
83 |
+
):
|
84 |
+
# Each condition had idx[1|2].is_monotonic_decreasing
|
85 |
+
# but failed when e.g.
|
86 |
+
# idx1 = Index(
|
87 |
+
# [True, True, True, True, True, True, True, True, False, False], dtype='bool'
|
88 |
+
# )
|
89 |
+
# idx2 = Index([0, 0, 1, 1, 2, 2], dtype='int64')
|
90 |
+
mark = pytest.mark.xfail(
|
91 |
+
reason="GH#44000 True==1", raises=ValueError, strict=False
|
92 |
+
)
|
93 |
+
request.applymarker(mark)
|
94 |
+
|
95 |
+
common_dtype = find_common_type([idx1.dtype, idx2.dtype])
|
96 |
+
|
97 |
+
warn = None
|
98 |
+
msg = "'<' not supported between"
|
99 |
+
if not len(idx1) or not len(idx2):
|
100 |
+
pass
|
101 |
+
elif (idx1.dtype.kind == "c" and (not lib.is_np_dtype(idx2.dtype, "iufc"))) or (
|
102 |
+
idx2.dtype.kind == "c" and (not lib.is_np_dtype(idx1.dtype, "iufc"))
|
103 |
+
):
|
104 |
+
# complex objects non-sortable
|
105 |
+
warn = RuntimeWarning
|
106 |
+
elif (
|
107 |
+
isinstance(idx1.dtype, PeriodDtype) and isinstance(idx2.dtype, CategoricalDtype)
|
108 |
+
) or (
|
109 |
+
isinstance(idx2.dtype, PeriodDtype) and isinstance(idx1.dtype, CategoricalDtype)
|
110 |
+
):
|
111 |
+
warn = FutureWarning
|
112 |
+
msg = r"PeriodDtype\[B\] is deprecated"
|
113 |
+
mark = pytest.mark.xfail(
|
114 |
+
reason="Warning not produced on all builds",
|
115 |
+
raises=AssertionError,
|
116 |
+
strict=False,
|
117 |
+
)
|
118 |
+
request.applymarker(mark)
|
119 |
+
|
120 |
+
any_uint64 = np.uint64 in (idx1.dtype, idx2.dtype)
|
121 |
+
idx1_signed = is_signed_integer_dtype(idx1.dtype)
|
122 |
+
idx2_signed = is_signed_integer_dtype(idx2.dtype)
|
123 |
+
|
124 |
+
# Union with a non-unique, non-monotonic index raises error
|
125 |
+
# This applies to the boolean index
|
126 |
+
idx1 = idx1.sort_values()
|
127 |
+
idx2 = idx2.sort_values()
|
128 |
+
|
129 |
+
with tm.assert_produces_warning(warn, match=msg):
|
130 |
+
res1 = idx1.union(idx2)
|
131 |
+
res2 = idx2.union(idx1)
|
132 |
+
|
133 |
+
if any_uint64 and (idx1_signed or idx2_signed):
|
134 |
+
assert res1.dtype == np.dtype("O")
|
135 |
+
assert res2.dtype == np.dtype("O")
|
136 |
+
else:
|
137 |
+
assert res1.dtype == common_dtype
|
138 |
+
assert res2.dtype == common_dtype
|
139 |
+
|
140 |
+
|
141 |
+
@pytest.mark.parametrize(
|
142 |
+
"idx1,idx2",
|
143 |
+
[
|
144 |
+
(Index(np.arange(5), dtype=np.int64), RangeIndex(5)),
|
145 |
+
(Index(np.arange(5), dtype=np.float64), Index(np.arange(5), dtype=np.int64)),
|
146 |
+
(Index(np.arange(5), dtype=np.float64), RangeIndex(5)),
|
147 |
+
(Index(np.arange(5), dtype=np.float64), Index(np.arange(5), dtype=np.uint64)),
|
148 |
+
],
|
149 |
+
)
|
150 |
+
def test_compatible_inconsistent_pairs(idx1, idx2):
|
151 |
+
# GH 23525
|
152 |
+
res1 = idx1.union(idx2)
|
153 |
+
res2 = idx2.union(idx1)
|
154 |
+
|
155 |
+
assert res1.dtype in (idx1.dtype, idx2.dtype)
|
156 |
+
assert res2.dtype in (idx1.dtype, idx2.dtype)
|
157 |
+
|
158 |
+
|
159 |
+
@pytest.mark.parametrize(
|
160 |
+
"left, right, expected",
|
161 |
+
[
|
162 |
+
("int64", "int64", "int64"),
|
163 |
+
("int64", "uint64", "object"),
|
164 |
+
("int64", "float64", "float64"),
|
165 |
+
("uint64", "float64", "float64"),
|
166 |
+
("uint64", "uint64", "uint64"),
|
167 |
+
("float64", "float64", "float64"),
|
168 |
+
("datetime64[ns]", "int64", "object"),
|
169 |
+
("datetime64[ns]", "uint64", "object"),
|
170 |
+
("datetime64[ns]", "float64", "object"),
|
171 |
+
("datetime64[ns, CET]", "int64", "object"),
|
172 |
+
("datetime64[ns, CET]", "uint64", "object"),
|
173 |
+
("datetime64[ns, CET]", "float64", "object"),
|
174 |
+
("Period[D]", "int64", "object"),
|
175 |
+
("Period[D]", "uint64", "object"),
|
176 |
+
("Period[D]", "float64", "object"),
|
177 |
+
],
|
178 |
+
)
|
179 |
+
@pytest.mark.parametrize("names", [("foo", "foo", "foo"), ("foo", "bar", None)])
|
180 |
+
def test_union_dtypes(left, right, expected, names):
|
181 |
+
left = pandas_dtype(left)
|
182 |
+
right = pandas_dtype(right)
|
183 |
+
a = Index([], dtype=left, name=names[0])
|
184 |
+
b = Index([], dtype=right, name=names[1])
|
185 |
+
result = a.union(b)
|
186 |
+
assert result.dtype == expected
|
187 |
+
assert result.name == names[2]
|
188 |
+
|
189 |
+
# Testing name retention
|
190 |
+
# TODO: pin down desired dtype; do we want it to be commutative?
|
191 |
+
result = a.intersection(b)
|
192 |
+
assert result.name == names[2]
|
193 |
+
|
194 |
+
|
195 |
+
@pytest.mark.parametrize("values", [[1, 2, 2, 3], [3, 3]])
|
196 |
+
def test_intersection_duplicates(values):
|
197 |
+
# GH#31326
|
198 |
+
a = Index(values)
|
199 |
+
b = Index([3, 3])
|
200 |
+
result = a.intersection(b)
|
201 |
+
expected = Index([3])
|
202 |
+
tm.assert_index_equal(result, expected)
|
203 |
+
|
204 |
+
|
205 |
+
class TestSetOps:
|
206 |
+
# Set operation tests shared by all indexes in the `index` fixture
|
207 |
+
@pytest.mark.parametrize("case", [0.5, "xxx"])
|
208 |
+
@pytest.mark.parametrize(
|
209 |
+
"method", ["intersection", "union", "difference", "symmetric_difference"]
|
210 |
+
)
|
211 |
+
def test_set_ops_error_cases(self, case, method, index):
|
212 |
+
# non-iterable input
|
213 |
+
msg = "Input must be Index or array-like"
|
214 |
+
with pytest.raises(TypeError, match=msg):
|
215 |
+
getattr(index, method)(case)
|
216 |
+
|
217 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
218 |
+
def test_intersection_base(self, index):
|
219 |
+
if isinstance(index, CategoricalIndex):
|
220 |
+
pytest.skip(f"Not relevant for {type(index).__name__}")
|
221 |
+
|
222 |
+
first = index[:5].unique()
|
223 |
+
second = index[:3].unique()
|
224 |
+
intersect = first.intersection(second)
|
225 |
+
tm.assert_index_equal(intersect, second)
|
226 |
+
|
227 |
+
if isinstance(index.dtype, DatetimeTZDtype):
|
228 |
+
# The second.values below will drop tz, so the rest of this test
|
229 |
+
# is not applicable.
|
230 |
+
return
|
231 |
+
|
232 |
+
# GH#10149
|
233 |
+
cases = [second.to_numpy(), second.to_series(), second.to_list()]
|
234 |
+
for case in cases:
|
235 |
+
result = first.intersection(case)
|
236 |
+
assert equal_contents(result, second)
|
237 |
+
|
238 |
+
if isinstance(index, MultiIndex):
|
239 |
+
msg = "other must be a MultiIndex or a list of tuples"
|
240 |
+
with pytest.raises(TypeError, match=msg):
|
241 |
+
first.intersection([1, 2, 3])
|
242 |
+
|
243 |
+
@pytest.mark.filterwarnings(
|
244 |
+
"ignore:Falling back on a non-pyarrow:pandas.errors.PerformanceWarning"
|
245 |
+
)
|
246 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
247 |
+
def test_union_base(self, index):
|
248 |
+
index = index.unique()
|
249 |
+
first = index[3:]
|
250 |
+
second = index[:5]
|
251 |
+
everything = index
|
252 |
+
|
253 |
+
union = first.union(second)
|
254 |
+
tm.assert_index_equal(union.sort_values(), everything.sort_values())
|
255 |
+
|
256 |
+
if isinstance(index.dtype, DatetimeTZDtype):
|
257 |
+
# The second.values below will drop tz, so the rest of this test
|
258 |
+
# is not applicable.
|
259 |
+
return
|
260 |
+
|
261 |
+
# GH#10149
|
262 |
+
cases = [second.to_numpy(), second.to_series(), second.to_list()]
|
263 |
+
for case in cases:
|
264 |
+
result = first.union(case)
|
265 |
+
assert equal_contents(result, everything)
|
266 |
+
|
267 |
+
if isinstance(index, MultiIndex):
|
268 |
+
msg = "other must be a MultiIndex or a list of tuples"
|
269 |
+
with pytest.raises(TypeError, match=msg):
|
270 |
+
first.union([1, 2, 3])
|
271 |
+
|
272 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
273 |
+
@pytest.mark.filterwarnings(
|
274 |
+
"ignore:Falling back on a non-pyarrow:pandas.errors.PerformanceWarning"
|
275 |
+
)
|
276 |
+
def test_difference_base(self, sort, index):
|
277 |
+
first = index[2:]
|
278 |
+
second = index[:4]
|
279 |
+
if index.inferred_type == "boolean":
|
280 |
+
# i think (TODO: be sure) there assumptions baked in about
|
281 |
+
# the index fixture that don't hold here?
|
282 |
+
answer = set(first).difference(set(second))
|
283 |
+
elif isinstance(index, CategoricalIndex):
|
284 |
+
answer = []
|
285 |
+
else:
|
286 |
+
answer = index[4:]
|
287 |
+
result = first.difference(second, sort)
|
288 |
+
assert equal_contents(result, answer)
|
289 |
+
|
290 |
+
# GH#10149
|
291 |
+
cases = [second.to_numpy(), second.to_series(), second.to_list()]
|
292 |
+
for case in cases:
|
293 |
+
result = first.difference(case, sort)
|
294 |
+
assert equal_contents(result, answer)
|
295 |
+
|
296 |
+
if isinstance(index, MultiIndex):
|
297 |
+
msg = "other must be a MultiIndex or a list of tuples"
|
298 |
+
with pytest.raises(TypeError, match=msg):
|
299 |
+
first.difference([1, 2, 3], sort)
|
300 |
+
|
301 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
302 |
+
@pytest.mark.filterwarnings(
|
303 |
+
"ignore:Falling back on a non-pyarrow:pandas.errors.PerformanceWarning"
|
304 |
+
)
|
305 |
+
def test_symmetric_difference(self, index):
|
306 |
+
if isinstance(index, CategoricalIndex):
|
307 |
+
pytest.skip(f"Not relevant for {type(index).__name__}")
|
308 |
+
if len(index) < 2:
|
309 |
+
pytest.skip("Too few values for test")
|
310 |
+
if index[0] in index[1:] or index[-1] in index[:-1]:
|
311 |
+
# index fixture has e.g. an index of bools that does not satisfy this,
|
312 |
+
# another with [0, 0, 1, 1, 2, 2]
|
313 |
+
pytest.skip("Index values no not satisfy test condition.")
|
314 |
+
|
315 |
+
first = index[1:]
|
316 |
+
second = index[:-1]
|
317 |
+
answer = index[[0, -1]]
|
318 |
+
result = first.symmetric_difference(second)
|
319 |
+
tm.assert_index_equal(result.sort_values(), answer.sort_values())
|
320 |
+
|
321 |
+
# GH#10149
|
322 |
+
cases = [second.to_numpy(), second.to_series(), second.to_list()]
|
323 |
+
for case in cases:
|
324 |
+
result = first.symmetric_difference(case)
|
325 |
+
assert equal_contents(result, answer)
|
326 |
+
|
327 |
+
if isinstance(index, MultiIndex):
|
328 |
+
msg = "other must be a MultiIndex or a list of tuples"
|
329 |
+
with pytest.raises(TypeError, match=msg):
|
330 |
+
first.symmetric_difference([1, 2, 3])
|
331 |
+
|
332 |
+
@pytest.mark.parametrize(
|
333 |
+
"fname, sname, expected_name",
|
334 |
+
[
|
335 |
+
("A", "A", "A"),
|
336 |
+
("A", "B", None),
|
337 |
+
("A", None, None),
|
338 |
+
(None, "B", None),
|
339 |
+
(None, None, None),
|
340 |
+
],
|
341 |
+
)
|
342 |
+
def test_corner_union(self, index_flat, fname, sname, expected_name):
|
343 |
+
# GH#9943, GH#9862
|
344 |
+
# Test unions with various name combinations
|
345 |
+
# Do not test MultiIndex or repeats
|
346 |
+
if not index_flat.is_unique:
|
347 |
+
index = index_flat.unique()
|
348 |
+
else:
|
349 |
+
index = index_flat
|
350 |
+
|
351 |
+
# Test copy.union(copy)
|
352 |
+
first = index.copy().set_names(fname)
|
353 |
+
second = index.copy().set_names(sname)
|
354 |
+
union = first.union(second)
|
355 |
+
expected = index.copy().set_names(expected_name)
|
356 |
+
tm.assert_index_equal(union, expected)
|
357 |
+
|
358 |
+
# Test copy.union(empty)
|
359 |
+
first = index.copy().set_names(fname)
|
360 |
+
second = index.drop(index).set_names(sname)
|
361 |
+
union = first.union(second)
|
362 |
+
expected = index.copy().set_names(expected_name)
|
363 |
+
tm.assert_index_equal(union, expected)
|
364 |
+
|
365 |
+
# Test empty.union(copy)
|
366 |
+
first = index.drop(index).set_names(fname)
|
367 |
+
second = index.copy().set_names(sname)
|
368 |
+
union = first.union(second)
|
369 |
+
expected = index.copy().set_names(expected_name)
|
370 |
+
tm.assert_index_equal(union, expected)
|
371 |
+
|
372 |
+
# Test empty.union(empty)
|
373 |
+
first = index.drop(index).set_names(fname)
|
374 |
+
second = index.drop(index).set_names(sname)
|
375 |
+
union = first.union(second)
|
376 |
+
expected = index.drop(index).set_names(expected_name)
|
377 |
+
tm.assert_index_equal(union, expected)
|
378 |
+
|
379 |
+
@pytest.mark.parametrize(
|
380 |
+
"fname, sname, expected_name",
|
381 |
+
[
|
382 |
+
("A", "A", "A"),
|
383 |
+
("A", "B", None),
|
384 |
+
("A", None, None),
|
385 |
+
(None, "B", None),
|
386 |
+
(None, None, None),
|
387 |
+
],
|
388 |
+
)
|
389 |
+
def test_union_unequal(self, index_flat, fname, sname, expected_name):
|
390 |
+
if not index_flat.is_unique:
|
391 |
+
index = index_flat.unique()
|
392 |
+
else:
|
393 |
+
index = index_flat
|
394 |
+
|
395 |
+
# test copy.union(subset) - need sort for unicode and string
|
396 |
+
first = index.copy().set_names(fname)
|
397 |
+
second = index[1:].set_names(sname)
|
398 |
+
union = first.union(second).sort_values()
|
399 |
+
expected = index.set_names(expected_name).sort_values()
|
400 |
+
tm.assert_index_equal(union, expected)
|
401 |
+
|
402 |
+
@pytest.mark.parametrize(
|
403 |
+
"fname, sname, expected_name",
|
404 |
+
[
|
405 |
+
("A", "A", "A"),
|
406 |
+
("A", "B", None),
|
407 |
+
("A", None, None),
|
408 |
+
(None, "B", None),
|
409 |
+
(None, None, None),
|
410 |
+
],
|
411 |
+
)
|
412 |
+
def test_corner_intersect(self, index_flat, fname, sname, expected_name):
|
413 |
+
# GH#35847
|
414 |
+
# Test intersections with various name combinations
|
415 |
+
if not index_flat.is_unique:
|
416 |
+
index = index_flat.unique()
|
417 |
+
else:
|
418 |
+
index = index_flat
|
419 |
+
|
420 |
+
# Test copy.intersection(copy)
|
421 |
+
first = index.copy().set_names(fname)
|
422 |
+
second = index.copy().set_names(sname)
|
423 |
+
intersect = first.intersection(second)
|
424 |
+
expected = index.copy().set_names(expected_name)
|
425 |
+
tm.assert_index_equal(intersect, expected)
|
426 |
+
|
427 |
+
# Test copy.intersection(empty)
|
428 |
+
first = index.copy().set_names(fname)
|
429 |
+
second = index.drop(index).set_names(sname)
|
430 |
+
intersect = first.intersection(second)
|
431 |
+
expected = index.drop(index).set_names(expected_name)
|
432 |
+
tm.assert_index_equal(intersect, expected)
|
433 |
+
|
434 |
+
# Test empty.intersection(copy)
|
435 |
+
first = index.drop(index).set_names(fname)
|
436 |
+
second = index.copy().set_names(sname)
|
437 |
+
intersect = first.intersection(second)
|
438 |
+
expected = index.drop(index).set_names(expected_name)
|
439 |
+
tm.assert_index_equal(intersect, expected)
|
440 |
+
|
441 |
+
# Test empty.intersection(empty)
|
442 |
+
first = index.drop(index).set_names(fname)
|
443 |
+
second = index.drop(index).set_names(sname)
|
444 |
+
intersect = first.intersection(second)
|
445 |
+
expected = index.drop(index).set_names(expected_name)
|
446 |
+
tm.assert_index_equal(intersect, expected)
|
447 |
+
|
448 |
+
@pytest.mark.parametrize(
|
449 |
+
"fname, sname, expected_name",
|
450 |
+
[
|
451 |
+
("A", "A", "A"),
|
452 |
+
("A", "B", None),
|
453 |
+
("A", None, None),
|
454 |
+
(None, "B", None),
|
455 |
+
(None, None, None),
|
456 |
+
],
|
457 |
+
)
|
458 |
+
def test_intersect_unequal(self, index_flat, fname, sname, expected_name):
|
459 |
+
if not index_flat.is_unique:
|
460 |
+
index = index_flat.unique()
|
461 |
+
else:
|
462 |
+
index = index_flat
|
463 |
+
|
464 |
+
# test copy.intersection(subset) - need sort for unicode and string
|
465 |
+
first = index.copy().set_names(fname)
|
466 |
+
second = index[1:].set_names(sname)
|
467 |
+
intersect = first.intersection(second).sort_values()
|
468 |
+
expected = index[1:].set_names(expected_name).sort_values()
|
469 |
+
tm.assert_index_equal(intersect, expected)
|
470 |
+
|
471 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
472 |
+
def test_intersection_name_retention_with_nameless(self, index):
|
473 |
+
if isinstance(index, MultiIndex):
|
474 |
+
index = index.rename(list(range(index.nlevels)))
|
475 |
+
else:
|
476 |
+
index = index.rename("foo")
|
477 |
+
|
478 |
+
other = np.asarray(index)
|
479 |
+
|
480 |
+
result = index.intersection(other)
|
481 |
+
assert result.name == index.name
|
482 |
+
|
483 |
+
# empty other, same dtype
|
484 |
+
result = index.intersection(other[:0])
|
485 |
+
assert result.name == index.name
|
486 |
+
|
487 |
+
# empty `self`
|
488 |
+
result = index[:0].intersection(other)
|
489 |
+
assert result.name == index.name
|
490 |
+
|
491 |
+
def test_difference_preserves_type_empty(self, index, sort):
|
492 |
+
# GH#20040
|
493 |
+
# If taking difference of a set and itself, it
|
494 |
+
# needs to preserve the type of the index
|
495 |
+
if not index.is_unique:
|
496 |
+
pytest.skip("Not relevant since index is not unique")
|
497 |
+
result = index.difference(index, sort=sort)
|
498 |
+
expected = index[:0]
|
499 |
+
tm.assert_index_equal(result, expected, exact=True)
|
500 |
+
|
501 |
+
def test_difference_name_retention_equals(self, index, names):
|
502 |
+
if isinstance(index, MultiIndex):
|
503 |
+
names = [[x] * index.nlevels for x in names]
|
504 |
+
index = index.rename(names[0])
|
505 |
+
other = index.rename(names[1])
|
506 |
+
|
507 |
+
assert index.equals(other)
|
508 |
+
|
509 |
+
result = index.difference(other)
|
510 |
+
expected = index[:0].rename(names[2])
|
511 |
+
tm.assert_index_equal(result, expected)
|
512 |
+
|
513 |
+
def test_intersection_difference_match_empty(self, index, sort):
|
514 |
+
# GH#20040
|
515 |
+
# Test that the intersection of an index with an
|
516 |
+
# empty index produces the same index as the difference
|
517 |
+
# of an index with itself. Test for all types
|
518 |
+
if not index.is_unique:
|
519 |
+
pytest.skip("Not relevant because index is not unique")
|
520 |
+
inter = index.intersection(index[:0])
|
521 |
+
diff = index.difference(index, sort=sort)
|
522 |
+
tm.assert_index_equal(inter, diff, exact=True)
|
523 |
+
|
524 |
+
|
525 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
526 |
+
@pytest.mark.filterwarnings(
|
527 |
+
"ignore:Falling back on a non-pyarrow:pandas.errors.PerformanceWarning"
|
528 |
+
)
|
529 |
+
@pytest.mark.parametrize(
|
530 |
+
"method", ["intersection", "union", "difference", "symmetric_difference"]
|
531 |
+
)
|
532 |
+
def test_setop_with_categorical(index_flat, sort, method):
|
533 |
+
# MultiIndex tested separately in tests.indexes.multi.test_setops
|
534 |
+
index = index_flat
|
535 |
+
|
536 |
+
other = index.astype("category")
|
537 |
+
exact = "equiv" if isinstance(index, RangeIndex) else True
|
538 |
+
|
539 |
+
result = getattr(index, method)(other, sort=sort)
|
540 |
+
expected = getattr(index, method)(index, sort=sort)
|
541 |
+
tm.assert_index_equal(result, expected, exact=exact)
|
542 |
+
|
543 |
+
result = getattr(index, method)(other[:5], sort=sort)
|
544 |
+
expected = getattr(index, method)(index[:5], sort=sort)
|
545 |
+
tm.assert_index_equal(result, expected, exact=exact)
|
546 |
+
|
547 |
+
|
548 |
+
def test_intersection_duplicates_all_indexes(index):
|
549 |
+
# GH#38743
|
550 |
+
if index.empty:
|
551 |
+
# No duplicates in empty indexes
|
552 |
+
pytest.skip("Not relevant for empty Index")
|
553 |
+
|
554 |
+
idx = index
|
555 |
+
idx_non_unique = idx[[0, 0, 1, 2]]
|
556 |
+
|
557 |
+
assert idx.intersection(idx_non_unique).equals(idx_non_unique.intersection(idx))
|
558 |
+
assert idx.intersection(idx_non_unique).is_unique
|
559 |
+
|
560 |
+
|
561 |
+
def test_union_duplicate_index_subsets_of_each_other(
|
562 |
+
any_dtype_for_small_pos_integer_indexes,
|
563 |
+
):
|
564 |
+
# GH#31326
|
565 |
+
dtype = any_dtype_for_small_pos_integer_indexes
|
566 |
+
a = Index([1, 2, 2, 3], dtype=dtype)
|
567 |
+
b = Index([3, 3, 4], dtype=dtype)
|
568 |
+
|
569 |
+
expected = Index([1, 2, 2, 3, 3, 4], dtype=dtype)
|
570 |
+
if isinstance(a, CategoricalIndex):
|
571 |
+
expected = Index([1, 2, 2, 3, 3, 4])
|
572 |
+
result = a.union(b)
|
573 |
+
tm.assert_index_equal(result, expected)
|
574 |
+
result = a.union(b, sort=False)
|
575 |
+
tm.assert_index_equal(result, expected)
|
576 |
+
|
577 |
+
|
578 |
+
def test_union_with_duplicate_index_and_non_monotonic(
|
579 |
+
any_dtype_for_small_pos_integer_indexes,
|
580 |
+
):
|
581 |
+
# GH#36289
|
582 |
+
dtype = any_dtype_for_small_pos_integer_indexes
|
583 |
+
a = Index([1, 0, 0], dtype=dtype)
|
584 |
+
b = Index([0, 1], dtype=dtype)
|
585 |
+
expected = Index([0, 0, 1], dtype=dtype)
|
586 |
+
|
587 |
+
result = a.union(b)
|
588 |
+
tm.assert_index_equal(result, expected)
|
589 |
+
|
590 |
+
result = b.union(a)
|
591 |
+
tm.assert_index_equal(result, expected)
|
592 |
+
|
593 |
+
|
594 |
+
def test_union_duplicate_index_different_dtypes():
|
595 |
+
# GH#36289
|
596 |
+
a = Index([1, 2, 2, 3])
|
597 |
+
b = Index(["1", "0", "0"])
|
598 |
+
expected = Index([1, 2, 2, 3, "1", "0", "0"])
|
599 |
+
result = a.union(b, sort=False)
|
600 |
+
tm.assert_index_equal(result, expected)
|
601 |
+
|
602 |
+
|
603 |
+
def test_union_same_value_duplicated_in_both():
|
604 |
+
# GH#36289
|
605 |
+
a = Index([0, 0, 1])
|
606 |
+
b = Index([0, 0, 1, 2])
|
607 |
+
result = a.union(b)
|
608 |
+
expected = Index([0, 0, 1, 2])
|
609 |
+
tm.assert_index_equal(result, expected)
|
610 |
+
|
611 |
+
|
612 |
+
@pytest.mark.parametrize("dup", [1, np.nan])
|
613 |
+
def test_union_nan_in_both(dup):
|
614 |
+
# GH#36289
|
615 |
+
a = Index([np.nan, 1, 2, 2])
|
616 |
+
b = Index([np.nan, dup, 1, 2])
|
617 |
+
result = a.union(b, sort=False)
|
618 |
+
expected = Index([np.nan, dup, 1.0, 2.0, 2.0])
|
619 |
+
tm.assert_index_equal(result, expected)
|
620 |
+
|
621 |
+
|
622 |
+
def test_union_rangeindex_sort_true():
|
623 |
+
# GH 53490
|
624 |
+
idx1 = RangeIndex(1, 100, 6)
|
625 |
+
idx2 = RangeIndex(1, 50, 3)
|
626 |
+
result = idx1.union(idx2, sort=True)
|
627 |
+
expected = Index(
|
628 |
+
[
|
629 |
+
1,
|
630 |
+
4,
|
631 |
+
7,
|
632 |
+
10,
|
633 |
+
13,
|
634 |
+
16,
|
635 |
+
19,
|
636 |
+
22,
|
637 |
+
25,
|
638 |
+
28,
|
639 |
+
31,
|
640 |
+
34,
|
641 |
+
37,
|
642 |
+
40,
|
643 |
+
43,
|
644 |
+
46,
|
645 |
+
49,
|
646 |
+
55,
|
647 |
+
61,
|
648 |
+
67,
|
649 |
+
73,
|
650 |
+
79,
|
651 |
+
85,
|
652 |
+
91,
|
653 |
+
97,
|
654 |
+
]
|
655 |
+
)
|
656 |
+
tm.assert_index_equal(result, expected)
|
657 |
+
|
658 |
+
|
659 |
+
def test_union_with_duplicate_index_not_subset_and_non_monotonic(
|
660 |
+
any_dtype_for_small_pos_integer_indexes,
|
661 |
+
):
|
662 |
+
# GH#36289
|
663 |
+
dtype = any_dtype_for_small_pos_integer_indexes
|
664 |
+
a = Index([1, 0, 2], dtype=dtype)
|
665 |
+
b = Index([0, 0, 1], dtype=dtype)
|
666 |
+
expected = Index([0, 0, 1, 2], dtype=dtype)
|
667 |
+
if isinstance(a, CategoricalIndex):
|
668 |
+
expected = Index([0, 0, 1, 2])
|
669 |
+
|
670 |
+
result = a.union(b)
|
671 |
+
tm.assert_index_equal(result, expected)
|
672 |
+
|
673 |
+
result = b.union(a)
|
674 |
+
tm.assert_index_equal(result, expected)
|
675 |
+
|
676 |
+
|
677 |
+
def test_union_int_categorical_with_nan():
|
678 |
+
ci = CategoricalIndex([1, 2, np.nan])
|
679 |
+
assert ci.categories.dtype.kind == "i"
|
680 |
+
|
681 |
+
idx = Index([1, 2])
|
682 |
+
|
683 |
+
result = idx.union(ci)
|
684 |
+
expected = Index([1, 2, np.nan], dtype=np.float64)
|
685 |
+
tm.assert_index_equal(result, expected)
|
686 |
+
|
687 |
+
result = ci.union(idx)
|
688 |
+
tm.assert_index_equal(result, expected)
|
689 |
+
|
690 |
+
|
691 |
+
class TestSetOpsUnsorted:
|
692 |
+
# These may eventually belong in a dtype-specific test_setops, or
|
693 |
+
# parametrized over a more general fixture
|
694 |
+
def test_intersect_str_dates(self):
|
695 |
+
dt_dates = [datetime(2012, 2, 9), datetime(2012, 2, 22)]
|
696 |
+
|
697 |
+
index1 = Index(dt_dates, dtype=object)
|
698 |
+
index2 = Index(["aa"], dtype=object)
|
699 |
+
result = index2.intersection(index1)
|
700 |
+
|
701 |
+
expected = Index([], dtype=object)
|
702 |
+
tm.assert_index_equal(result, expected)
|
703 |
+
|
704 |
+
@pytest.mark.parametrize("index", ["string"], indirect=True)
|
705 |
+
def test_intersection(self, index, sort):
|
706 |
+
first = index[:20]
|
707 |
+
second = index[:10]
|
708 |
+
intersect = first.intersection(second, sort=sort)
|
709 |
+
if sort in (None, False):
|
710 |
+
tm.assert_index_equal(intersect.sort_values(), second.sort_values())
|
711 |
+
else:
|
712 |
+
tm.assert_index_equal(intersect, second)
|
713 |
+
|
714 |
+
# Corner cases
|
715 |
+
inter = first.intersection(first, sort=sort)
|
716 |
+
assert inter is first
|
717 |
+
|
718 |
+
@pytest.mark.parametrize(
|
719 |
+
"index2,keeps_name",
|
720 |
+
[
|
721 |
+
(Index([3, 4, 5, 6, 7], name="index"), True), # preserve same name
|
722 |
+
(Index([3, 4, 5, 6, 7], name="other"), False), # drop diff names
|
723 |
+
(Index([3, 4, 5, 6, 7]), False),
|
724 |
+
],
|
725 |
+
)
|
726 |
+
def test_intersection_name_preservation(self, index2, keeps_name, sort):
|
727 |
+
index1 = Index([1, 2, 3, 4, 5], name="index")
|
728 |
+
expected = Index([3, 4, 5])
|
729 |
+
result = index1.intersection(index2, sort)
|
730 |
+
|
731 |
+
if keeps_name:
|
732 |
+
expected.name = "index"
|
733 |
+
|
734 |
+
assert result.name == expected.name
|
735 |
+
tm.assert_index_equal(result, expected)
|
736 |
+
|
737 |
+
@pytest.mark.parametrize("index", ["string"], indirect=True)
|
738 |
+
@pytest.mark.parametrize(
|
739 |
+
"first_name,second_name,expected_name",
|
740 |
+
[("A", "A", "A"), ("A", "B", None), (None, "B", None)],
|
741 |
+
)
|
742 |
+
def test_intersection_name_preservation2(
|
743 |
+
self, index, first_name, second_name, expected_name, sort
|
744 |
+
):
|
745 |
+
first = index[5:20]
|
746 |
+
second = index[:10]
|
747 |
+
first.name = first_name
|
748 |
+
second.name = second_name
|
749 |
+
intersect = first.intersection(second, sort=sort)
|
750 |
+
assert intersect.name == expected_name
|
751 |
+
|
752 |
+
def test_chained_union(self, sort):
|
753 |
+
# Chained unions handles names correctly
|
754 |
+
i1 = Index([1, 2], name="i1")
|
755 |
+
i2 = Index([5, 6], name="i2")
|
756 |
+
i3 = Index([3, 4], name="i3")
|
757 |
+
union = i1.union(i2.union(i3, sort=sort), sort=sort)
|
758 |
+
expected = i1.union(i2, sort=sort).union(i3, sort=sort)
|
759 |
+
tm.assert_index_equal(union, expected)
|
760 |
+
|
761 |
+
j1 = Index([1, 2], name="j1")
|
762 |
+
j2 = Index([], name="j2")
|
763 |
+
j3 = Index([], name="j3")
|
764 |
+
union = j1.union(j2.union(j3, sort=sort), sort=sort)
|
765 |
+
expected = j1.union(j2, sort=sort).union(j3, sort=sort)
|
766 |
+
tm.assert_index_equal(union, expected)
|
767 |
+
|
768 |
+
@pytest.mark.parametrize("index", ["string"], indirect=True)
|
769 |
+
def test_union(self, index, sort):
|
770 |
+
first = index[5:20]
|
771 |
+
second = index[:10]
|
772 |
+
everything = index[:20]
|
773 |
+
|
774 |
+
union = first.union(second, sort=sort)
|
775 |
+
if sort in (None, False):
|
776 |
+
tm.assert_index_equal(union.sort_values(), everything.sort_values())
|
777 |
+
else:
|
778 |
+
tm.assert_index_equal(union, everything)
|
779 |
+
|
780 |
+
@pytest.mark.parametrize("klass", [np.array, Series, list])
|
781 |
+
@pytest.mark.parametrize("index", ["string"], indirect=True)
|
782 |
+
def test_union_from_iterables(self, index, klass, sort):
|
783 |
+
# GH#10149
|
784 |
+
first = index[5:20]
|
785 |
+
second = index[:10]
|
786 |
+
everything = index[:20]
|
787 |
+
|
788 |
+
case = klass(second.values)
|
789 |
+
result = first.union(case, sort=sort)
|
790 |
+
if sort in (None, False):
|
791 |
+
tm.assert_index_equal(result.sort_values(), everything.sort_values())
|
792 |
+
else:
|
793 |
+
tm.assert_index_equal(result, everything)
|
794 |
+
|
795 |
+
@pytest.mark.parametrize("index", ["string"], indirect=True)
|
796 |
+
def test_union_identity(self, index, sort):
|
797 |
+
first = index[5:20]
|
798 |
+
|
799 |
+
union = first.union(first, sort=sort)
|
800 |
+
# i.e. identity is not preserved when sort is True
|
801 |
+
assert (union is first) is (not sort)
|
802 |
+
|
803 |
+
# This should no longer be the same object, since [] is not consistent,
|
804 |
+
# both objects will be recast to dtype('O')
|
805 |
+
union = first.union(Index([], dtype=first.dtype), sort=sort)
|
806 |
+
assert (union is first) is (not sort)
|
807 |
+
|
808 |
+
union = Index([], dtype=first.dtype).union(first, sort=sort)
|
809 |
+
assert (union is first) is (not sort)
|
810 |
+
|
811 |
+
@pytest.mark.parametrize("index", ["string"], indirect=True)
|
812 |
+
@pytest.mark.parametrize("second_name,expected", [(None, None), ("name", "name")])
|
813 |
+
def test_difference_name_preservation(self, index, second_name, expected, sort):
|
814 |
+
first = index[5:20]
|
815 |
+
second = index[:10]
|
816 |
+
answer = index[10:20]
|
817 |
+
|
818 |
+
first.name = "name"
|
819 |
+
second.name = second_name
|
820 |
+
result = first.difference(second, sort=sort)
|
821 |
+
|
822 |
+
if sort is True:
|
823 |
+
tm.assert_index_equal(result, answer)
|
824 |
+
else:
|
825 |
+
answer.name = second_name
|
826 |
+
tm.assert_index_equal(result.sort_values(), answer.sort_values())
|
827 |
+
|
828 |
+
if expected is None:
|
829 |
+
assert result.name is None
|
830 |
+
else:
|
831 |
+
assert result.name == expected
|
832 |
+
|
833 |
+
def test_difference_empty_arg(self, index, sort):
|
834 |
+
first = index.copy()
|
835 |
+
first = first[5:20]
|
836 |
+
first.name = "name"
|
837 |
+
result = first.difference([], sort)
|
838 |
+
expected = index[5:20].unique()
|
839 |
+
expected.name = "name"
|
840 |
+
tm.assert_index_equal(result, expected)
|
841 |
+
|
842 |
+
def test_difference_should_not_compare(self):
|
843 |
+
# GH 55113
|
844 |
+
left = Index([1, 1])
|
845 |
+
right = Index([True])
|
846 |
+
result = left.difference(right)
|
847 |
+
expected = Index([1])
|
848 |
+
tm.assert_index_equal(result, expected)
|
849 |
+
|
850 |
+
@pytest.mark.parametrize("index", ["string"], indirect=True)
|
851 |
+
def test_difference_identity(self, index, sort):
|
852 |
+
first = index[5:20]
|
853 |
+
first.name = "name"
|
854 |
+
result = first.difference(first, sort)
|
855 |
+
|
856 |
+
assert len(result) == 0
|
857 |
+
assert result.name == first.name
|
858 |
+
|
859 |
+
@pytest.mark.parametrize("index", ["string"], indirect=True)
|
860 |
+
def test_difference_sort(self, index, sort):
|
861 |
+
first = index[5:20]
|
862 |
+
second = index[:10]
|
863 |
+
|
864 |
+
result = first.difference(second, sort)
|
865 |
+
expected = index[10:20]
|
866 |
+
|
867 |
+
if sort is None:
|
868 |
+
expected = expected.sort_values()
|
869 |
+
|
870 |
+
tm.assert_index_equal(result, expected)
|
871 |
+
|
872 |
+
@pytest.mark.parametrize("opname", ["difference", "symmetric_difference"])
|
873 |
+
def test_difference_incomparable(self, opname):
|
874 |
+
a = Index([3, Timestamp("2000"), 1])
|
875 |
+
b = Index([2, Timestamp("1999"), 1])
|
876 |
+
op = operator.methodcaller(opname, b)
|
877 |
+
|
878 |
+
with tm.assert_produces_warning(RuntimeWarning):
|
879 |
+
# sort=None, the default
|
880 |
+
result = op(a)
|
881 |
+
expected = Index([3, Timestamp("2000"), 2, Timestamp("1999")])
|
882 |
+
if opname == "difference":
|
883 |
+
expected = expected[:2]
|
884 |
+
tm.assert_index_equal(result, expected)
|
885 |
+
|
886 |
+
# sort=False
|
887 |
+
op = operator.methodcaller(opname, b, sort=False)
|
888 |
+
result = op(a)
|
889 |
+
tm.assert_index_equal(result, expected)
|
890 |
+
|
891 |
+
@pytest.mark.parametrize("opname", ["difference", "symmetric_difference"])
|
892 |
+
def test_difference_incomparable_true(self, opname):
|
893 |
+
a = Index([3, Timestamp("2000"), 1])
|
894 |
+
b = Index([2, Timestamp("1999"), 1])
|
895 |
+
op = operator.methodcaller(opname, b, sort=True)
|
896 |
+
|
897 |
+
msg = "'<' not supported between instances of 'Timestamp' and 'int'"
|
898 |
+
with pytest.raises(TypeError, match=msg):
|
899 |
+
op(a)
|
900 |
+
|
901 |
+
def test_symmetric_difference_mi(self, sort):
|
902 |
+
index1 = MultiIndex.from_tuples(zip(["foo", "bar", "baz"], [1, 2, 3]))
|
903 |
+
index2 = MultiIndex.from_tuples([("foo", 1), ("bar", 3)])
|
904 |
+
result = index1.symmetric_difference(index2, sort=sort)
|
905 |
+
expected = MultiIndex.from_tuples([("bar", 2), ("baz", 3), ("bar", 3)])
|
906 |
+
if sort is None:
|
907 |
+
expected = expected.sort_values()
|
908 |
+
tm.assert_index_equal(result, expected)
|
909 |
+
|
910 |
+
@pytest.mark.parametrize(
|
911 |
+
"index2,expected",
|
912 |
+
[
|
913 |
+
(Index([0, 1, np.nan]), Index([2.0, 3.0, 0.0])),
|
914 |
+
(Index([0, 1]), Index([np.nan, 2.0, 3.0, 0.0])),
|
915 |
+
],
|
916 |
+
)
|
917 |
+
def test_symmetric_difference_missing(self, index2, expected, sort):
|
918 |
+
# GH#13514 change: {nan} - {nan} == {}
|
919 |
+
# (GH#6444, sorting of nans, is no longer an issue)
|
920 |
+
index1 = Index([1, np.nan, 2, 3])
|
921 |
+
|
922 |
+
result = index1.symmetric_difference(index2, sort=sort)
|
923 |
+
if sort is None:
|
924 |
+
expected = expected.sort_values()
|
925 |
+
tm.assert_index_equal(result, expected)
|
926 |
+
|
927 |
+
def test_symmetric_difference_non_index(self, sort):
|
928 |
+
index1 = Index([1, 2, 3, 4], name="index1")
|
929 |
+
index2 = np.array([2, 3, 4, 5])
|
930 |
+
expected = Index([1, 5], name="index1")
|
931 |
+
result = index1.symmetric_difference(index2, sort=sort)
|
932 |
+
if sort in (None, True):
|
933 |
+
tm.assert_index_equal(result, expected)
|
934 |
+
else:
|
935 |
+
tm.assert_index_equal(result.sort_values(), expected)
|
936 |
+
assert result.name == "index1"
|
937 |
+
|
938 |
+
result = index1.symmetric_difference(index2, result_name="new_name", sort=sort)
|
939 |
+
expected.name = "new_name"
|
940 |
+
if sort in (None, True):
|
941 |
+
tm.assert_index_equal(result, expected)
|
942 |
+
else:
|
943 |
+
tm.assert_index_equal(result.sort_values(), expected)
|
944 |
+
assert result.name == "new_name"
|
945 |
+
|
946 |
+
def test_union_ea_dtypes(self, any_numeric_ea_and_arrow_dtype):
|
947 |
+
# GH#51365
|
948 |
+
idx = Index([1, 2, 3], dtype=any_numeric_ea_and_arrow_dtype)
|
949 |
+
idx2 = Index([3, 4, 5], dtype=any_numeric_ea_and_arrow_dtype)
|
950 |
+
result = idx.union(idx2)
|
951 |
+
expected = Index([1, 2, 3, 4, 5], dtype=any_numeric_ea_and_arrow_dtype)
|
952 |
+
tm.assert_index_equal(result, expected)
|
953 |
+
|
954 |
+
def test_union_string_array(self, any_string_dtype):
|
955 |
+
idx1 = Index(["a"], dtype=any_string_dtype)
|
956 |
+
idx2 = Index(["b"], dtype=any_string_dtype)
|
957 |
+
result = idx1.union(idx2)
|
958 |
+
expected = Index(["a", "b"], dtype=any_string_dtype)
|
959 |
+
tm.assert_index_equal(result, expected)
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/indexes/test_subclass.py
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Tests involving custom Index subclasses
|
3 |
+
"""
|
4 |
+
import numpy as np
|
5 |
+
|
6 |
+
from pandas import (
|
7 |
+
DataFrame,
|
8 |
+
Index,
|
9 |
+
)
|
10 |
+
import pandas._testing as tm
|
11 |
+
|
12 |
+
|
13 |
+
class CustomIndex(Index):
|
14 |
+
def __new__(cls, data, name=None):
|
15 |
+
# assert that this index class cannot hold strings
|
16 |
+
if any(isinstance(val, str) for val in data):
|
17 |
+
raise TypeError("CustomIndex cannot hold strings")
|
18 |
+
|
19 |
+
if name is None and hasattr(data, "name"):
|
20 |
+
name = data.name
|
21 |
+
data = np.array(data, dtype="O")
|
22 |
+
|
23 |
+
return cls._simple_new(data, name)
|
24 |
+
|
25 |
+
|
26 |
+
def test_insert_fallback_to_base_index():
|
27 |
+
# https://github.com/pandas-dev/pandas/issues/47071
|
28 |
+
|
29 |
+
idx = CustomIndex([1, 2, 3])
|
30 |
+
result = idx.insert(0, "string")
|
31 |
+
expected = Index(["string", 1, 2, 3], dtype=object)
|
32 |
+
tm.assert_index_equal(result, expected)
|
33 |
+
|
34 |
+
df = DataFrame(
|
35 |
+
np.random.default_rng(2).standard_normal((2, 3)),
|
36 |
+
columns=idx,
|
37 |
+
index=Index([1, 2], name="string"),
|
38 |
+
)
|
39 |
+
result = df.reset_index()
|
40 |
+
tm.assert_index_equal(result.columns, expected)
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/resample/__init__.py
ADDED
File without changes
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/resample/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (186 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/pandas/tests/resample/__pycache__/conftest.cpython-310.pyc
ADDED
Binary file (3.64 kB). View file
|
|