applied-ai-018 commited on
Commit
c0aa3bc
·
verified ·
1 Parent(s): 1c57666

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ckpts/universal/global_step80/zero/19.attention.query_key_value.weight/exp_avg_sq.pt +3 -0
  2. ckpts/universal/global_step80/zero/23.mlp.dense_h_to_4h_swiglu.weight/exp_avg_sq.pt +3 -0
  3. ckpts/universal/global_step80/zero/23.mlp.dense_h_to_4h_swiglu.weight/fp32.pt +3 -0
  4. ckpts/universal/global_step80/zero/4.input_layernorm.weight/exp_avg.pt +3 -0
  5. ckpts/universal/global_step80/zero/4.input_layernorm.weight/exp_avg_sq.pt +3 -0
  6. ckpts/universal/global_step80/zero/4.input_layernorm.weight/fp32.pt +3 -0
  7. venv/lib/python3.10/site-packages/pandas/tests/indexes/__init__.py +0 -0
  8. venv/lib/python3.10/site-packages/pandas/tests/indexes/conftest.py +41 -0
  9. venv/lib/python3.10/site-packages/pandas/tests/indexes/numeric/test_numeric.py +553 -0
  10. venv/lib/python3.10/site-packages/pandas/tests/indexes/test_any_index.py +172 -0
  11. venv/lib/python3.10/site-packages/pandas/tests/indexes/test_base.py +1737 -0
  12. venv/lib/python3.10/site-packages/pandas/tests/indexes/test_common.py +511 -0
  13. venv/lib/python3.10/site-packages/pandas/tests/indexes/test_datetimelike.py +171 -0
  14. venv/lib/python3.10/site-packages/pandas/tests/indexes/test_engines.py +192 -0
  15. venv/lib/python3.10/site-packages/pandas/tests/indexes/test_frozen.py +113 -0
  16. venv/lib/python3.10/site-packages/pandas/tests/indexes/test_index_new.py +432 -0
  17. venv/lib/python3.10/site-packages/pandas/tests/indexes/test_indexing.py +357 -0
  18. venv/lib/python3.10/site-packages/pandas/tests/indexes/test_numpy_compat.py +189 -0
  19. venv/lib/python3.10/site-packages/pandas/tests/indexes/test_old_base.py +1061 -0
  20. venv/lib/python3.10/site-packages/pandas/tests/indexes/test_setops.py +959 -0
  21. venv/lib/python3.10/site-packages/pandas/tests/indexes/test_subclass.py +40 -0
  22. venv/lib/python3.10/site-packages/pandas/tests/reshape/__init__.py +0 -0
  23. venv/lib/python3.10/site-packages/pandas/tests/reshape/__pycache__/__init__.cpython-310.pyc +0 -0
  24. venv/lib/python3.10/site-packages/pandas/tests/reshape/__pycache__/test_crosstab.cpython-310.pyc +0 -0
  25. venv/lib/python3.10/site-packages/pandas/tests/reshape/__pycache__/test_cut.cpython-310.pyc +0 -0
  26. venv/lib/python3.10/site-packages/pandas/tests/reshape/__pycache__/test_from_dummies.cpython-310.pyc +0 -0
  27. venv/lib/python3.10/site-packages/pandas/tests/reshape/__pycache__/test_get_dummies.cpython-310.pyc +0 -0
  28. venv/lib/python3.10/site-packages/pandas/tests/reshape/__pycache__/test_melt.cpython-310.pyc +0 -0
  29. venv/lib/python3.10/site-packages/pandas/tests/reshape/__pycache__/test_pivot.cpython-310.pyc +0 -0
  30. venv/lib/python3.10/site-packages/pandas/tests/reshape/__pycache__/test_pivot_multilevel.cpython-310.pyc +0 -0
  31. venv/lib/python3.10/site-packages/pandas/tests/reshape/__pycache__/test_qcut.cpython-310.pyc +0 -0
  32. venv/lib/python3.10/site-packages/pandas/tests/reshape/__pycache__/test_union_categoricals.cpython-310.pyc +0 -0
  33. venv/lib/python3.10/site-packages/pandas/tests/reshape/__pycache__/test_util.cpython-310.pyc +0 -0
  34. venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/__init__.py +0 -0
  35. venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/__pycache__/__init__.cpython-310.pyc +0 -0
  36. venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/__pycache__/conftest.cpython-310.pyc +0 -0
  37. venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/__pycache__/test_append.cpython-310.pyc +0 -0
  38. venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/__pycache__/test_append_common.cpython-310.pyc +0 -0
  39. venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/__pycache__/test_categorical.cpython-310.pyc +0 -0
  40. venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/__pycache__/test_concat.cpython-310.pyc +0 -0
  41. venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/__pycache__/test_dataframe.cpython-310.pyc +0 -0
  42. venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/__pycache__/test_datetimes.cpython-310.pyc +0 -0
  43. venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/__pycache__/test_empty.cpython-310.pyc +0 -0
  44. venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/__pycache__/test_index.cpython-310.pyc +0 -0
  45. venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/__pycache__/test_invalid.cpython-310.pyc +0 -0
  46. venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/__pycache__/test_series.cpython-310.pyc +0 -0
  47. venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/__pycache__/test_sort.cpython-310.pyc +0 -0
  48. venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/conftest.py +7 -0
  49. venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/test_append.py +389 -0
  50. venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/test_append_common.py +753 -0
ckpts/universal/global_step80/zero/19.attention.query_key_value.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3054bb0f6cc611c8e789cea7a531c3d26a4ef20b7eddff1c1852cdd70dbd3624
3
+ size 50332843
ckpts/universal/global_step80/zero/23.mlp.dense_h_to_4h_swiglu.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5c7f89f06aa4b00da404b2fd7100549ab29235ccb8ed82cea1b1efd1dce825c7
3
+ size 33555627
ckpts/universal/global_step80/zero/23.mlp.dense_h_to_4h_swiglu.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f44ea73b7083e5f96a62955209a56ad3b9d61aba008a852f38216c74d7e2c816
3
+ size 33555533
ckpts/universal/global_step80/zero/4.input_layernorm.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2a518397adb3b70de449e6e59e242887e34da4fd749b4447c33da246f803128e
3
+ size 9372
ckpts/universal/global_step80/zero/4.input_layernorm.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f9e2f12c01c745c70d5e7824fcbe05bd8aae6945f3c83d225f9522af3d69ea2a
3
+ size 9387
ckpts/universal/global_step80/zero/4.input_layernorm.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:482f8114839d6a7ea6bf930652c53bc3d9a2ce97b869af3f1716727b585ec103
3
+ size 9293
venv/lib/python3.10/site-packages/pandas/tests/indexes/__init__.py ADDED
File without changes
venv/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
venv/lib/python3.10/site-packages/pandas/tests/indexes/numeric/test_numeric.py ADDED
@@ -0,0 +1,553 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ import pandas as pd
5
+ from pandas import (
6
+ Index,
7
+ Series,
8
+ )
9
+ import pandas._testing as tm
10
+
11
+
12
+ class TestFloatNumericIndex:
13
+ @pytest.fixture(params=[np.float64, np.float32])
14
+ def dtype(self, request):
15
+ return request.param
16
+
17
+ @pytest.fixture
18
+ def simple_index(self, dtype):
19
+ values = np.arange(5, dtype=dtype)
20
+ return Index(values)
21
+
22
+ @pytest.fixture(
23
+ params=[
24
+ [1.5, 2, 3, 4, 5],
25
+ [0.0, 2.5, 5.0, 7.5, 10.0],
26
+ [5, 4, 3, 2, 1.5],
27
+ [10.0, 7.5, 5.0, 2.5, 0.0],
28
+ ],
29
+ ids=["mixed", "float", "mixed_dec", "float_dec"],
30
+ )
31
+ def index(self, request, dtype):
32
+ return Index(request.param, dtype=dtype)
33
+
34
+ @pytest.fixture
35
+ def mixed_index(self, dtype):
36
+ return Index([1.5, 2, 3, 4, 5], dtype=dtype)
37
+
38
+ @pytest.fixture
39
+ def float_index(self, dtype):
40
+ return Index([0.0, 2.5, 5.0, 7.5, 10.0], dtype=dtype)
41
+
42
+ def test_repr_roundtrip(self, index):
43
+ tm.assert_index_equal(eval(repr(index)), index, exact=True)
44
+
45
+ def check_coerce(self, a, b, is_float_index=True):
46
+ assert a.equals(b)
47
+ tm.assert_index_equal(a, b, exact=False)
48
+ if is_float_index:
49
+ assert isinstance(b, Index)
50
+ else:
51
+ assert type(b) is Index
52
+
53
+ def test_constructor_from_list_no_dtype(self):
54
+ index = Index([1.5, 2.5, 3.5])
55
+ assert index.dtype == np.float64
56
+
57
+ def test_constructor(self, dtype):
58
+ index_cls = Index
59
+
60
+ # explicit construction
61
+ index = index_cls([1, 2, 3, 4, 5], dtype=dtype)
62
+
63
+ assert isinstance(index, index_cls)
64
+ assert index.dtype == dtype
65
+
66
+ expected = np.array([1, 2, 3, 4, 5], dtype=dtype)
67
+ tm.assert_numpy_array_equal(index.values, expected)
68
+
69
+ index = index_cls(np.array([1, 2, 3, 4, 5]), dtype=dtype)
70
+ assert isinstance(index, index_cls)
71
+ assert index.dtype == dtype
72
+
73
+ index = index_cls([1.0, 2, 3, 4, 5], dtype=dtype)
74
+ assert isinstance(index, index_cls)
75
+ assert index.dtype == dtype
76
+
77
+ index = index_cls(np.array([1.0, 2, 3, 4, 5]), dtype=dtype)
78
+ assert isinstance(index, index_cls)
79
+ assert index.dtype == dtype
80
+
81
+ index = index_cls([1.0, 2, 3, 4, 5], dtype=dtype)
82
+ assert isinstance(index, index_cls)
83
+ assert index.dtype == dtype
84
+
85
+ index = index_cls(np.array([1.0, 2, 3, 4, 5]), dtype=dtype)
86
+ assert isinstance(index, index_cls)
87
+ assert index.dtype == dtype
88
+
89
+ # nan handling
90
+ result = index_cls([np.nan, np.nan], dtype=dtype)
91
+ assert pd.isna(result.values).all()
92
+
93
+ result = index_cls(np.array([np.nan]), dtype=dtype)
94
+ assert pd.isna(result.values).all()
95
+
96
+ def test_constructor_invalid(self):
97
+ index_cls = Index
98
+ cls_name = index_cls.__name__
99
+ # invalid
100
+ msg = (
101
+ rf"{cls_name}\(\.\.\.\) must be called with a collection of "
102
+ r"some kind, 0\.0 was passed"
103
+ )
104
+ with pytest.raises(TypeError, match=msg):
105
+ index_cls(0.0)
106
+
107
+ def test_constructor_coerce(self, mixed_index, float_index):
108
+ self.check_coerce(mixed_index, Index([1.5, 2, 3, 4, 5]))
109
+ self.check_coerce(float_index, Index(np.arange(5) * 2.5))
110
+
111
+ result = Index(np.array(np.arange(5) * 2.5, dtype=object))
112
+ assert result.dtype == object # as of 2.0 to match Series
113
+ self.check_coerce(float_index, result.astype("float64"))
114
+
115
+ def test_constructor_explicit(self, mixed_index, float_index):
116
+ # these don't auto convert
117
+ self.check_coerce(
118
+ float_index, Index((np.arange(5) * 2.5), dtype=object), is_float_index=False
119
+ )
120
+ self.check_coerce(
121
+ mixed_index, Index([1.5, 2, 3, 4, 5], dtype=object), is_float_index=False
122
+ )
123
+
124
+ def test_type_coercion_fail(self, any_int_numpy_dtype):
125
+ # see gh-15832
126
+ msg = "Trying to coerce float values to integers"
127
+ with pytest.raises(ValueError, match=msg):
128
+ Index([1, 2, 3.5], dtype=any_int_numpy_dtype)
129
+
130
+ def test_equals_numeric(self):
131
+ index_cls = Index
132
+
133
+ idx = index_cls([1.0, 2.0])
134
+ assert idx.equals(idx)
135
+ assert idx.identical(idx)
136
+
137
+ idx2 = index_cls([1.0, 2.0])
138
+ assert idx.equals(idx2)
139
+
140
+ idx = index_cls([1.0, np.nan])
141
+ assert idx.equals(idx)
142
+ assert idx.identical(idx)
143
+
144
+ idx2 = index_cls([1.0, np.nan])
145
+ assert idx.equals(idx2)
146
+
147
+ @pytest.mark.parametrize(
148
+ "other",
149
+ (
150
+ Index([1, 2], dtype=np.int64),
151
+ Index([1.0, 2.0], dtype=object),
152
+ Index([1, 2], dtype=object),
153
+ ),
154
+ )
155
+ def test_equals_numeric_other_index_type(self, other):
156
+ idx = Index([1.0, 2.0])
157
+ assert idx.equals(other)
158
+ assert other.equals(idx)
159
+
160
+ @pytest.mark.parametrize(
161
+ "vals",
162
+ [
163
+ pd.date_range("2016-01-01", periods=3),
164
+ pd.timedelta_range("1 Day", periods=3),
165
+ ],
166
+ )
167
+ def test_lookups_datetimelike_values(self, vals, dtype):
168
+ # If we have datetime64 or timedelta64 values, make sure they are
169
+ # wrapped correctly GH#31163
170
+ ser = Series(vals, index=range(3, 6))
171
+ ser.index = ser.index.astype(dtype)
172
+
173
+ expected = vals[1]
174
+
175
+ result = ser[4.0]
176
+ assert isinstance(result, type(expected)) and result == expected
177
+ result = ser[4]
178
+ assert isinstance(result, type(expected)) and result == expected
179
+
180
+ result = ser.loc[4.0]
181
+ assert isinstance(result, type(expected)) and result == expected
182
+ result = ser.loc[4]
183
+ assert isinstance(result, type(expected)) and result == expected
184
+
185
+ result = ser.at[4.0]
186
+ assert isinstance(result, type(expected)) and result == expected
187
+ # GH#31329 .at[4] should cast to 4.0, matching .loc behavior
188
+ result = ser.at[4]
189
+ assert isinstance(result, type(expected)) and result == expected
190
+
191
+ result = ser.iloc[1]
192
+ assert isinstance(result, type(expected)) and result == expected
193
+
194
+ result = ser.iat[1]
195
+ assert isinstance(result, type(expected)) and result == expected
196
+
197
+ def test_doesnt_contain_all_the_things(self):
198
+ idx = Index([np.nan])
199
+ assert not idx.isin([0]).item()
200
+ assert not idx.isin([1]).item()
201
+ assert idx.isin([np.nan]).item()
202
+
203
+ def test_nan_multiple_containment(self):
204
+ index_cls = Index
205
+
206
+ idx = index_cls([1.0, np.nan])
207
+ tm.assert_numpy_array_equal(idx.isin([1.0]), np.array([True, False]))
208
+ tm.assert_numpy_array_equal(idx.isin([2.0, np.pi]), np.array([False, False]))
209
+ tm.assert_numpy_array_equal(idx.isin([np.nan]), np.array([False, True]))
210
+ tm.assert_numpy_array_equal(idx.isin([1.0, np.nan]), np.array([True, True]))
211
+ idx = index_cls([1.0, 2.0])
212
+ tm.assert_numpy_array_equal(idx.isin([np.nan]), np.array([False, False]))
213
+
214
+ def test_fillna_float64(self):
215
+ index_cls = Index
216
+ # GH 11343
217
+ idx = Index([1.0, np.nan, 3.0], dtype=float, name="x")
218
+ # can't downcast
219
+ exp = Index([1.0, 0.1, 3.0], name="x")
220
+ tm.assert_index_equal(idx.fillna(0.1), exp, exact=True)
221
+
222
+ # downcast
223
+ exp = index_cls([1.0, 2.0, 3.0], name="x")
224
+ tm.assert_index_equal(idx.fillna(2), exp)
225
+
226
+ # object
227
+ exp = Index([1.0, "obj", 3.0], name="x")
228
+ tm.assert_index_equal(idx.fillna("obj"), exp, exact=True)
229
+
230
+ def test_logical_compat(self, simple_index):
231
+ idx = simple_index
232
+ assert idx.all() == idx.values.all()
233
+ assert idx.any() == idx.values.any()
234
+
235
+ assert idx.all() == idx.to_series().all()
236
+ assert idx.any() == idx.to_series().any()
237
+
238
+
239
+ class TestNumericInt:
240
+ @pytest.fixture(params=[np.int64, np.int32, np.int16, np.int8, np.uint64])
241
+ def dtype(self, request):
242
+ return request.param
243
+
244
+ @pytest.fixture
245
+ def simple_index(self, dtype):
246
+ return Index(range(0, 20, 2), dtype=dtype)
247
+
248
+ def test_is_monotonic(self):
249
+ index_cls = Index
250
+
251
+ index = index_cls([1, 2, 3, 4])
252
+ assert index.is_monotonic_increasing is True
253
+ assert index.is_monotonic_increasing is True
254
+ assert index._is_strictly_monotonic_increasing is True
255
+ assert index.is_monotonic_decreasing is False
256
+ assert index._is_strictly_monotonic_decreasing is False
257
+
258
+ index = index_cls([4, 3, 2, 1])
259
+ assert index.is_monotonic_increasing is False
260
+ assert index._is_strictly_monotonic_increasing is False
261
+ assert index._is_strictly_monotonic_decreasing is True
262
+
263
+ index = index_cls([1])
264
+ assert index.is_monotonic_increasing is True
265
+ assert index.is_monotonic_increasing is True
266
+ assert index.is_monotonic_decreasing is True
267
+ assert index._is_strictly_monotonic_increasing is True
268
+ assert index._is_strictly_monotonic_decreasing is True
269
+
270
+ def test_is_strictly_monotonic(self):
271
+ index_cls = Index
272
+
273
+ index = index_cls([1, 1, 2, 3])
274
+ assert index.is_monotonic_increasing is True
275
+ assert index._is_strictly_monotonic_increasing is False
276
+
277
+ index = index_cls([3, 2, 1, 1])
278
+ assert index.is_monotonic_decreasing is True
279
+ assert index._is_strictly_monotonic_decreasing is False
280
+
281
+ index = index_cls([1, 1])
282
+ assert index.is_monotonic_increasing
283
+ assert index.is_monotonic_decreasing
284
+ assert not index._is_strictly_monotonic_increasing
285
+ assert not index._is_strictly_monotonic_decreasing
286
+
287
+ def test_logical_compat(self, simple_index):
288
+ idx = simple_index
289
+ assert idx.all() == idx.values.all()
290
+ assert idx.any() == idx.values.any()
291
+
292
+ def test_identical(self, simple_index, dtype):
293
+ index = simple_index
294
+
295
+ idx = Index(index.copy())
296
+ assert idx.identical(index)
297
+
298
+ same_values_different_type = Index(idx, dtype=object)
299
+ assert not idx.identical(same_values_different_type)
300
+
301
+ idx = index.astype(dtype=object)
302
+ idx = idx.rename("foo")
303
+ same_values = Index(idx, dtype=object)
304
+ assert same_values.identical(idx)
305
+
306
+ assert not idx.identical(index)
307
+ assert Index(same_values, name="foo", dtype=object).identical(idx)
308
+
309
+ assert not index.astype(dtype=object).identical(index.astype(dtype=dtype))
310
+
311
+ def test_cant_or_shouldnt_cast(self, dtype):
312
+ msg = r"invalid literal for int\(\) with base 10: 'foo'"
313
+
314
+ # can't
315
+ data = ["foo", "bar", "baz"]
316
+ with pytest.raises(ValueError, match=msg):
317
+ Index(data, dtype=dtype)
318
+
319
+ def test_view_index(self, simple_index):
320
+ index = simple_index
321
+ msg = "Passing a type in .*Index.view is deprecated"
322
+ with tm.assert_produces_warning(FutureWarning, match=msg):
323
+ index.view(Index)
324
+
325
+ def test_prevent_casting(self, simple_index):
326
+ index = simple_index
327
+ result = index.astype("O")
328
+ assert result.dtype == np.object_
329
+
330
+
331
+ class TestIntNumericIndex:
332
+ @pytest.fixture(params=[np.int64, np.int32, np.int16, np.int8])
333
+ def dtype(self, request):
334
+ return request.param
335
+
336
+ def test_constructor_from_list_no_dtype(self):
337
+ index = Index([1, 2, 3])
338
+ assert index.dtype == np.int64
339
+
340
+ def test_constructor(self, dtype):
341
+ index_cls = Index
342
+
343
+ # scalar raise Exception
344
+ msg = (
345
+ rf"{index_cls.__name__}\(\.\.\.\) must be called with a collection of some "
346
+ "kind, 5 was passed"
347
+ )
348
+ with pytest.raises(TypeError, match=msg):
349
+ index_cls(5)
350
+
351
+ # copy
352
+ # pass list, coerce fine
353
+ index = index_cls([-5, 0, 1, 2], dtype=dtype)
354
+ arr = index.values.copy()
355
+ new_index = index_cls(arr, copy=True)
356
+ tm.assert_index_equal(new_index, index, exact=True)
357
+ val = int(arr[0]) + 3000
358
+
359
+ # this should not change index
360
+ if dtype != np.int8:
361
+ # NEP 50 won't allow assignment that would overflow
362
+ arr[0] = val
363
+ assert new_index[0] != val
364
+
365
+ if dtype == np.int64:
366
+ # pass list, coerce fine
367
+ index = index_cls([-5, 0, 1, 2], dtype=dtype)
368
+ expected = Index([-5, 0, 1, 2], dtype=dtype)
369
+ tm.assert_index_equal(index, expected)
370
+
371
+ # from iterable
372
+ index = index_cls(iter([-5, 0, 1, 2]), dtype=dtype)
373
+ expected = index_cls([-5, 0, 1, 2], dtype=dtype)
374
+ tm.assert_index_equal(index, expected, exact=True)
375
+
376
+ # interpret list-like
377
+ expected = index_cls([5, 0], dtype=dtype)
378
+ for cls in [Index, index_cls]:
379
+ for idx in [
380
+ cls([5, 0], dtype=dtype),
381
+ cls(np.array([5, 0]), dtype=dtype),
382
+ cls(Series([5, 0]), dtype=dtype),
383
+ ]:
384
+ tm.assert_index_equal(idx, expected)
385
+
386
+ def test_constructor_corner(self, dtype):
387
+ index_cls = Index
388
+
389
+ arr = np.array([1, 2, 3, 4], dtype=object)
390
+
391
+ index = index_cls(arr, dtype=dtype)
392
+ assert index.values.dtype == index.dtype
393
+ if dtype == np.int64:
394
+ without_dtype = Index(arr)
395
+ # as of 2.0 we do not infer a dtype when we get an object-dtype
396
+ # ndarray of numbers, matching Series behavior
397
+ assert without_dtype.dtype == object
398
+
399
+ tm.assert_index_equal(index, without_dtype.astype(np.int64))
400
+
401
+ # preventing casting
402
+ arr = np.array([1, "2", 3, "4"], dtype=object)
403
+ msg = "Trying to coerce float values to integers"
404
+ with pytest.raises(ValueError, match=msg):
405
+ index_cls(arr, dtype=dtype)
406
+
407
+ def test_constructor_coercion_signed_to_unsigned(
408
+ self,
409
+ any_unsigned_int_numpy_dtype,
410
+ ):
411
+ # see gh-15832
412
+ msg = "|".join(
413
+ [
414
+ "Trying to coerce negative values to unsigned integers",
415
+ "The elements provided in the data cannot all be casted",
416
+ ]
417
+ )
418
+ with pytest.raises(OverflowError, match=msg):
419
+ Index([-1], dtype=any_unsigned_int_numpy_dtype)
420
+
421
+ def test_constructor_np_signed(self, any_signed_int_numpy_dtype):
422
+ # GH#47475
423
+ scalar = np.dtype(any_signed_int_numpy_dtype).type(1)
424
+ result = Index([scalar])
425
+ expected = Index([1], dtype=any_signed_int_numpy_dtype)
426
+ tm.assert_index_equal(result, expected, exact=True)
427
+
428
+ def test_constructor_np_unsigned(self, any_unsigned_int_numpy_dtype):
429
+ # GH#47475
430
+ scalar = np.dtype(any_unsigned_int_numpy_dtype).type(1)
431
+ result = Index([scalar])
432
+ expected = Index([1], dtype=any_unsigned_int_numpy_dtype)
433
+ tm.assert_index_equal(result, expected, exact=True)
434
+
435
+ def test_coerce_list(self):
436
+ # coerce things
437
+ arr = Index([1, 2, 3, 4])
438
+ assert isinstance(arr, Index)
439
+
440
+ # but not if explicit dtype passed
441
+ arr = Index([1, 2, 3, 4], dtype=object)
442
+ assert type(arr) is Index
443
+
444
+
445
+ class TestFloat16Index:
446
+ # float 16 indexes not supported
447
+ # GH 49535
448
+ def test_constructor(self):
449
+ index_cls = Index
450
+ dtype = np.float16
451
+
452
+ msg = "float16 indexes are not supported"
453
+
454
+ # explicit construction
455
+ with pytest.raises(NotImplementedError, match=msg):
456
+ index_cls([1, 2, 3, 4, 5], dtype=dtype)
457
+
458
+ with pytest.raises(NotImplementedError, match=msg):
459
+ index_cls(np.array([1, 2, 3, 4, 5]), dtype=dtype)
460
+
461
+ with pytest.raises(NotImplementedError, match=msg):
462
+ index_cls([1.0, 2, 3, 4, 5], dtype=dtype)
463
+
464
+ with pytest.raises(NotImplementedError, match=msg):
465
+ index_cls(np.array([1.0, 2, 3, 4, 5]), dtype=dtype)
466
+
467
+ with pytest.raises(NotImplementedError, match=msg):
468
+ index_cls([1.0, 2, 3, 4, 5], dtype=dtype)
469
+
470
+ with pytest.raises(NotImplementedError, match=msg):
471
+ index_cls(np.array([1.0, 2, 3, 4, 5]), dtype=dtype)
472
+
473
+ # nan handling
474
+ with pytest.raises(NotImplementedError, match=msg):
475
+ index_cls([np.nan, np.nan], dtype=dtype)
476
+
477
+ with pytest.raises(NotImplementedError, match=msg):
478
+ index_cls(np.array([np.nan]), dtype=dtype)
479
+
480
+
481
+ @pytest.mark.parametrize(
482
+ "box",
483
+ [list, lambda x: np.array(x, dtype=object), lambda x: Index(x, dtype=object)],
484
+ )
485
+ def test_uint_index_does_not_convert_to_float64(box):
486
+ # https://github.com/pandas-dev/pandas/issues/28279
487
+ # https://github.com/pandas-dev/pandas/issues/28023
488
+ series = Series(
489
+ [0, 1, 2, 3, 4, 5],
490
+ index=[
491
+ 7606741985629028552,
492
+ 17876870360202815256,
493
+ 17876870360202815256,
494
+ 13106359306506049338,
495
+ 8991270399732411471,
496
+ 8991270399732411472,
497
+ ],
498
+ )
499
+
500
+ result = series.loc[box([7606741985629028552, 17876870360202815256])]
501
+
502
+ expected = Index(
503
+ [7606741985629028552, 17876870360202815256, 17876870360202815256],
504
+ dtype="uint64",
505
+ )
506
+ tm.assert_index_equal(result.index, expected)
507
+
508
+ tm.assert_equal(result, series.iloc[:3])
509
+
510
+
511
+ def test_float64_index_equals():
512
+ # https://github.com/pandas-dev/pandas/issues/35217
513
+ float_index = Index([1.0, 2, 3])
514
+ string_index = Index(["1", "2", "3"])
515
+
516
+ result = float_index.equals(string_index)
517
+ assert result is False
518
+
519
+ result = string_index.equals(float_index)
520
+ assert result is False
521
+
522
+
523
+ def test_map_dtype_inference_unsigned_to_signed():
524
+ # GH#44609 cases where we don't retain dtype
525
+ idx = Index([1, 2, 3], dtype=np.uint64)
526
+ result = idx.map(lambda x: -x)
527
+ expected = Index([-1, -2, -3], dtype=np.int64)
528
+ tm.assert_index_equal(result, expected)
529
+
530
+
531
+ def test_map_dtype_inference_overflows():
532
+ # GH#44609 case where we have to upcast
533
+ idx = Index(np.array([1, 2, 3], dtype=np.int8))
534
+ result = idx.map(lambda x: x * 1000)
535
+ # TODO: we could plausibly try to infer down to int16 here
536
+ expected = Index([1000, 2000, 3000], dtype=np.int64)
537
+ tm.assert_index_equal(result, expected)
538
+
539
+
540
+ def test_view_to_datetimelike():
541
+ # GH#55710
542
+ idx = Index([1, 2, 3])
543
+ res = idx.view("m8[s]")
544
+ expected = pd.TimedeltaIndex(idx.values.view("m8[s]"))
545
+ tm.assert_index_equal(res, expected)
546
+
547
+ res2 = idx.view("m8[D]")
548
+ expected2 = idx.values.view("m8[D]")
549
+ tm.assert_numpy_array_equal(res2, expected2)
550
+
551
+ res3 = idx.view("M8[h]")
552
+ expected3 = idx.values.view("M8[h]")
553
+ tm.assert_numpy_array_equal(res3, expected3)
venv/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)
venv/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
venv/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
venv/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)
venv/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()
venv/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)
venv/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")
venv/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))
venv/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)
venv/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)
venv/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)
venv/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)
venv/lib/python3.10/site-packages/pandas/tests/reshape/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/pandas/tests/reshape/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (188 Bytes). View file
 
venv/lib/python3.10/site-packages/pandas/tests/reshape/__pycache__/test_crosstab.cpython-310.pyc ADDED
Binary file (23 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/reshape/__pycache__/test_cut.cpython-310.pyc ADDED
Binary file (22.5 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/reshape/__pycache__/test_from_dummies.cpython-310.pyc ADDED
Binary file (11.2 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/reshape/__pycache__/test_get_dummies.cpython-310.pyc ADDED
Binary file (20.9 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/reshape/__pycache__/test_melt.cpython-310.pyc ADDED
Binary file (29.1 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/reshape/__pycache__/test_pivot.cpython-310.pyc ADDED
Binary file (63.1 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/reshape/__pycache__/test_pivot_multilevel.cpython-310.pyc ADDED
Binary file (4.56 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/reshape/__pycache__/test_qcut.cpython-310.pyc ADDED
Binary file (8.4 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/reshape/__pycache__/test_union_categoricals.cpython-310.pyc ADDED
Binary file (11.1 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/reshape/__pycache__/test_util.cpython-310.pyc ADDED
Binary file (3.83 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (195 Bytes). View file
 
venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/__pycache__/conftest.cpython-310.pyc ADDED
Binary file (417 Bytes). View file
 
venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/__pycache__/test_append.cpython-310.pyc ADDED
Binary file (11 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/__pycache__/test_append_common.cpython-310.pyc ADDED
Binary file (16.7 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/__pycache__/test_categorical.cpython-310.pyc ADDED
Binary file (7.82 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/__pycache__/test_concat.cpython-310.pyc ADDED
Binary file (27.8 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/__pycache__/test_dataframe.cpython-310.pyc ADDED
Binary file (7.5 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/__pycache__/test_datetimes.cpython-310.pyc ADDED
Binary file (17.2 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/__pycache__/test_empty.cpython-310.pyc ADDED
Binary file (8.99 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/__pycache__/test_index.cpython-310.pyc ADDED
Binary file (14.3 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/__pycache__/test_invalid.cpython-310.pyc ADDED
Binary file (2.47 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/__pycache__/test_series.cpython-310.pyc ADDED
Binary file (6.14 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/__pycache__/test_sort.cpython-310.pyc ADDED
Binary file (4.44 kB). View file
 
venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/conftest.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+
4
+ @pytest.fixture(params=[True, False])
5
+ def sort(request):
6
+ """Boolean sort keyword for concat and DataFrame.append."""
7
+ return request.param
venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/test_append.py ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime as dt
2
+ from itertools import combinations
3
+
4
+ import dateutil
5
+ import numpy as np
6
+ import pytest
7
+
8
+ import pandas as pd
9
+ from pandas import (
10
+ DataFrame,
11
+ Index,
12
+ Series,
13
+ Timestamp,
14
+ concat,
15
+ isna,
16
+ )
17
+ import pandas._testing as tm
18
+
19
+
20
+ class TestAppend:
21
+ def test_append(self, sort, float_frame):
22
+ mixed_frame = float_frame.copy()
23
+ mixed_frame["foo"] = "bar"
24
+
25
+ begin_index = float_frame.index[:5]
26
+ end_index = float_frame.index[5:]
27
+
28
+ begin_frame = float_frame.reindex(begin_index)
29
+ end_frame = float_frame.reindex(end_index)
30
+
31
+ appended = begin_frame._append(end_frame)
32
+ tm.assert_almost_equal(appended["A"], float_frame["A"])
33
+
34
+ del end_frame["A"]
35
+ partial_appended = begin_frame._append(end_frame, sort=sort)
36
+ assert "A" in partial_appended
37
+
38
+ partial_appended = end_frame._append(begin_frame, sort=sort)
39
+ assert "A" in partial_appended
40
+
41
+ # mixed type handling
42
+ appended = mixed_frame[:5]._append(mixed_frame[5:])
43
+ tm.assert_frame_equal(appended, mixed_frame)
44
+
45
+ # what to test here
46
+ mixed_appended = mixed_frame[:5]._append(float_frame[5:], sort=sort)
47
+ mixed_appended2 = float_frame[:5]._append(mixed_frame[5:], sort=sort)
48
+
49
+ # all equal except 'foo' column
50
+ tm.assert_frame_equal(
51
+ mixed_appended.reindex(columns=["A", "B", "C", "D"]),
52
+ mixed_appended2.reindex(columns=["A", "B", "C", "D"]),
53
+ )
54
+
55
+ def test_append_empty(self, float_frame):
56
+ empty = DataFrame()
57
+
58
+ appended = float_frame._append(empty)
59
+ tm.assert_frame_equal(float_frame, appended)
60
+ assert appended is not float_frame
61
+
62
+ appended = empty._append(float_frame)
63
+ tm.assert_frame_equal(float_frame, appended)
64
+ assert appended is not float_frame
65
+
66
+ def test_append_overlap_raises(self, float_frame):
67
+ msg = "Indexes have overlapping values"
68
+ with pytest.raises(ValueError, match=msg):
69
+ float_frame._append(float_frame, verify_integrity=True)
70
+
71
+ def test_append_new_columns(self):
72
+ # see gh-6129: new columns
73
+ df = DataFrame({"a": {"x": 1, "y": 2}, "b": {"x": 3, "y": 4}})
74
+ row = Series([5, 6, 7], index=["a", "b", "c"], name="z")
75
+ expected = DataFrame(
76
+ {
77
+ "a": {"x": 1, "y": 2, "z": 5},
78
+ "b": {"x": 3, "y": 4, "z": 6},
79
+ "c": {"z": 7},
80
+ }
81
+ )
82
+ result = df._append(row)
83
+ tm.assert_frame_equal(result, expected)
84
+
85
+ def test_append_length0_frame(self, sort):
86
+ df = DataFrame(columns=["A", "B", "C"])
87
+ df3 = DataFrame(index=[0, 1], columns=["A", "B"])
88
+ df5 = df._append(df3, sort=sort)
89
+
90
+ expected = DataFrame(index=[0, 1], columns=["A", "B", "C"])
91
+ tm.assert_frame_equal(df5, expected)
92
+
93
+ def test_append_records(self):
94
+ arr1 = np.zeros((2,), dtype=("i4,f4,S10"))
95
+ arr1[:] = [(1, 2.0, "Hello"), (2, 3.0, "World")]
96
+
97
+ arr2 = np.zeros((3,), dtype=("i4,f4,S10"))
98
+ arr2[:] = [(3, 4.0, "foo"), (5, 6.0, "bar"), (7.0, 8.0, "baz")]
99
+
100
+ df1 = DataFrame(arr1)
101
+ df2 = DataFrame(arr2)
102
+
103
+ result = df1._append(df2, ignore_index=True)
104
+ expected = DataFrame(np.concatenate((arr1, arr2)))
105
+ tm.assert_frame_equal(result, expected)
106
+
107
+ # rewrite sort fixture, since we also want to test default of None
108
+ def test_append_sorts(self, sort):
109
+ df1 = DataFrame({"a": [1, 2], "b": [1, 2]}, columns=["b", "a"])
110
+ df2 = DataFrame({"a": [1, 2], "c": [3, 4]}, index=[2, 3])
111
+
112
+ result = df1._append(df2, sort=sort)
113
+
114
+ # for None / True
115
+ expected = DataFrame(
116
+ {"b": [1, 2, None, None], "a": [1, 2, 1, 2], "c": [None, None, 3, 4]},
117
+ columns=["a", "b", "c"],
118
+ )
119
+ if sort is False:
120
+ expected = expected[["b", "a", "c"]]
121
+ tm.assert_frame_equal(result, expected)
122
+
123
+ def test_append_different_columns(self, sort):
124
+ df = DataFrame(
125
+ {
126
+ "bools": np.random.default_rng(2).standard_normal(10) > 0,
127
+ "ints": np.random.default_rng(2).integers(0, 10, 10),
128
+ "floats": np.random.default_rng(2).standard_normal(10),
129
+ "strings": ["foo", "bar"] * 5,
130
+ }
131
+ )
132
+
133
+ a = df[:5].loc[:, ["bools", "ints", "floats"]]
134
+ b = df[5:].loc[:, ["strings", "ints", "floats"]]
135
+
136
+ appended = a._append(b, sort=sort)
137
+ assert isna(appended["strings"][0:4]).all()
138
+ assert isna(appended["bools"][5:]).all()
139
+
140
+ def test_append_many(self, sort, float_frame):
141
+ chunks = [
142
+ float_frame[:5],
143
+ float_frame[5:10],
144
+ float_frame[10:15],
145
+ float_frame[15:],
146
+ ]
147
+
148
+ result = chunks[0]._append(chunks[1:])
149
+ tm.assert_frame_equal(result, float_frame)
150
+
151
+ chunks[-1] = chunks[-1].copy()
152
+ chunks[-1]["foo"] = "bar"
153
+ result = chunks[0]._append(chunks[1:], sort=sort)
154
+ tm.assert_frame_equal(result.loc[:, float_frame.columns], float_frame)
155
+ assert (result["foo"][15:] == "bar").all()
156
+ assert result["foo"][:15].isna().all()
157
+
158
+ def test_append_preserve_index_name(self):
159
+ # #980
160
+ df1 = DataFrame(columns=["A", "B", "C"])
161
+ df1 = df1.set_index(["A"])
162
+ df2 = DataFrame(data=[[1, 4, 7], [2, 5, 8], [3, 6, 9]], columns=["A", "B", "C"])
163
+ df2 = df2.set_index(["A"])
164
+
165
+ msg = "The behavior of array concatenation with empty entries is deprecated"
166
+ with tm.assert_produces_warning(FutureWarning, match=msg):
167
+ result = df1._append(df2)
168
+ assert result.index.name == "A"
169
+
170
+ indexes_can_append = [
171
+ pd.RangeIndex(3),
172
+ Index([4, 5, 6]),
173
+ Index([4.5, 5.5, 6.5]),
174
+ Index(list("abc")),
175
+ pd.CategoricalIndex("A B C".split()),
176
+ pd.CategoricalIndex("D E F".split(), ordered=True),
177
+ pd.IntervalIndex.from_breaks([7, 8, 9, 10]),
178
+ pd.DatetimeIndex(
179
+ [
180
+ dt.datetime(2013, 1, 3, 0, 0),
181
+ dt.datetime(2013, 1, 3, 6, 10),
182
+ dt.datetime(2013, 1, 3, 7, 12),
183
+ ]
184
+ ),
185
+ pd.MultiIndex.from_arrays(["A B C".split(), "D E F".split()]),
186
+ ]
187
+
188
+ @pytest.mark.parametrize(
189
+ "index", indexes_can_append, ids=lambda x: type(x).__name__
190
+ )
191
+ def test_append_same_columns_type(self, index):
192
+ # GH18359
193
+
194
+ # df wider than ser
195
+ df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=index)
196
+ ser_index = index[:2]
197
+ ser = Series([7, 8], index=ser_index, name=2)
198
+ result = df._append(ser)
199
+ expected = DataFrame(
200
+ [[1, 2, 3.0], [4, 5, 6], [7, 8, np.nan]], index=[0, 1, 2], columns=index
201
+ )
202
+ # integer dtype is preserved for columns present in ser.index
203
+ assert expected.dtypes.iloc[0].kind == "i"
204
+ assert expected.dtypes.iloc[1].kind == "i"
205
+
206
+ tm.assert_frame_equal(result, expected)
207
+
208
+ # ser wider than df
209
+ ser_index = index
210
+ index = index[:2]
211
+ df = DataFrame([[1, 2], [4, 5]], columns=index)
212
+ ser = Series([7, 8, 9], index=ser_index, name=2)
213
+ result = df._append(ser)
214
+ expected = DataFrame(
215
+ [[1, 2, np.nan], [4, 5, np.nan], [7, 8, 9]],
216
+ index=[0, 1, 2],
217
+ columns=ser_index,
218
+ )
219
+ tm.assert_frame_equal(result, expected)
220
+
221
+ @pytest.mark.parametrize(
222
+ "df_columns, series_index",
223
+ combinations(indexes_can_append, r=2),
224
+ ids=lambda x: type(x).__name__,
225
+ )
226
+ def test_append_different_columns_types(self, df_columns, series_index):
227
+ # GH18359
228
+ # See also test 'test_append_different_columns_types_raises' below
229
+ # for errors raised when appending
230
+
231
+ df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=df_columns)
232
+ ser = Series([7, 8, 9], index=series_index, name=2)
233
+
234
+ result = df._append(ser)
235
+ idx_diff = ser.index.difference(df_columns)
236
+ combined_columns = Index(df_columns.tolist()).append(idx_diff)
237
+ expected = DataFrame(
238
+ [
239
+ [1.0, 2.0, 3.0, np.nan, np.nan, np.nan],
240
+ [4, 5, 6, np.nan, np.nan, np.nan],
241
+ [np.nan, np.nan, np.nan, 7, 8, 9],
242
+ ],
243
+ index=[0, 1, 2],
244
+ columns=combined_columns,
245
+ )
246
+ tm.assert_frame_equal(result, expected)
247
+
248
+ def test_append_dtype_coerce(self, sort):
249
+ # GH 4993
250
+ # appending with datetime will incorrectly convert datetime64
251
+
252
+ df1 = DataFrame(
253
+ index=[1, 2],
254
+ data=[dt.datetime(2013, 1, 1, 0, 0), dt.datetime(2013, 1, 2, 0, 0)],
255
+ columns=["start_time"],
256
+ )
257
+ df2 = DataFrame(
258
+ index=[4, 5],
259
+ data=[
260
+ [dt.datetime(2013, 1, 3, 0, 0), dt.datetime(2013, 1, 3, 6, 10)],
261
+ [dt.datetime(2013, 1, 4, 0, 0), dt.datetime(2013, 1, 4, 7, 10)],
262
+ ],
263
+ columns=["start_time", "end_time"],
264
+ )
265
+
266
+ expected = concat(
267
+ [
268
+ Series(
269
+ [
270
+ pd.NaT,
271
+ pd.NaT,
272
+ dt.datetime(2013, 1, 3, 6, 10),
273
+ dt.datetime(2013, 1, 4, 7, 10),
274
+ ],
275
+ name="end_time",
276
+ ),
277
+ Series(
278
+ [
279
+ dt.datetime(2013, 1, 1, 0, 0),
280
+ dt.datetime(2013, 1, 2, 0, 0),
281
+ dt.datetime(2013, 1, 3, 0, 0),
282
+ dt.datetime(2013, 1, 4, 0, 0),
283
+ ],
284
+ name="start_time",
285
+ ),
286
+ ],
287
+ axis=1,
288
+ sort=sort,
289
+ )
290
+ result = df1._append(df2, ignore_index=True, sort=sort)
291
+ if sort:
292
+ expected = expected[["end_time", "start_time"]]
293
+ else:
294
+ expected = expected[["start_time", "end_time"]]
295
+
296
+ tm.assert_frame_equal(result, expected)
297
+
298
+ def test_append_missing_column_proper_upcast(self, sort):
299
+ df1 = DataFrame({"A": np.array([1, 2, 3, 4], dtype="i8")})
300
+ df2 = DataFrame({"B": np.array([True, False, True, False], dtype=bool)})
301
+
302
+ appended = df1._append(df2, ignore_index=True, sort=sort)
303
+ assert appended["A"].dtype == "f8"
304
+ assert appended["B"].dtype == "O"
305
+
306
+ def test_append_empty_frame_to_series_with_dateutil_tz(self):
307
+ # GH 23682
308
+ date = Timestamp("2018-10-24 07:30:00", tz=dateutil.tz.tzutc())
309
+ ser = Series({"a": 1.0, "b": 2.0, "date": date})
310
+ df = DataFrame(columns=["c", "d"])
311
+ result_a = df._append(ser, ignore_index=True)
312
+ expected = DataFrame(
313
+ [[np.nan, np.nan, 1.0, 2.0, date]], columns=["c", "d", "a", "b", "date"]
314
+ )
315
+ # These columns get cast to object after append
316
+ expected["c"] = expected["c"].astype(object)
317
+ expected["d"] = expected["d"].astype(object)
318
+ tm.assert_frame_equal(result_a, expected)
319
+
320
+ expected = DataFrame(
321
+ [[np.nan, np.nan, 1.0, 2.0, date]] * 2, columns=["c", "d", "a", "b", "date"]
322
+ )
323
+ expected["c"] = expected["c"].astype(object)
324
+ expected["d"] = expected["d"].astype(object)
325
+ result_b = result_a._append(ser, ignore_index=True)
326
+ tm.assert_frame_equal(result_b, expected)
327
+
328
+ result = df._append([ser, ser], ignore_index=True)
329
+ tm.assert_frame_equal(result, expected)
330
+
331
+ def test_append_empty_tz_frame_with_datetime64ns(self, using_array_manager):
332
+ # https://github.com/pandas-dev/pandas/issues/35460
333
+ df = DataFrame(columns=["a"]).astype("datetime64[ns, UTC]")
334
+
335
+ # pd.NaT gets inferred as tz-naive, so append result is tz-naive
336
+ result = df._append({"a": pd.NaT}, ignore_index=True)
337
+ if using_array_manager:
338
+ expected = DataFrame({"a": [pd.NaT]}, dtype=object)
339
+ else:
340
+ expected = DataFrame({"a": [np.nan]}, dtype=object)
341
+ tm.assert_frame_equal(result, expected)
342
+
343
+ # also test with typed value to append
344
+ df = DataFrame(columns=["a"]).astype("datetime64[ns, UTC]")
345
+ other = Series({"a": pd.NaT}, dtype="datetime64[ns]")
346
+ result = df._append(other, ignore_index=True)
347
+ tm.assert_frame_equal(result, expected)
348
+
349
+ # mismatched tz
350
+ other = Series({"a": pd.NaT}, dtype="datetime64[ns, US/Pacific]")
351
+ result = df._append(other, ignore_index=True)
352
+ expected = DataFrame({"a": [pd.NaT]}).astype(object)
353
+ tm.assert_frame_equal(result, expected)
354
+
355
+ @pytest.mark.parametrize(
356
+ "dtype_str", ["datetime64[ns, UTC]", "datetime64[ns]", "Int64", "int64"]
357
+ )
358
+ @pytest.mark.parametrize("val", [1, "NaT"])
359
+ def test_append_empty_frame_with_timedelta64ns_nat(
360
+ self, dtype_str, val, using_array_manager
361
+ ):
362
+ # https://github.com/pandas-dev/pandas/issues/35460
363
+ df = DataFrame(columns=["a"]).astype(dtype_str)
364
+
365
+ other = DataFrame({"a": [np.timedelta64(val, "ns")]})
366
+ result = df._append(other, ignore_index=True)
367
+
368
+ expected = other.astype(object)
369
+ if isinstance(val, str) and dtype_str != "int64" and not using_array_manager:
370
+ # TODO: expected used to be `other.astype(object)` which is a more
371
+ # reasonable result. This was changed when tightening
372
+ # assert_frame_equal's treatment of mismatched NAs to match the
373
+ # existing behavior.
374
+ expected = DataFrame({"a": [np.nan]}, dtype=object)
375
+ tm.assert_frame_equal(result, expected)
376
+
377
+ @pytest.mark.parametrize(
378
+ "dtype_str", ["datetime64[ns, UTC]", "datetime64[ns]", "Int64", "int64"]
379
+ )
380
+ @pytest.mark.parametrize("val", [1, "NaT"])
381
+ def test_append_frame_with_timedelta64ns_nat(self, dtype_str, val):
382
+ # https://github.com/pandas-dev/pandas/issues/35460
383
+ df = DataFrame({"a": pd.array([1], dtype=dtype_str)})
384
+
385
+ other = DataFrame({"a": [np.timedelta64(val, "ns")]})
386
+ result = df._append(other, ignore_index=True)
387
+
388
+ expected = DataFrame({"a": [df.iloc[0, 0], other.iloc[0, 0]]}, dtype=object)
389
+ tm.assert_frame_equal(result, expected)
venv/lib/python3.10/site-packages/pandas/tests/reshape/concat/test_append_common.py ADDED
@@ -0,0 +1,753 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ import pandas as pd
5
+ from pandas import (
6
+ Categorical,
7
+ DataFrame,
8
+ Index,
9
+ Series,
10
+ )
11
+ import pandas._testing as tm
12
+
13
+
14
+ @pytest.fixture(
15
+ params=list(
16
+ {
17
+ "bool": [True, False, True],
18
+ "int64": [1, 2, 3],
19
+ "float64": [1.1, np.nan, 3.3],
20
+ "category": Categorical(["X", "Y", "Z"]),
21
+ "object": ["a", "b", "c"],
22
+ "datetime64[ns]": [
23
+ pd.Timestamp("2011-01-01"),
24
+ pd.Timestamp("2011-01-02"),
25
+ pd.Timestamp("2011-01-03"),
26
+ ],
27
+ "datetime64[ns, US/Eastern]": [
28
+ pd.Timestamp("2011-01-01", tz="US/Eastern"),
29
+ pd.Timestamp("2011-01-02", tz="US/Eastern"),
30
+ pd.Timestamp("2011-01-03", tz="US/Eastern"),
31
+ ],
32
+ "timedelta64[ns]": [
33
+ pd.Timedelta("1 days"),
34
+ pd.Timedelta("2 days"),
35
+ pd.Timedelta("3 days"),
36
+ ],
37
+ "period[M]": [
38
+ pd.Period("2011-01", freq="M"),
39
+ pd.Period("2011-02", freq="M"),
40
+ pd.Period("2011-03", freq="M"),
41
+ ],
42
+ }.items()
43
+ )
44
+ )
45
+ def item(request):
46
+ key, data = request.param
47
+ return key, data
48
+
49
+
50
+ @pytest.fixture
51
+ def item2(item):
52
+ return item
53
+
54
+
55
+ class TestConcatAppendCommon:
56
+ """
57
+ Test common dtype coercion rules between concat and append.
58
+ """
59
+
60
+ def test_dtypes(self, item, index_or_series, using_infer_string):
61
+ # to confirm test case covers intended dtypes
62
+ typ, vals = item
63
+ obj = index_or_series(vals)
64
+ if typ == "object" and using_infer_string:
65
+ typ = "string"
66
+ if isinstance(obj, Index):
67
+ assert obj.dtype == typ
68
+ elif isinstance(obj, Series):
69
+ if typ.startswith("period"):
70
+ assert obj.dtype == "Period[M]"
71
+ else:
72
+ assert obj.dtype == typ
73
+
74
+ def test_concatlike_same_dtypes(self, item):
75
+ # GH 13660
76
+ typ1, vals1 = item
77
+
78
+ vals2 = vals1
79
+ vals3 = vals1
80
+
81
+ if typ1 == "category":
82
+ exp_data = Categorical(list(vals1) + list(vals2))
83
+ exp_data3 = Categorical(list(vals1) + list(vals2) + list(vals3))
84
+ else:
85
+ exp_data = vals1 + vals2
86
+ exp_data3 = vals1 + vals2 + vals3
87
+
88
+ # ----- Index ----- #
89
+
90
+ # index.append
91
+ res = Index(vals1).append(Index(vals2))
92
+ exp = Index(exp_data)
93
+ tm.assert_index_equal(res, exp)
94
+
95
+ # 3 elements
96
+ res = Index(vals1).append([Index(vals2), Index(vals3)])
97
+ exp = Index(exp_data3)
98
+ tm.assert_index_equal(res, exp)
99
+
100
+ # index.append name mismatch
101
+ i1 = Index(vals1, name="x")
102
+ i2 = Index(vals2, name="y")
103
+ res = i1.append(i2)
104
+ exp = Index(exp_data)
105
+ tm.assert_index_equal(res, exp)
106
+
107
+ # index.append name match
108
+ i1 = Index(vals1, name="x")
109
+ i2 = Index(vals2, name="x")
110
+ res = i1.append(i2)
111
+ exp = Index(exp_data, name="x")
112
+ tm.assert_index_equal(res, exp)
113
+
114
+ # cannot append non-index
115
+ with pytest.raises(TypeError, match="all inputs must be Index"):
116
+ Index(vals1).append(vals2)
117
+
118
+ with pytest.raises(TypeError, match="all inputs must be Index"):
119
+ Index(vals1).append([Index(vals2), vals3])
120
+
121
+ # ----- Series ----- #
122
+
123
+ # series.append
124
+ res = Series(vals1)._append(Series(vals2), ignore_index=True)
125
+ exp = Series(exp_data)
126
+ tm.assert_series_equal(res, exp, check_index_type=True)
127
+
128
+ # concat
129
+ res = pd.concat([Series(vals1), Series(vals2)], ignore_index=True)
130
+ tm.assert_series_equal(res, exp, check_index_type=True)
131
+
132
+ # 3 elements
133
+ res = Series(vals1)._append([Series(vals2), Series(vals3)], ignore_index=True)
134
+ exp = Series(exp_data3)
135
+ tm.assert_series_equal(res, exp)
136
+
137
+ res = pd.concat(
138
+ [Series(vals1), Series(vals2), Series(vals3)],
139
+ ignore_index=True,
140
+ )
141
+ tm.assert_series_equal(res, exp)
142
+
143
+ # name mismatch
144
+ s1 = Series(vals1, name="x")
145
+ s2 = Series(vals2, name="y")
146
+ res = s1._append(s2, ignore_index=True)
147
+ exp = Series(exp_data)
148
+ tm.assert_series_equal(res, exp, check_index_type=True)
149
+
150
+ res = pd.concat([s1, s2], ignore_index=True)
151
+ tm.assert_series_equal(res, exp, check_index_type=True)
152
+
153
+ # name match
154
+ s1 = Series(vals1, name="x")
155
+ s2 = Series(vals2, name="x")
156
+ res = s1._append(s2, ignore_index=True)
157
+ exp = Series(exp_data, name="x")
158
+ tm.assert_series_equal(res, exp, check_index_type=True)
159
+
160
+ res = pd.concat([s1, s2], ignore_index=True)
161
+ tm.assert_series_equal(res, exp, check_index_type=True)
162
+
163
+ # cannot append non-index
164
+ msg = (
165
+ r"cannot concatenate object of type '.+'; "
166
+ "only Series and DataFrame objs are valid"
167
+ )
168
+ with pytest.raises(TypeError, match=msg):
169
+ Series(vals1)._append(vals2)
170
+
171
+ with pytest.raises(TypeError, match=msg):
172
+ Series(vals1)._append([Series(vals2), vals3])
173
+
174
+ with pytest.raises(TypeError, match=msg):
175
+ pd.concat([Series(vals1), vals2])
176
+
177
+ with pytest.raises(TypeError, match=msg):
178
+ pd.concat([Series(vals1), Series(vals2), vals3])
179
+
180
+ def test_concatlike_dtypes_coercion(self, item, item2, request):
181
+ # GH 13660
182
+ typ1, vals1 = item
183
+ typ2, vals2 = item2
184
+
185
+ vals3 = vals2
186
+
187
+ # basically infer
188
+ exp_index_dtype = None
189
+ exp_series_dtype = None
190
+
191
+ if typ1 == typ2:
192
+ pytest.skip("same dtype is tested in test_concatlike_same_dtypes")
193
+ elif typ1 == "category" or typ2 == "category":
194
+ pytest.skip("categorical type tested elsewhere")
195
+
196
+ # specify expected dtype
197
+ if typ1 == "bool" and typ2 in ("int64", "float64"):
198
+ # series coerces to numeric based on numpy rule
199
+ # index doesn't because bool is object dtype
200
+ exp_series_dtype = typ2
201
+ mark = pytest.mark.xfail(reason="GH#39187 casting to object")
202
+ request.applymarker(mark)
203
+ elif typ2 == "bool" and typ1 in ("int64", "float64"):
204
+ exp_series_dtype = typ1
205
+ mark = pytest.mark.xfail(reason="GH#39187 casting to object")
206
+ request.applymarker(mark)
207
+ elif typ1 in {"datetime64[ns, US/Eastern]", "timedelta64[ns]"} or typ2 in {
208
+ "datetime64[ns, US/Eastern]",
209
+ "timedelta64[ns]",
210
+ }:
211
+ exp_index_dtype = object
212
+ exp_series_dtype = object
213
+
214
+ exp_data = vals1 + vals2
215
+ exp_data3 = vals1 + vals2 + vals3
216
+
217
+ # ----- Index ----- #
218
+
219
+ # index.append
220
+ # GH#39817
221
+ res = Index(vals1).append(Index(vals2))
222
+ exp = Index(exp_data, dtype=exp_index_dtype)
223
+ tm.assert_index_equal(res, exp)
224
+
225
+ # 3 elements
226
+ res = Index(vals1).append([Index(vals2), Index(vals3)])
227
+ exp = Index(exp_data3, dtype=exp_index_dtype)
228
+ tm.assert_index_equal(res, exp)
229
+
230
+ # ----- Series ----- #
231
+
232
+ # series._append
233
+ # GH#39817
234
+ res = Series(vals1)._append(Series(vals2), ignore_index=True)
235
+ exp = Series(exp_data, dtype=exp_series_dtype)
236
+ tm.assert_series_equal(res, exp, check_index_type=True)
237
+
238
+ # concat
239
+ # GH#39817
240
+ res = pd.concat([Series(vals1), Series(vals2)], ignore_index=True)
241
+ tm.assert_series_equal(res, exp, check_index_type=True)
242
+
243
+ # 3 elements
244
+ # GH#39817
245
+ res = Series(vals1)._append([Series(vals2), Series(vals3)], ignore_index=True)
246
+ exp = Series(exp_data3, dtype=exp_series_dtype)
247
+ tm.assert_series_equal(res, exp)
248
+
249
+ # GH#39817
250
+ res = pd.concat(
251
+ [Series(vals1), Series(vals2), Series(vals3)],
252
+ ignore_index=True,
253
+ )
254
+ tm.assert_series_equal(res, exp)
255
+
256
+ def test_concatlike_common_coerce_to_pandas_object(self):
257
+ # GH 13626
258
+ # result must be Timestamp/Timedelta, not datetime.datetime/timedelta
259
+ dti = pd.DatetimeIndex(["2011-01-01", "2011-01-02"])
260
+ tdi = pd.TimedeltaIndex(["1 days", "2 days"])
261
+
262
+ exp = Index(
263
+ [
264
+ pd.Timestamp("2011-01-01"),
265
+ pd.Timestamp("2011-01-02"),
266
+ pd.Timedelta("1 days"),
267
+ pd.Timedelta("2 days"),
268
+ ]
269
+ )
270
+
271
+ res = dti.append(tdi)
272
+ tm.assert_index_equal(res, exp)
273
+ assert isinstance(res[0], pd.Timestamp)
274
+ assert isinstance(res[-1], pd.Timedelta)
275
+
276
+ dts = Series(dti)
277
+ tds = Series(tdi)
278
+ res = dts._append(tds)
279
+ tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
280
+ assert isinstance(res.iloc[0], pd.Timestamp)
281
+ assert isinstance(res.iloc[-1], pd.Timedelta)
282
+
283
+ res = pd.concat([dts, tds])
284
+ tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
285
+ assert isinstance(res.iloc[0], pd.Timestamp)
286
+ assert isinstance(res.iloc[-1], pd.Timedelta)
287
+
288
+ def test_concatlike_datetimetz(self, tz_aware_fixture):
289
+ tz = tz_aware_fixture
290
+ # GH 7795
291
+ dti1 = pd.DatetimeIndex(["2011-01-01", "2011-01-02"], tz=tz)
292
+ dti2 = pd.DatetimeIndex(["2012-01-01", "2012-01-02"], tz=tz)
293
+
294
+ exp = pd.DatetimeIndex(
295
+ ["2011-01-01", "2011-01-02", "2012-01-01", "2012-01-02"], tz=tz
296
+ )
297
+
298
+ res = dti1.append(dti2)
299
+ tm.assert_index_equal(res, exp)
300
+
301
+ dts1 = Series(dti1)
302
+ dts2 = Series(dti2)
303
+ res = dts1._append(dts2)
304
+ tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
305
+
306
+ res = pd.concat([dts1, dts2])
307
+ tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
308
+
309
+ @pytest.mark.parametrize("tz", ["UTC", "US/Eastern", "Asia/Tokyo", "EST5EDT"])
310
+ def test_concatlike_datetimetz_short(self, tz):
311
+ # GH#7795
312
+ ix1 = pd.date_range(start="2014-07-15", end="2014-07-17", freq="D", tz=tz)
313
+ ix2 = pd.DatetimeIndex(["2014-07-11", "2014-07-21"], tz=tz)
314
+ df1 = DataFrame(0, index=ix1, columns=["A", "B"])
315
+ df2 = DataFrame(0, index=ix2, columns=["A", "B"])
316
+
317
+ exp_idx = pd.DatetimeIndex(
318
+ ["2014-07-15", "2014-07-16", "2014-07-17", "2014-07-11", "2014-07-21"],
319
+ tz=tz,
320
+ ).as_unit("ns")
321
+ exp = DataFrame(0, index=exp_idx, columns=["A", "B"])
322
+
323
+ tm.assert_frame_equal(df1._append(df2), exp)
324
+ tm.assert_frame_equal(pd.concat([df1, df2]), exp)
325
+
326
+ def test_concatlike_datetimetz_to_object(self, tz_aware_fixture):
327
+ tz = tz_aware_fixture
328
+ # GH 13660
329
+
330
+ # different tz coerces to object
331
+ dti1 = pd.DatetimeIndex(["2011-01-01", "2011-01-02"], tz=tz)
332
+ dti2 = pd.DatetimeIndex(["2012-01-01", "2012-01-02"])
333
+
334
+ exp = Index(
335
+ [
336
+ pd.Timestamp("2011-01-01", tz=tz),
337
+ pd.Timestamp("2011-01-02", tz=tz),
338
+ pd.Timestamp("2012-01-01"),
339
+ pd.Timestamp("2012-01-02"),
340
+ ],
341
+ dtype=object,
342
+ )
343
+
344
+ res = dti1.append(dti2)
345
+ tm.assert_index_equal(res, exp)
346
+
347
+ dts1 = Series(dti1)
348
+ dts2 = Series(dti2)
349
+ res = dts1._append(dts2)
350
+ tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
351
+
352
+ res = pd.concat([dts1, dts2])
353
+ tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
354
+
355
+ # different tz
356
+ dti3 = pd.DatetimeIndex(["2012-01-01", "2012-01-02"], tz="US/Pacific")
357
+
358
+ exp = Index(
359
+ [
360
+ pd.Timestamp("2011-01-01", tz=tz),
361
+ pd.Timestamp("2011-01-02", tz=tz),
362
+ pd.Timestamp("2012-01-01", tz="US/Pacific"),
363
+ pd.Timestamp("2012-01-02", tz="US/Pacific"),
364
+ ],
365
+ dtype=object,
366
+ )
367
+
368
+ res = dti1.append(dti3)
369
+ tm.assert_index_equal(res, exp)
370
+
371
+ dts1 = Series(dti1)
372
+ dts3 = Series(dti3)
373
+ res = dts1._append(dts3)
374
+ tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
375
+
376
+ res = pd.concat([dts1, dts3])
377
+ tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
378
+
379
+ def test_concatlike_common_period(self):
380
+ # GH 13660
381
+ pi1 = pd.PeriodIndex(["2011-01", "2011-02"], freq="M")
382
+ pi2 = pd.PeriodIndex(["2012-01", "2012-02"], freq="M")
383
+
384
+ exp = pd.PeriodIndex(["2011-01", "2011-02", "2012-01", "2012-02"], freq="M")
385
+
386
+ res = pi1.append(pi2)
387
+ tm.assert_index_equal(res, exp)
388
+
389
+ ps1 = Series(pi1)
390
+ ps2 = Series(pi2)
391
+ res = ps1._append(ps2)
392
+ tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
393
+
394
+ res = pd.concat([ps1, ps2])
395
+ tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
396
+
397
+ def test_concatlike_common_period_diff_freq_to_object(self):
398
+ # GH 13221
399
+ pi1 = pd.PeriodIndex(["2011-01", "2011-02"], freq="M")
400
+ pi2 = pd.PeriodIndex(["2012-01-01", "2012-02-01"], freq="D")
401
+
402
+ exp = Index(
403
+ [
404
+ pd.Period("2011-01", freq="M"),
405
+ pd.Period("2011-02", freq="M"),
406
+ pd.Period("2012-01-01", freq="D"),
407
+ pd.Period("2012-02-01", freq="D"),
408
+ ],
409
+ dtype=object,
410
+ )
411
+
412
+ res = pi1.append(pi2)
413
+ tm.assert_index_equal(res, exp)
414
+
415
+ ps1 = Series(pi1)
416
+ ps2 = Series(pi2)
417
+ res = ps1._append(ps2)
418
+ tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
419
+
420
+ res = pd.concat([ps1, ps2])
421
+ tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
422
+
423
+ def test_concatlike_common_period_mixed_dt_to_object(self):
424
+ # GH 13221
425
+ # different datetimelike
426
+ pi1 = pd.PeriodIndex(["2011-01", "2011-02"], freq="M")
427
+ tdi = pd.TimedeltaIndex(["1 days", "2 days"])
428
+ exp = Index(
429
+ [
430
+ pd.Period("2011-01", freq="M"),
431
+ pd.Period("2011-02", freq="M"),
432
+ pd.Timedelta("1 days"),
433
+ pd.Timedelta("2 days"),
434
+ ],
435
+ dtype=object,
436
+ )
437
+
438
+ res = pi1.append(tdi)
439
+ tm.assert_index_equal(res, exp)
440
+
441
+ ps1 = Series(pi1)
442
+ tds = Series(tdi)
443
+ res = ps1._append(tds)
444
+ tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
445
+
446
+ res = pd.concat([ps1, tds])
447
+ tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
448
+
449
+ # inverse
450
+ exp = Index(
451
+ [
452
+ pd.Timedelta("1 days"),
453
+ pd.Timedelta("2 days"),
454
+ pd.Period("2011-01", freq="M"),
455
+ pd.Period("2011-02", freq="M"),
456
+ ],
457
+ dtype=object,
458
+ )
459
+
460
+ res = tdi.append(pi1)
461
+ tm.assert_index_equal(res, exp)
462
+
463
+ ps1 = Series(pi1)
464
+ tds = Series(tdi)
465
+ res = tds._append(ps1)
466
+ tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
467
+
468
+ res = pd.concat([tds, ps1])
469
+ tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1]))
470
+
471
+ def test_concat_categorical(self):
472
+ # GH 13524
473
+
474
+ # same categories -> category
475
+ s1 = Series([1, 2, np.nan], dtype="category")
476
+ s2 = Series([2, 1, 2], dtype="category")
477
+
478
+ exp = Series([1, 2, np.nan, 2, 1, 2], dtype="category")
479
+ tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp)
480
+ tm.assert_series_equal(s1._append(s2, ignore_index=True), exp)
481
+
482
+ # partially different categories => not-category
483
+ s1 = Series([3, 2], dtype="category")
484
+ s2 = Series([2, 1], dtype="category")
485
+
486
+ exp = Series([3, 2, 2, 1])
487
+ tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp)
488
+ tm.assert_series_equal(s1._append(s2, ignore_index=True), exp)
489
+
490
+ # completely different categories (same dtype) => not-category
491
+ s1 = Series([10, 11, np.nan], dtype="category")
492
+ s2 = Series([np.nan, 1, 3, 2], dtype="category")
493
+
494
+ exp = Series([10, 11, np.nan, np.nan, 1, 3, 2], dtype=np.float64)
495
+ tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp)
496
+ tm.assert_series_equal(s1._append(s2, ignore_index=True), exp)
497
+
498
+ def test_union_categorical_same_categories_different_order(self):
499
+ # https://github.com/pandas-dev/pandas/issues/19096
500
+ a = Series(Categorical(["a", "b", "c"], categories=["a", "b", "c"]))
501
+ b = Series(Categorical(["a", "b", "c"], categories=["b", "a", "c"]))
502
+ result = pd.concat([a, b], ignore_index=True)
503
+ expected = Series(
504
+ Categorical(["a", "b", "c", "a", "b", "c"], categories=["a", "b", "c"])
505
+ )
506
+ tm.assert_series_equal(result, expected)
507
+
508
+ def test_concat_categorical_coercion(self):
509
+ # GH 13524
510
+
511
+ # category + not-category => not-category
512
+ s1 = Series([1, 2, np.nan], dtype="category")
513
+ s2 = Series([2, 1, 2])
514
+
515
+ exp = Series([1, 2, np.nan, 2, 1, 2], dtype=np.float64)
516
+ tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp)
517
+ tm.assert_series_equal(s1._append(s2, ignore_index=True), exp)
518
+
519
+ # result shouldn't be affected by 1st elem dtype
520
+ exp = Series([2, 1, 2, 1, 2, np.nan], dtype=np.float64)
521
+ tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), exp)
522
+ tm.assert_series_equal(s2._append(s1, ignore_index=True), exp)
523
+
524
+ # all values are not in category => not-category
525
+ s1 = Series([3, 2], dtype="category")
526
+ s2 = Series([2, 1])
527
+
528
+ exp = Series([3, 2, 2, 1])
529
+ tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp)
530
+ tm.assert_series_equal(s1._append(s2, ignore_index=True), exp)
531
+
532
+ exp = Series([2, 1, 3, 2])
533
+ tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), exp)
534
+ tm.assert_series_equal(s2._append(s1, ignore_index=True), exp)
535
+
536
+ # completely different categories => not-category
537
+ s1 = Series([10, 11, np.nan], dtype="category")
538
+ s2 = Series([1, 3, 2])
539
+
540
+ exp = Series([10, 11, np.nan, 1, 3, 2], dtype=np.float64)
541
+ tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp)
542
+ tm.assert_series_equal(s1._append(s2, ignore_index=True), exp)
543
+
544
+ exp = Series([1, 3, 2, 10, 11, np.nan], dtype=np.float64)
545
+ tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), exp)
546
+ tm.assert_series_equal(s2._append(s1, ignore_index=True), exp)
547
+
548
+ # different dtype => not-category
549
+ s1 = Series([10, 11, np.nan], dtype="category")
550
+ s2 = Series(["a", "b", "c"])
551
+
552
+ exp = Series([10, 11, np.nan, "a", "b", "c"])
553
+ tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp)
554
+ tm.assert_series_equal(s1._append(s2, ignore_index=True), exp)
555
+
556
+ exp = Series(["a", "b", "c", 10, 11, np.nan])
557
+ tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), exp)
558
+ tm.assert_series_equal(s2._append(s1, ignore_index=True), exp)
559
+
560
+ # if normal series only contains NaN-likes => not-category
561
+ s1 = Series([10, 11], dtype="category")
562
+ s2 = Series([np.nan, np.nan, np.nan])
563
+
564
+ exp = Series([10, 11, np.nan, np.nan, np.nan])
565
+ tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp)
566
+ tm.assert_series_equal(s1._append(s2, ignore_index=True), exp)
567
+
568
+ exp = Series([np.nan, np.nan, np.nan, 10, 11])
569
+ tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), exp)
570
+ tm.assert_series_equal(s2._append(s1, ignore_index=True), exp)
571
+
572
+ def test_concat_categorical_3elem_coercion(self):
573
+ # GH 13524
574
+
575
+ # mixed dtypes => not-category
576
+ s1 = Series([1, 2, np.nan], dtype="category")
577
+ s2 = Series([2, 1, 2], dtype="category")
578
+ s3 = Series([1, 2, 1, 2, np.nan])
579
+
580
+ exp = Series([1, 2, np.nan, 2, 1, 2, 1, 2, 1, 2, np.nan], dtype="float")
581
+ tm.assert_series_equal(pd.concat([s1, s2, s3], ignore_index=True), exp)
582
+ tm.assert_series_equal(s1._append([s2, s3], ignore_index=True), exp)
583
+
584
+ exp = Series([1, 2, 1, 2, np.nan, 1, 2, np.nan, 2, 1, 2], dtype="float")
585
+ tm.assert_series_equal(pd.concat([s3, s1, s2], ignore_index=True), exp)
586
+ tm.assert_series_equal(s3._append([s1, s2], ignore_index=True), exp)
587
+
588
+ # values are all in either category => not-category
589
+ s1 = Series([4, 5, 6], dtype="category")
590
+ s2 = Series([1, 2, 3], dtype="category")
591
+ s3 = Series([1, 3, 4])
592
+
593
+ exp = Series([4, 5, 6, 1, 2, 3, 1, 3, 4])
594
+ tm.assert_series_equal(pd.concat([s1, s2, s3], ignore_index=True), exp)
595
+ tm.assert_series_equal(s1._append([s2, s3], ignore_index=True), exp)
596
+
597
+ exp = Series([1, 3, 4, 4, 5, 6, 1, 2, 3])
598
+ tm.assert_series_equal(pd.concat([s3, s1, s2], ignore_index=True), exp)
599
+ tm.assert_series_equal(s3._append([s1, s2], ignore_index=True), exp)
600
+
601
+ # values are all in either category => not-category
602
+ s1 = Series([4, 5, 6], dtype="category")
603
+ s2 = Series([1, 2, 3], dtype="category")
604
+ s3 = Series([10, 11, 12])
605
+
606
+ exp = Series([4, 5, 6, 1, 2, 3, 10, 11, 12])
607
+ tm.assert_series_equal(pd.concat([s1, s2, s3], ignore_index=True), exp)
608
+ tm.assert_series_equal(s1._append([s2, s3], ignore_index=True), exp)
609
+
610
+ exp = Series([10, 11, 12, 4, 5, 6, 1, 2, 3])
611
+ tm.assert_series_equal(pd.concat([s3, s1, s2], ignore_index=True), exp)
612
+ tm.assert_series_equal(s3._append([s1, s2], ignore_index=True), exp)
613
+
614
+ def test_concat_categorical_multi_coercion(self):
615
+ # GH 13524
616
+
617
+ s1 = Series([1, 3], dtype="category")
618
+ s2 = Series([3, 4], dtype="category")
619
+ s3 = Series([2, 3])
620
+ s4 = Series([2, 2], dtype="category")
621
+ s5 = Series([1, np.nan])
622
+ s6 = Series([1, 3, 2], dtype="category")
623
+
624
+ # mixed dtype, values are all in categories => not-category
625
+ exp = Series([1, 3, 3, 4, 2, 3, 2, 2, 1, np.nan, 1, 3, 2])
626
+ res = pd.concat([s1, s2, s3, s4, s5, s6], ignore_index=True)
627
+ tm.assert_series_equal(res, exp)
628
+ res = s1._append([s2, s3, s4, s5, s6], ignore_index=True)
629
+ tm.assert_series_equal(res, exp)
630
+
631
+ exp = Series([1, 3, 2, 1, np.nan, 2, 2, 2, 3, 3, 4, 1, 3])
632
+ res = pd.concat([s6, s5, s4, s3, s2, s1], ignore_index=True)
633
+ tm.assert_series_equal(res, exp)
634
+ res = s6._append([s5, s4, s3, s2, s1], ignore_index=True)
635
+ tm.assert_series_equal(res, exp)
636
+
637
+ def test_concat_categorical_ordered(self):
638
+ # GH 13524
639
+
640
+ s1 = Series(Categorical([1, 2, np.nan], ordered=True))
641
+ s2 = Series(Categorical([2, 1, 2], ordered=True))
642
+
643
+ exp = Series(Categorical([1, 2, np.nan, 2, 1, 2], ordered=True))
644
+ tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp)
645
+ tm.assert_series_equal(s1._append(s2, ignore_index=True), exp)
646
+
647
+ exp = Series(Categorical([1, 2, np.nan, 2, 1, 2, 1, 2, np.nan], ordered=True))
648
+ tm.assert_series_equal(pd.concat([s1, s2, s1], ignore_index=True), exp)
649
+ tm.assert_series_equal(s1._append([s2, s1], ignore_index=True), exp)
650
+
651
+ def test_concat_categorical_coercion_nan(self):
652
+ # GH 13524
653
+
654
+ # some edge cases
655
+ # category + not-category => not category
656
+ s1 = Series(np.array([np.nan, np.nan], dtype=np.float64), dtype="category")
657
+ s2 = Series([np.nan, 1])
658
+
659
+ exp = Series([np.nan, np.nan, np.nan, 1])
660
+ tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp)
661
+ tm.assert_series_equal(s1._append(s2, ignore_index=True), exp)
662
+
663
+ s1 = Series([1, np.nan], dtype="category")
664
+ s2 = Series([np.nan, np.nan])
665
+
666
+ exp = Series([1, np.nan, np.nan, np.nan], dtype="float")
667
+ tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp)
668
+ tm.assert_series_equal(s1._append(s2, ignore_index=True), exp)
669
+
670
+ # mixed dtype, all nan-likes => not-category
671
+ s1 = Series([np.nan, np.nan], dtype="category")
672
+ s2 = Series([np.nan, np.nan])
673
+
674
+ exp = Series([np.nan, np.nan, np.nan, np.nan])
675
+ tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp)
676
+ tm.assert_series_equal(s1._append(s2, ignore_index=True), exp)
677
+ tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), exp)
678
+ tm.assert_series_equal(s2._append(s1, ignore_index=True), exp)
679
+
680
+ # all category nan-likes => category
681
+ s1 = Series([np.nan, np.nan], dtype="category")
682
+ s2 = Series([np.nan, np.nan], dtype="category")
683
+
684
+ exp = Series([np.nan, np.nan, np.nan, np.nan], dtype="category")
685
+
686
+ tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp)
687
+ tm.assert_series_equal(s1._append(s2, ignore_index=True), exp)
688
+
689
+ def test_concat_categorical_empty(self):
690
+ # GH 13524
691
+
692
+ s1 = Series([], dtype="category")
693
+ s2 = Series([1, 2], dtype="category")
694
+
695
+ msg = "The behavior of array concatenation with empty entries is deprecated"
696
+ with tm.assert_produces_warning(FutureWarning, match=msg):
697
+ tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), s2)
698
+ tm.assert_series_equal(s1._append(s2, ignore_index=True), s2)
699
+
700
+ with tm.assert_produces_warning(FutureWarning, match=msg):
701
+ tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), s2)
702
+ tm.assert_series_equal(s2._append(s1, ignore_index=True), s2)
703
+
704
+ s1 = Series([], dtype="category")
705
+ s2 = Series([], dtype="category")
706
+
707
+ tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), s2)
708
+ tm.assert_series_equal(s1._append(s2, ignore_index=True), s2)
709
+
710
+ s1 = Series([], dtype="category")
711
+ s2 = Series([], dtype="object")
712
+
713
+ # different dtype => not-category
714
+ tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), s2)
715
+ tm.assert_series_equal(s1._append(s2, ignore_index=True), s2)
716
+ tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), s2)
717
+ tm.assert_series_equal(s2._append(s1, ignore_index=True), s2)
718
+
719
+ s1 = Series([], dtype="category")
720
+ s2 = Series([np.nan, np.nan])
721
+
722
+ # empty Series is ignored
723
+ exp = Series([np.nan, np.nan])
724
+ with tm.assert_produces_warning(FutureWarning, match=msg):
725
+ tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp)
726
+ tm.assert_series_equal(s1._append(s2, ignore_index=True), exp)
727
+
728
+ with tm.assert_produces_warning(FutureWarning, match=msg):
729
+ tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), exp)
730
+ tm.assert_series_equal(s2._append(s1, ignore_index=True), exp)
731
+
732
+ def test_categorical_concat_append(self):
733
+ cat = Categorical(["a", "b"], categories=["a", "b"])
734
+ vals = [1, 2]
735
+ df = DataFrame({"cats": cat, "vals": vals})
736
+ cat2 = Categorical(["a", "b", "a", "b"], categories=["a", "b"])
737
+ vals2 = [1, 2, 1, 2]
738
+ exp = DataFrame({"cats": cat2, "vals": vals2}, index=Index([0, 1, 0, 1]))
739
+
740
+ tm.assert_frame_equal(pd.concat([df, df]), exp)
741
+ tm.assert_frame_equal(df._append(df), exp)
742
+
743
+ # GH 13524 can concat different categories
744
+ cat3 = Categorical(["a", "b"], categories=["a", "b", "c"])
745
+ vals3 = [1, 2]
746
+ df_different_categories = DataFrame({"cats": cat3, "vals": vals3})
747
+
748
+ res = pd.concat([df, df_different_categories], ignore_index=True)
749
+ exp = DataFrame({"cats": list("abab"), "vals": [1, 2, 1, 2]})
750
+ tm.assert_frame_equal(res, exp)
751
+
752
+ res = df._append(df_different_categories, ignore_index=True)
753
+ tm.assert_frame_equal(res, exp)