ZTWHHH commited on
Commit
bda707c
·
verified ·
1 Parent(s): 6952595

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. .gitattributes +2 -0
  2. videochat2/lib/python3.10/site-packages/pandas/core/__pycache__/series.cpython-310.pyc +3 -0
  3. videochat2/lib/python3.10/site-packages/pandas/core/indexes/__pycache__/base.cpython-310.pyc +3 -0
  4. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/__init__.py +0 -0
  5. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/common.py +947 -0
  6. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/conftest.py +61 -0
  7. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike.py +137 -0
  8. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/numeric/__init__.py +0 -0
  9. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/numeric/__pycache__/__init__.cpython-310.pyc +0 -0
  10. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/numeric/__pycache__/test_astype.cpython-310.pyc +0 -0
  11. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/numeric/__pycache__/test_indexing.cpython-310.pyc +0 -0
  12. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/numeric/__pycache__/test_join.cpython-310.pyc +0 -0
  13. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/numeric/__pycache__/test_numeric.cpython-310.pyc +0 -0
  14. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/numeric/__pycache__/test_setops.cpython-310.pyc +0 -0
  15. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/numeric/test_astype.py +95 -0
  16. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/numeric/test_indexing.py +611 -0
  17. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/numeric/test_join.py +380 -0
  18. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/numeric/test_numeric.py +551 -0
  19. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/numeric/test_setops.py +154 -0
  20. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/test_any_index.py +171 -0
  21. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/test_common.py +488 -0
  22. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/test_engines.py +192 -0
  23. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/test_frozen.py +113 -0
  24. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/test_indexing.py +360 -0
  25. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/test_numpy_compat.py +191 -0
  26. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/test_setops.py +888 -0
  27. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/test_subclass.py +38 -0
  28. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__init__.py +0 -0
  29. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_constructors.py +275 -0
  30. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_freq_attr.py +61 -0
  31. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_indexing.py +347 -0
  32. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_join.py +53 -0
  33. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_ops.py +14 -0
  34. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_setops.py +252 -0
  35. videochat2/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_timedelta.py +159 -0
  36. videochat2/lib/python3.10/site-packages/pandas/tests/tseries/__pycache__/__init__.cpython-310.pyc +0 -0
  37. videochat2/lib/python3.10/site-packages/pandas/tests/tseries/offsets/__init__.py +0 -0
  38. videochat2/lib/python3.10/site-packages/pandas/tests/tseries/offsets/__pycache__/__init__.cpython-310.pyc +0 -0
  39. videochat2/lib/python3.10/site-packages/pandas/tests/tseries/offsets/__pycache__/common.cpython-310.pyc +0 -0
  40. videochat2/lib/python3.10/site-packages/pandas/tests/tseries/offsets/__pycache__/conftest.cpython-310.pyc +0 -0
  41. videochat2/lib/python3.10/site-packages/pandas/tests/tseries/offsets/__pycache__/test_business_day.cpython-310.pyc +0 -0
  42. videochat2/lib/python3.10/site-packages/pandas/tests/tseries/offsets/__pycache__/test_business_hour.cpython-310.pyc +0 -0
  43. videochat2/lib/python3.10/site-packages/pandas/tests/tseries/offsets/__pycache__/test_business_month.cpython-310.pyc +0 -0
  44. videochat2/lib/python3.10/site-packages/pandas/tests/tseries/offsets/__pycache__/test_business_quarter.cpython-310.pyc +0 -0
  45. videochat2/lib/python3.10/site-packages/pandas/tests/tseries/offsets/__pycache__/test_business_year.cpython-310.pyc +0 -0
  46. videochat2/lib/python3.10/site-packages/pandas/tests/tseries/offsets/__pycache__/test_common.cpython-310.pyc +0 -0
  47. videochat2/lib/python3.10/site-packages/pandas/tests/tseries/offsets/__pycache__/test_custom_business_day.cpython-310.pyc +0 -0
  48. videochat2/lib/python3.10/site-packages/pandas/tests/tseries/offsets/__pycache__/test_custom_business_hour.cpython-310.pyc +0 -0
  49. videochat2/lib/python3.10/site-packages/pandas/tests/tseries/offsets/__pycache__/test_custom_business_month.cpython-310.pyc +0 -0
  50. videochat2/lib/python3.10/site-packages/pandas/tests/tseries/offsets/__pycache__/test_dst.cpython-310.pyc +0 -0
.gitattributes CHANGED
@@ -1275,3 +1275,5 @@ videochat2/lib/python3.10/site-packages/pandas/_libs/tslibs/conversion.cpython-3
1275
  videochat2/lib/python3.10/site-packages/pandas/_libs/tslibs/np_datetime.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1276
  videochat2/lib/python3.10/site-packages/pandas/_libs/tslibs/timezones.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1277
  videochat2/lib/python3.10/site-packages/pandas/core/groupby/__pycache__/groupby.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
1275
  videochat2/lib/python3.10/site-packages/pandas/_libs/tslibs/np_datetime.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1276
  videochat2/lib/python3.10/site-packages/pandas/_libs/tslibs/timezones.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1277
  videochat2/lib/python3.10/site-packages/pandas/core/groupby/__pycache__/groupby.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1278
+ videochat2/lib/python3.10/site-packages/pandas/core/indexes/__pycache__/base.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1279
+ videochat2/lib/python3.10/site-packages/pandas/core/__pycache__/series.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
videochat2/lib/python3.10/site-packages/pandas/core/__pycache__/series.cpython-310.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:32702f2829ead8f65482c7dc7c5baab1e995ffc8be3e74dc203bb5d1c29b3e19
3
+ size 158641
videochat2/lib/python3.10/site-packages/pandas/core/indexes/__pycache__/base.cpython-310.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e5635178510de825b065ff9c76263b3cc24e6bc5e2a36f73cf3610c77c39129e
3
+ size 181384
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/__init__.py ADDED
File without changes
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/common.py ADDED
@@ -0,0 +1,947 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from datetime import datetime
4
+ import gc
5
+
6
+ import numpy as np
7
+ import pytest
8
+
9
+ from pandas._libs.tslibs import Timestamp
10
+
11
+ from pandas.core.dtypes.common import (
12
+ is_datetime64tz_dtype,
13
+ is_integer_dtype,
14
+ )
15
+ from pandas.core.dtypes.dtypes import CategoricalDtype
16
+
17
+ import pandas as pd
18
+ from pandas import (
19
+ CategoricalIndex,
20
+ DatetimeIndex,
21
+ Index,
22
+ IntervalIndex,
23
+ MultiIndex,
24
+ PeriodIndex,
25
+ RangeIndex,
26
+ Series,
27
+ TimedeltaIndex,
28
+ isna,
29
+ )
30
+ import pandas._testing as tm
31
+ from pandas.core.arrays import BaseMaskedArray
32
+
33
+
34
+ class Base:
35
+ """
36
+ Base class for index sub-class tests.
37
+ """
38
+
39
+ _index_cls: type[Index]
40
+
41
+ @pytest.fixture
42
+ def simple_index(self):
43
+ raise NotImplementedError("Method not implemented")
44
+
45
+ def create_index(self) -> Index:
46
+ raise NotImplementedError("Method not implemented")
47
+
48
+ def test_pickle_compat_construction(self):
49
+ # need an object to create with
50
+ msg = "|".join(
51
+ [
52
+ r"Index\(\.\.\.\) must be called with a collection of some "
53
+ r"kind, None was passed",
54
+ r"DatetimeIndex\(\) must be called with a collection of some "
55
+ r"kind, None was passed",
56
+ r"TimedeltaIndex\(\) must be called with a collection of some "
57
+ r"kind, None was passed",
58
+ r"__new__\(\) missing 1 required positional argument: 'data'",
59
+ r"__new__\(\) takes at least 2 arguments \(1 given\)",
60
+ ]
61
+ )
62
+ with pytest.raises(TypeError, match=msg):
63
+ self._index_cls()
64
+
65
+ def test_shift(self, simple_index):
66
+ # GH8083 test the base class for shift
67
+ idx = simple_index
68
+ msg = (
69
+ f"This method is only implemented for DatetimeIndex, PeriodIndex and "
70
+ f"TimedeltaIndex; Got type {type(idx).__name__}"
71
+ )
72
+ with pytest.raises(NotImplementedError, match=msg):
73
+ idx.shift(1)
74
+ with pytest.raises(NotImplementedError, match=msg):
75
+ idx.shift(1, 2)
76
+
77
+ def test_constructor_name_unhashable(self, simple_index):
78
+ # GH#29069 check that name is hashable
79
+ # See also same-named test in tests.series.test_constructors
80
+ idx = simple_index
81
+ with pytest.raises(TypeError, match="Index.name must be a hashable type"):
82
+ type(idx)(idx, name=[])
83
+
84
+ def test_create_index_existing_name(self, simple_index):
85
+ # GH11193, when an existing index is passed, and a new name is not
86
+ # specified, the new index should inherit the previous object name
87
+ expected = simple_index
88
+ if not isinstance(expected, MultiIndex):
89
+ expected.name = "foo"
90
+ result = Index(expected)
91
+ tm.assert_index_equal(result, expected)
92
+
93
+ result = Index(expected, name="bar")
94
+ expected.name = "bar"
95
+ tm.assert_index_equal(result, expected)
96
+ else:
97
+ expected.names = ["foo", "bar"]
98
+ result = Index(expected)
99
+ tm.assert_index_equal(
100
+ result,
101
+ Index(
102
+ Index(
103
+ [
104
+ ("foo", "one"),
105
+ ("foo", "two"),
106
+ ("bar", "one"),
107
+ ("baz", "two"),
108
+ ("qux", "one"),
109
+ ("qux", "two"),
110
+ ],
111
+ dtype="object",
112
+ ),
113
+ names=["foo", "bar"],
114
+ ),
115
+ )
116
+
117
+ result = Index(expected, names=["A", "B"])
118
+ tm.assert_index_equal(
119
+ result,
120
+ Index(
121
+ Index(
122
+ [
123
+ ("foo", "one"),
124
+ ("foo", "two"),
125
+ ("bar", "one"),
126
+ ("baz", "two"),
127
+ ("qux", "one"),
128
+ ("qux", "two"),
129
+ ],
130
+ dtype="object",
131
+ ),
132
+ names=["A", "B"],
133
+ ),
134
+ )
135
+
136
+ def test_numeric_compat(self, simple_index):
137
+ idx = simple_index
138
+ # Check that this doesn't cover MultiIndex case, if/when it does,
139
+ # we can remove multi.test_compat.test_numeric_compat
140
+ assert not isinstance(idx, MultiIndex)
141
+ if type(idx) is Index:
142
+ return
143
+
144
+ typ = type(idx._data).__name__
145
+ cls = type(idx).__name__
146
+ lmsg = "|".join(
147
+ [
148
+ rf"unsupported operand type\(s\) for \*: '{typ}' and 'int'",
149
+ "cannot perform (__mul__|__truediv__|__floordiv__) with "
150
+ f"this index type: ({cls}|{typ})",
151
+ ]
152
+ )
153
+ with pytest.raises(TypeError, match=lmsg):
154
+ idx * 1
155
+ rmsg = "|".join(
156
+ [
157
+ rf"unsupported operand type\(s\) for \*: 'int' and '{typ}'",
158
+ "cannot perform (__rmul__|__rtruediv__|__rfloordiv__) with "
159
+ f"this index type: ({cls}|{typ})",
160
+ ]
161
+ )
162
+ with pytest.raises(TypeError, match=rmsg):
163
+ 1 * idx
164
+
165
+ div_err = lmsg.replace("*", "/")
166
+ with pytest.raises(TypeError, match=div_err):
167
+ idx / 1
168
+ div_err = rmsg.replace("*", "/")
169
+ with pytest.raises(TypeError, match=div_err):
170
+ 1 / idx
171
+
172
+ floordiv_err = lmsg.replace("*", "//")
173
+ with pytest.raises(TypeError, match=floordiv_err):
174
+ idx // 1
175
+ floordiv_err = rmsg.replace("*", "//")
176
+ with pytest.raises(TypeError, match=floordiv_err):
177
+ 1 // idx
178
+
179
+ def test_logical_compat(self, simple_index):
180
+ idx = simple_index
181
+ with pytest.raises(TypeError, match="cannot perform all"):
182
+ idx.all()
183
+ with pytest.raises(TypeError, match="cannot perform any"):
184
+ idx.any()
185
+
186
+ def test_repr_roundtrip(self, simple_index):
187
+ idx = simple_index
188
+ tm.assert_index_equal(eval(repr(idx)), idx)
189
+
190
+ def test_repr_max_seq_item_setting(self, simple_index):
191
+ # GH10182
192
+ idx = simple_index
193
+ idx = idx.repeat(50)
194
+ with pd.option_context("display.max_seq_items", None):
195
+ repr(idx)
196
+ assert "..." not in str(idx)
197
+
198
+ def test_ensure_copied_data(self, index):
199
+ # Check the "copy" argument of each Index.__new__ is honoured
200
+ # GH12309
201
+ init_kwargs = {}
202
+ if isinstance(index, PeriodIndex):
203
+ # Needs "freq" specification:
204
+ init_kwargs["freq"] = index.freq
205
+ elif isinstance(index, (RangeIndex, MultiIndex, CategoricalIndex)):
206
+ # RangeIndex cannot be initialized from data
207
+ # MultiIndex and CategoricalIndex are tested separately
208
+ return
209
+ elif index.dtype == object and index.inferred_type == "boolean":
210
+ init_kwargs["dtype"] = index.dtype
211
+
212
+ index_type = type(index)
213
+ result = index_type(index.values, copy=True, **init_kwargs)
214
+ if is_datetime64tz_dtype(index.dtype):
215
+ result = result.tz_localize("UTC").tz_convert(index.tz)
216
+ if isinstance(index, (DatetimeIndex, TimedeltaIndex)):
217
+ index = index._with_freq(None)
218
+
219
+ tm.assert_index_equal(index, result)
220
+
221
+ if isinstance(index, PeriodIndex):
222
+ # .values an object array of Period, thus copied
223
+ result = index_type(ordinal=index.asi8, copy=False, **init_kwargs)
224
+ tm.assert_numpy_array_equal(index.asi8, result.asi8, check_same="same")
225
+ elif isinstance(index, IntervalIndex):
226
+ # checked in test_interval.py
227
+ pass
228
+ elif type(index) is Index and not isinstance(index.dtype, np.dtype):
229
+ result = index_type(index.values, copy=False, **init_kwargs)
230
+ tm.assert_index_equal(result, index)
231
+
232
+ if isinstance(index._values, BaseMaskedArray):
233
+ assert np.shares_memory(index._values._data, result._values._data)
234
+ tm.assert_numpy_array_equal(
235
+ index._values._data, result._values._data, check_same="same"
236
+ )
237
+ assert np.shares_memory(index._values._mask, result._values._mask)
238
+ tm.assert_numpy_array_equal(
239
+ index._values._mask, result._values._mask, check_same="same"
240
+ )
241
+ elif index.dtype == "string[python]":
242
+ assert np.shares_memory(index._values._ndarray, result._values._ndarray)
243
+ tm.assert_numpy_array_equal(
244
+ index._values._ndarray, result._values._ndarray, check_same="same"
245
+ )
246
+ elif index.dtype == "string[pyarrow]":
247
+ assert tm.shares_memory(result._values, index._values)
248
+ else:
249
+ raise NotImplementedError(index.dtype)
250
+ else:
251
+ result = index_type(index.values, copy=False, **init_kwargs)
252
+ tm.assert_numpy_array_equal(index.values, result.values, check_same="same")
253
+
254
+ def test_memory_usage(self, index):
255
+ index._engine.clear_mapping()
256
+ result = index.memory_usage()
257
+ if index.empty:
258
+ # we report 0 for no-length
259
+ assert result == 0
260
+ return
261
+
262
+ # non-zero length
263
+ index.get_loc(index[0])
264
+ result2 = index.memory_usage()
265
+ result3 = index.memory_usage(deep=True)
266
+
267
+ # RangeIndex, IntervalIndex
268
+ # don't have engines
269
+ # Index[EA] has engine but it does not have a Hashtable .mapping
270
+ if not isinstance(index, (RangeIndex, IntervalIndex)) and not (
271
+ type(index) is Index and not isinstance(index.dtype, np.dtype)
272
+ ):
273
+ assert result2 > result
274
+
275
+ if index.inferred_type == "object":
276
+ assert result3 > result2
277
+
278
+ def test_argsort(self, index):
279
+ # separately tested
280
+ if isinstance(index, CategoricalIndex):
281
+ return
282
+
283
+ result = index.argsort()
284
+ expected = np.array(index).argsort()
285
+ tm.assert_numpy_array_equal(result, expected, check_dtype=False)
286
+
287
+ def test_numpy_argsort(self, index):
288
+ result = np.argsort(index)
289
+ expected = index.argsort()
290
+ tm.assert_numpy_array_equal(result, expected)
291
+
292
+ result = np.argsort(index, kind="mergesort")
293
+ expected = index.argsort(kind="mergesort")
294
+ tm.assert_numpy_array_equal(result, expected)
295
+
296
+ # these are the only two types that perform
297
+ # pandas compatibility input validation - the
298
+ # rest already perform separate (or no) such
299
+ # validation via their 'values' attribute as
300
+ # defined in pandas.core.indexes/base.py - they
301
+ # cannot be changed at the moment due to
302
+ # backwards compatibility concerns
303
+ if isinstance(index, (CategoricalIndex, RangeIndex)):
304
+ msg = "the 'axis' parameter is not supported"
305
+ with pytest.raises(ValueError, match=msg):
306
+ np.argsort(index, axis=1)
307
+
308
+ msg = "the 'order' parameter is not supported"
309
+ with pytest.raises(ValueError, match=msg):
310
+ np.argsort(index, order=("a", "b"))
311
+
312
+ def test_repeat(self, simple_index):
313
+ rep = 2
314
+ idx = simple_index.copy()
315
+ new_index_cls = idx._constructor
316
+ expected = new_index_cls(idx.values.repeat(rep), name=idx.name)
317
+ tm.assert_index_equal(idx.repeat(rep), expected)
318
+
319
+ idx = simple_index
320
+ rep = np.arange(len(idx))
321
+ expected = new_index_cls(idx.values.repeat(rep), name=idx.name)
322
+ tm.assert_index_equal(idx.repeat(rep), expected)
323
+
324
+ def test_numpy_repeat(self, simple_index):
325
+ rep = 2
326
+ idx = simple_index
327
+ expected = idx.repeat(rep)
328
+ tm.assert_index_equal(np.repeat(idx, rep), expected)
329
+
330
+ msg = "the 'axis' parameter is not supported"
331
+ with pytest.raises(ValueError, match=msg):
332
+ np.repeat(idx, rep, axis=0)
333
+
334
+ def test_where(self, listlike_box, simple_index):
335
+ klass = listlike_box
336
+
337
+ idx = simple_index
338
+ if isinstance(idx, (DatetimeIndex, TimedeltaIndex)):
339
+ # where does not preserve freq
340
+ idx = idx._with_freq(None)
341
+
342
+ cond = [True] * len(idx)
343
+ result = idx.where(klass(cond))
344
+ expected = idx
345
+ tm.assert_index_equal(result, expected)
346
+
347
+ cond = [False] + [True] * len(idx[1:])
348
+ expected = Index([idx._na_value] + idx[1:].tolist(), dtype=idx.dtype)
349
+ result = idx.where(klass(cond))
350
+ tm.assert_index_equal(result, expected)
351
+
352
+ def test_insert_base(self, index):
353
+ result = index[1:4]
354
+
355
+ if not len(index):
356
+ return
357
+
358
+ # test 0th element
359
+ assert index[0:4].equals(result.insert(0, index[0]))
360
+
361
+ def test_insert_out_of_bounds(self, index):
362
+ # TypeError/IndexError matches what np.insert raises in these cases
363
+
364
+ if len(index) > 0:
365
+ err = TypeError
366
+ else:
367
+ err = IndexError
368
+ if len(index) == 0:
369
+ # 0 vs 0.5 in error message varies with numpy version
370
+ msg = "index (0|0.5) is out of bounds for axis 0 with size 0"
371
+ else:
372
+ msg = "slice indices must be integers or None or have an __index__ method"
373
+ with pytest.raises(err, match=msg):
374
+ index.insert(0.5, "foo")
375
+
376
+ msg = "|".join(
377
+ [
378
+ r"index -?\d+ is out of bounds for axis 0 with size \d+",
379
+ "loc must be an integer between",
380
+ ]
381
+ )
382
+ with pytest.raises(IndexError, match=msg):
383
+ index.insert(len(index) + 1, 1)
384
+
385
+ with pytest.raises(IndexError, match=msg):
386
+ index.insert(-len(index) - 1, 1)
387
+
388
+ def test_delete_base(self, index):
389
+ if not len(index):
390
+ return
391
+
392
+ if isinstance(index, RangeIndex):
393
+ # tested in class
394
+ return
395
+
396
+ expected = index[1:]
397
+ result = index.delete(0)
398
+ assert result.equals(expected)
399
+ assert result.name == expected.name
400
+
401
+ expected = index[:-1]
402
+ result = index.delete(-1)
403
+ assert result.equals(expected)
404
+ assert result.name == expected.name
405
+
406
+ length = len(index)
407
+ msg = f"index {length} is out of bounds for axis 0 with size {length}"
408
+ with pytest.raises(IndexError, match=msg):
409
+ index.delete(length)
410
+
411
+ def test_equals(self, index):
412
+ if isinstance(index, IntervalIndex):
413
+ # IntervalIndex tested separately, the index.equals(index.astype(object))
414
+ # fails for IntervalIndex
415
+ return
416
+
417
+ is_ea_idx = type(index) is Index and not isinstance(index.dtype, np.dtype)
418
+
419
+ assert index.equals(index)
420
+ assert index.equals(index.copy())
421
+ if not is_ea_idx:
422
+ # doesn't hold for e.g. IntegerDtype
423
+ assert index.equals(index.astype(object))
424
+
425
+ assert not index.equals(list(index))
426
+ assert not index.equals(np.array(index))
427
+
428
+ # Cannot pass in non-int64 dtype to RangeIndex
429
+ if not isinstance(index, RangeIndex) and not is_ea_idx:
430
+ same_values = Index(index, dtype=object)
431
+ assert index.equals(same_values)
432
+ assert same_values.equals(index)
433
+
434
+ if index.nlevels == 1:
435
+ # do not test MultiIndex
436
+ assert not index.equals(Series(index))
437
+
438
+ def test_equals_op(self, simple_index):
439
+ # GH9947, GH10637
440
+ index_a = simple_index
441
+
442
+ n = len(index_a)
443
+ index_b = index_a[0:-1]
444
+ index_c = index_a[0:-1].append(index_a[-2:-1])
445
+ index_d = index_a[0:1]
446
+
447
+ msg = "Lengths must match|could not be broadcast"
448
+ with pytest.raises(ValueError, match=msg):
449
+ index_a == index_b
450
+ expected1 = np.array([True] * n)
451
+ expected2 = np.array([True] * (n - 1) + [False])
452
+ tm.assert_numpy_array_equal(index_a == index_a, expected1)
453
+ tm.assert_numpy_array_equal(index_a == index_c, expected2)
454
+
455
+ # test comparisons with numpy arrays
456
+ array_a = np.array(index_a)
457
+ array_b = np.array(index_a[0:-1])
458
+ array_c = np.array(index_a[0:-1].append(index_a[-2:-1]))
459
+ array_d = np.array(index_a[0:1])
460
+ with pytest.raises(ValueError, match=msg):
461
+ index_a == array_b
462
+ tm.assert_numpy_array_equal(index_a == array_a, expected1)
463
+ tm.assert_numpy_array_equal(index_a == array_c, expected2)
464
+
465
+ # test comparisons with Series
466
+ series_a = Series(array_a)
467
+ series_b = Series(array_b)
468
+ series_c = Series(array_c)
469
+ series_d = Series(array_d)
470
+ with pytest.raises(ValueError, match=msg):
471
+ index_a == series_b
472
+
473
+ tm.assert_numpy_array_equal(index_a == series_a, expected1)
474
+ tm.assert_numpy_array_equal(index_a == series_c, expected2)
475
+
476
+ # cases where length is 1 for one of them
477
+ with pytest.raises(ValueError, match="Lengths must match"):
478
+ index_a == index_d
479
+ with pytest.raises(ValueError, match="Lengths must match"):
480
+ index_a == series_d
481
+ with pytest.raises(ValueError, match="Lengths must match"):
482
+ index_a == array_d
483
+ msg = "Can only compare identically-labeled Series objects"
484
+ with pytest.raises(ValueError, match=msg):
485
+ series_a == series_d
486
+ with pytest.raises(ValueError, match="Lengths must match"):
487
+ series_a == array_d
488
+
489
+ # comparing with a scalar should broadcast; note that we are excluding
490
+ # MultiIndex because in this case each item in the index is a tuple of
491
+ # length 2, and therefore is considered an array of length 2 in the
492
+ # comparison instead of a scalar
493
+ if not isinstance(index_a, MultiIndex):
494
+ expected3 = np.array([False] * (len(index_a) - 2) + [True, False])
495
+ # assuming the 2nd to last item is unique in the data
496
+ item = index_a[-2]
497
+ tm.assert_numpy_array_equal(index_a == item, expected3)
498
+ tm.assert_series_equal(series_a == item, Series(expected3))
499
+
500
+ def test_format(self, simple_index):
501
+ # GH35439
502
+ idx = simple_index
503
+ expected = [str(x) for x in idx]
504
+ assert idx.format() == expected
505
+
506
+ def test_format_empty(self):
507
+ # GH35712
508
+ empty_idx = self._index_cls([])
509
+ assert empty_idx.format() == []
510
+ assert empty_idx.format(name=True) == [""]
511
+
512
+ def test_fillna(self, index):
513
+ # GH 11343
514
+ if len(index) == 0:
515
+ return
516
+ elif index.dtype == bool:
517
+ # can't hold NAs
518
+ return
519
+ elif isinstance(index, Index) and is_integer_dtype(index.dtype):
520
+ return
521
+ elif isinstance(index, MultiIndex):
522
+ idx = index.copy(deep=True)
523
+ msg = "isna is not defined for MultiIndex"
524
+ with pytest.raises(NotImplementedError, match=msg):
525
+ idx.fillna(idx[0])
526
+ else:
527
+ idx = index.copy(deep=True)
528
+ result = idx.fillna(idx[0])
529
+ tm.assert_index_equal(result, idx)
530
+ assert result is not idx
531
+
532
+ msg = "'value' must be a scalar, passed: "
533
+ with pytest.raises(TypeError, match=msg):
534
+ idx.fillna([idx[0]])
535
+
536
+ idx = index.copy(deep=True)
537
+ values = idx._values
538
+
539
+ values[1] = np.nan
540
+
541
+ idx = type(index)(values)
542
+
543
+ msg = "does not support 'downcast'"
544
+ with pytest.raises(NotImplementedError, match=msg):
545
+ # For now at least, we only raise if there are NAs present
546
+ idx.fillna(idx[0], downcast="infer")
547
+
548
+ expected = np.array([False] * len(idx), dtype=bool)
549
+ expected[1] = True
550
+ tm.assert_numpy_array_equal(idx._isnan, expected)
551
+ assert idx.hasnans is True
552
+
553
+ def test_nulls(self, index):
554
+ # this is really a smoke test for the methods
555
+ # as these are adequately tested for function elsewhere
556
+ if len(index) == 0:
557
+ tm.assert_numpy_array_equal(index.isna(), np.array([], dtype=bool))
558
+ elif isinstance(index, MultiIndex):
559
+ idx = index.copy()
560
+ msg = "isna is not defined for MultiIndex"
561
+ with pytest.raises(NotImplementedError, match=msg):
562
+ idx.isna()
563
+ elif not index.hasnans:
564
+ tm.assert_numpy_array_equal(index.isna(), np.zeros(len(index), dtype=bool))
565
+ tm.assert_numpy_array_equal(index.notna(), np.ones(len(index), dtype=bool))
566
+ else:
567
+ result = isna(index)
568
+ tm.assert_numpy_array_equal(index.isna(), result)
569
+ tm.assert_numpy_array_equal(index.notna(), ~result)
570
+
571
+ def test_empty(self, simple_index):
572
+ # GH 15270
573
+ idx = simple_index
574
+ assert not idx.empty
575
+ assert idx[:0].empty
576
+
577
+ def test_join_self_unique(self, join_type, simple_index):
578
+ idx = simple_index
579
+ if idx.is_unique:
580
+ joined = idx.join(idx, how=join_type)
581
+ assert (idx == joined).all()
582
+
583
+ def test_map(self, simple_index):
584
+ # callable
585
+ idx = simple_index
586
+
587
+ result = idx.map(lambda x: x)
588
+ # RangeIndex are equivalent to the similar Index with int64 dtype
589
+ tm.assert_index_equal(result, idx, exact="equiv")
590
+
591
+ @pytest.mark.parametrize(
592
+ "mapper",
593
+ [
594
+ lambda values, index: {i: e for e, i in zip(values, index)},
595
+ lambda values, index: Series(values, index),
596
+ ],
597
+ )
598
+ def test_map_dictlike(self, mapper, simple_index):
599
+ idx = simple_index
600
+ if isinstance(idx, CategoricalIndex):
601
+ # FIXME: this fails with CategoricalIndex bc it goes through
602
+ # Categorical.map which ends up calling get_indexer with
603
+ # non-unique values, which raises. This _should_ work fine for
604
+ # CategoricalIndex.
605
+ pytest.skip(f"skipping tests for {type(idx)}")
606
+
607
+ identity = mapper(idx.values, idx)
608
+
609
+ result = idx.map(identity)
610
+ # RangeIndex are equivalent to the similar Index with int64 dtype
611
+ tm.assert_index_equal(result, idx, exact="equiv")
612
+
613
+ # empty mappable
614
+ dtype = None
615
+ if idx.dtype.kind == "f":
616
+ dtype = idx.dtype
617
+
618
+ expected = Index([np.nan] * len(idx), dtype=dtype)
619
+ result = idx.map(mapper(expected, idx))
620
+ tm.assert_index_equal(result, expected)
621
+
622
+ def test_map_str(self, simple_index):
623
+ # GH 31202
624
+ idx = simple_index
625
+ result = idx.map(str)
626
+ expected = Index([str(x) for x in idx], dtype=object)
627
+ tm.assert_index_equal(result, expected)
628
+
629
+ @pytest.mark.parametrize("copy", [True, False])
630
+ @pytest.mark.parametrize("name", [None, "foo"])
631
+ @pytest.mark.parametrize("ordered", [True, False])
632
+ def test_astype_category(self, copy, name, ordered, simple_index):
633
+ # GH 18630
634
+ idx = simple_index
635
+ if name:
636
+ idx = idx.rename(name)
637
+
638
+ # standard categories
639
+ dtype = CategoricalDtype(ordered=ordered)
640
+ result = idx.astype(dtype, copy=copy)
641
+ expected = CategoricalIndex(idx, name=name, ordered=ordered)
642
+ tm.assert_index_equal(result, expected, exact=True)
643
+
644
+ # non-standard categories
645
+ dtype = CategoricalDtype(idx.unique().tolist()[:-1], ordered)
646
+ result = idx.astype(dtype, copy=copy)
647
+ expected = CategoricalIndex(idx, name=name, dtype=dtype)
648
+ tm.assert_index_equal(result, expected, exact=True)
649
+
650
+ if ordered is False:
651
+ # dtype='category' defaults to ordered=False, so only test once
652
+ result = idx.astype("category", copy=copy)
653
+ expected = CategoricalIndex(idx, name=name)
654
+ tm.assert_index_equal(result, expected, exact=True)
655
+
656
+ def test_is_unique(self, simple_index):
657
+ # initialize a unique index
658
+ index = simple_index.drop_duplicates()
659
+ assert index.is_unique is True
660
+
661
+ # empty index should be unique
662
+ index_empty = index[:0]
663
+ assert index_empty.is_unique is True
664
+
665
+ # test basic dupes
666
+ index_dup = index.insert(0, index[0])
667
+ assert index_dup.is_unique is False
668
+
669
+ # single NA should be unique
670
+ index_na = index.insert(0, np.nan)
671
+ assert index_na.is_unique is True
672
+
673
+ # multiple NA should not be unique
674
+ index_na_dup = index_na.insert(0, np.nan)
675
+ assert index_na_dup.is_unique is False
676
+
677
+ @pytest.mark.arm_slow
678
+ def test_engine_reference_cycle(self, simple_index):
679
+ # GH27585
680
+ index = simple_index
681
+ nrefs_pre = len(gc.get_referrers(index))
682
+ index._engine
683
+ assert len(gc.get_referrers(index)) == nrefs_pre
684
+
685
+ def test_getitem_2d_deprecated(self, simple_index):
686
+ # GH#30588, GH#31479
687
+ idx = simple_index
688
+ msg = "Multi-dimensional indexing"
689
+ with pytest.raises(ValueError, match=msg):
690
+ idx[:, None]
691
+
692
+ if not isinstance(idx, RangeIndex):
693
+ # GH#44051 RangeIndex already raised pre-2.0 with a different message
694
+ with pytest.raises(ValueError, match=msg):
695
+ idx[True]
696
+ with pytest.raises(ValueError, match=msg):
697
+ idx[False]
698
+ else:
699
+ msg = "only integers, slices"
700
+ with pytest.raises(IndexError, match=msg):
701
+ idx[True]
702
+ with pytest.raises(IndexError, match=msg):
703
+ idx[False]
704
+
705
+ def test_copy_shares_cache(self, simple_index):
706
+ # GH32898, GH36840
707
+ idx = simple_index
708
+ idx.get_loc(idx[0]) # populates the _cache.
709
+ copy = idx.copy()
710
+
711
+ assert copy._cache is idx._cache
712
+
713
+ def test_shallow_copy_shares_cache(self, simple_index):
714
+ # GH32669, GH36840
715
+ idx = simple_index
716
+ idx.get_loc(idx[0]) # populates the _cache.
717
+ shallow_copy = idx._view()
718
+
719
+ assert shallow_copy._cache is idx._cache
720
+
721
+ shallow_copy = idx._shallow_copy(idx._data)
722
+ assert shallow_copy._cache is not idx._cache
723
+ assert shallow_copy._cache == {}
724
+
725
+ def test_index_groupby(self, simple_index):
726
+ idx = simple_index[:5]
727
+ to_groupby = np.array([1, 2, np.nan, 2, 1])
728
+ tm.assert_dict_equal(
729
+ idx.groupby(to_groupby), {1.0: idx[[0, 4]], 2.0: idx[[1, 3]]}
730
+ )
731
+
732
+ to_groupby = DatetimeIndex(
733
+ [
734
+ datetime(2011, 11, 1),
735
+ datetime(2011, 12, 1),
736
+ pd.NaT,
737
+ datetime(2011, 12, 1),
738
+ datetime(2011, 11, 1),
739
+ ],
740
+ tz="UTC",
741
+ ).values
742
+
743
+ ex_keys = [Timestamp("2011-11-01"), Timestamp("2011-12-01")]
744
+ expected = {ex_keys[0]: idx[[0, 4]], ex_keys[1]: idx[[1, 3]]}
745
+ tm.assert_dict_equal(idx.groupby(to_groupby), expected)
746
+
747
+ def test_append_preserves_dtype(self, simple_index):
748
+ # In particular Index with dtype float32
749
+ index = simple_index
750
+ N = len(index)
751
+
752
+ result = index.append(index)
753
+ assert result.dtype == index.dtype
754
+ tm.assert_index_equal(result[:N], index, check_exact=True)
755
+ tm.assert_index_equal(result[N:], index, check_exact=True)
756
+
757
+ alt = index.take(list(range(N)) * 2)
758
+ tm.assert_index_equal(result, alt, check_exact=True)
759
+
760
+ def test_inv(self, simple_index):
761
+ idx = simple_index
762
+
763
+ if idx.dtype.kind in ["i", "u"]:
764
+ res = ~idx
765
+ expected = Index(~idx.values, name=idx.name)
766
+ tm.assert_index_equal(res, expected)
767
+
768
+ # check that we are matching Series behavior
769
+ res2 = ~Series(idx)
770
+ tm.assert_series_equal(res2, Series(expected))
771
+ else:
772
+ if idx.dtype.kind == "f":
773
+ msg = "ufunc 'invert' not supported for the input types"
774
+ else:
775
+ msg = "bad operand"
776
+ with pytest.raises(TypeError, match=msg):
777
+ ~idx
778
+
779
+ # check that we get the same behavior with Series
780
+ with pytest.raises(TypeError, match=msg):
781
+ ~Series(idx)
782
+
783
+ def test_is_boolean_is_deprecated(self, simple_index):
784
+ # GH50042
785
+ idx = simple_index
786
+ with tm.assert_produces_warning(FutureWarning):
787
+ idx.is_boolean()
788
+
789
+ def test_is_floating_is_deprecated(self, simple_index):
790
+ # GH50042
791
+ idx = simple_index
792
+ with tm.assert_produces_warning(FutureWarning):
793
+ idx.is_floating()
794
+
795
+ def test_is_integer_is_deprecated(self, simple_index):
796
+ # GH50042
797
+ idx = simple_index
798
+ with tm.assert_produces_warning(FutureWarning):
799
+ idx.is_integer()
800
+
801
+ def test_holds_integer_deprecated(self, simple_index):
802
+ # GH50243
803
+ idx = simple_index
804
+ msg = f"{type(idx).__name__}.holds_integer is deprecated. "
805
+ with tm.assert_produces_warning(FutureWarning, match=msg):
806
+ idx.holds_integer()
807
+
808
+ def test_is_numeric_is_deprecated(self, simple_index):
809
+ # GH50042
810
+ idx = simple_index
811
+ with tm.assert_produces_warning(
812
+ FutureWarning,
813
+ match=f"{type(idx).__name__}.is_numeric is deprecated. ",
814
+ ):
815
+ idx.is_numeric()
816
+
817
+ def test_is_categorical_is_deprecated(self, simple_index):
818
+ # GH50042
819
+ idx = simple_index
820
+ with tm.assert_produces_warning(
821
+ FutureWarning,
822
+ match=r"Use pandas\.api\.types\.is_categorical_dtype instead",
823
+ ):
824
+ idx.is_categorical()
825
+
826
+ def test_is_interval_is_deprecated(self, simple_index):
827
+ # GH50042
828
+ idx = simple_index
829
+ with tm.assert_produces_warning(FutureWarning):
830
+ idx.is_interval()
831
+
832
+ def test_is_object_is_deprecated(self, simple_index):
833
+ # GH50042
834
+ idx = simple_index
835
+ with tm.assert_produces_warning(FutureWarning):
836
+ idx.is_object()
837
+
838
+
839
+ class NumericBase(Base):
840
+ """
841
+ Base class for numeric index (incl. RangeIndex) sub-class tests.
842
+ """
843
+
844
+ def test_constructor_unwraps_index(self, dtype):
845
+ index_cls = self._index_cls
846
+
847
+ idx = Index([1, 2], dtype=dtype)
848
+ result = index_cls(idx)
849
+ expected = np.array([1, 2], dtype=idx.dtype)
850
+ tm.assert_numpy_array_equal(result._data, expected)
851
+
852
+ def test_where(self):
853
+ # Tested in numeric.test_indexing
854
+ pass
855
+
856
+ def test_can_hold_identifiers(self, simple_index):
857
+ idx = simple_index
858
+ key = idx[0]
859
+ assert idx._can_hold_identifiers_and_holds_name(key) is False
860
+
861
+ def test_view(self, dtype):
862
+ index_cls = self._index_cls
863
+
864
+ idx = index_cls([], dtype=dtype, name="Foo")
865
+ idx_view = idx.view()
866
+ assert idx_view.name == "Foo"
867
+
868
+ idx_view = idx.view(dtype)
869
+ tm.assert_index_equal(idx, index_cls(idx_view, name="Foo"), exact=True)
870
+
871
+ idx_view = idx.view(index_cls)
872
+ tm.assert_index_equal(idx, index_cls(idx_view, name="Foo"), exact=True)
873
+
874
+ def test_format(self, simple_index):
875
+ # GH35439
876
+ idx = simple_index
877
+ max_width = max(len(str(x)) for x in idx)
878
+ expected = [str(x).ljust(max_width) for x in idx]
879
+ assert idx.format() == expected
880
+
881
+ def test_numeric_compat(self):
882
+ pass # override Base method
883
+
884
+ def test_insert_non_na(self, simple_index):
885
+ # GH#43921 inserting an element that we know we can hold should
886
+ # not change dtype or type (except for RangeIndex)
887
+ index = simple_index
888
+
889
+ result = index.insert(0, index[0])
890
+
891
+ expected = Index([index[0]] + list(index), dtype=index.dtype)
892
+ tm.assert_index_equal(result, expected, exact=True)
893
+
894
+ def test_insert_na(self, nulls_fixture, simple_index):
895
+ # GH 18295 (test missing)
896
+ index = simple_index
897
+ na_val = nulls_fixture
898
+
899
+ if na_val is pd.NaT:
900
+ expected = Index([index[0], pd.NaT] + list(index[1:]), dtype=object)
901
+ else:
902
+ expected = Index([index[0], np.nan] + list(index[1:]))
903
+ # GH#43921 we preserve float dtype
904
+ if index.dtype.kind == "f":
905
+ expected = Index(expected, dtype=index.dtype)
906
+
907
+ result = index.insert(1, na_val)
908
+ tm.assert_index_equal(result, expected, exact=True)
909
+
910
+ def test_arithmetic_explicit_conversions(self):
911
+ # GH 8608
912
+ # add/sub are overridden explicitly for Float/Int Index
913
+ index_cls = self._index_cls
914
+ if index_cls is RangeIndex:
915
+ idx = RangeIndex(5)
916
+ else:
917
+ idx = index_cls(np.arange(5, dtype="int64"))
918
+
919
+ # float conversions
920
+ arr = np.arange(5, dtype="int64") * 3.2
921
+ expected = Index(arr, dtype=np.float64)
922
+ fidx = idx * 3.2
923
+ tm.assert_index_equal(fidx, expected)
924
+ fidx = 3.2 * idx
925
+ tm.assert_index_equal(fidx, expected)
926
+
927
+ # interops with numpy arrays
928
+ expected = Index(arr, dtype=np.float64)
929
+ a = np.zeros(5, dtype="float64")
930
+ result = fidx - a
931
+ tm.assert_index_equal(result, expected)
932
+
933
+ expected = Index(-arr, dtype=np.float64)
934
+ a = np.zeros(5, dtype="float64")
935
+ result = a - fidx
936
+ tm.assert_index_equal(result, expected)
937
+
938
+ @pytest.mark.parametrize("complex_dtype", [np.complex64, np.complex128])
939
+ def test_astype_to_complex(self, complex_dtype, simple_index):
940
+ result = simple_index.astype(complex_dtype)
941
+
942
+ assert type(result) is Index and result.dtype == complex_dtype
943
+
944
+ def test_cast_string(self, dtype):
945
+ result = self._index_cls(["0", "1", "2"], dtype=dtype)
946
+ expected = self._index_cls([0, 1, 2], dtype=dtype)
947
+ tm.assert_index_equal(result, expected)
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/conftest.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas import (
5
+ Series,
6
+ array,
7
+ )
8
+ import pandas._testing as tm
9
+
10
+
11
+ @pytest.fixture(params=[None, False])
12
+ def sort(request):
13
+ """
14
+ Valid values for the 'sort' parameter used in the Index
15
+ setops methods (intersection, union, etc.)
16
+
17
+ Caution:
18
+ Don't confuse this one with the "sort" fixture used
19
+ for DataFrame.append or concat. That one has
20
+ parameters [True, False].
21
+
22
+ We can't combine them as sort=True is not permitted
23
+ in the Index setops methods.
24
+ """
25
+ return request.param
26
+
27
+
28
+ @pytest.fixture(params=["D", "3D", "-3D", "H", "2H", "-2H", "T", "2T", "S", "-3S"])
29
+ def freq_sample(request):
30
+ """
31
+ Valid values for 'freq' parameter used to create date_range and
32
+ timedelta_range..
33
+ """
34
+ return request.param
35
+
36
+
37
+ @pytest.fixture(params=[list, tuple, np.array, array, Series])
38
+ def listlike_box(request):
39
+ """
40
+ Types that may be passed as the indexer to searchsorted.
41
+ """
42
+ return request.param
43
+
44
+
45
+ @pytest.fixture(
46
+ params=tm.ALL_REAL_NUMPY_DTYPES
47
+ + [
48
+ "object",
49
+ "category",
50
+ "datetime64[ns]",
51
+ "timedelta64[ns]",
52
+ ]
53
+ )
54
+ def any_dtype_for_small_pos_integer_indexes(request):
55
+ """
56
+ Dtypes that can be given to an Index with small positive integers.
57
+
58
+ This means that for any dtype `x` in the params list, `Index([1, 2, 3], dtype=x)` is
59
+ valid and gives the correct Index (sub-)class.
60
+ """
61
+ return request.param
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from pandas.tests.indexes.common import Base
9
+
10
+
11
+ class DatetimeLike(Base):
12
+ def test_isin(self, simple_index):
13
+ index = simple_index[:4]
14
+ result = index.isin(index)
15
+ assert result.all()
16
+
17
+ result = index.isin(list(index))
18
+ assert result.all()
19
+
20
+ result = index.isin([index[2], 5])
21
+ expected = np.array([False, False, True, False])
22
+ tm.assert_numpy_array_equal(result, expected)
23
+
24
+ def test_argsort_matches_array(self, simple_index):
25
+ idx = simple_index
26
+ idx = idx.insert(1, pd.NaT)
27
+
28
+ result = idx.argsort()
29
+ expected = idx._data.argsort()
30
+ tm.assert_numpy_array_equal(result, expected)
31
+
32
+ def test_can_hold_identifiers(self, simple_index):
33
+ idx = simple_index
34
+ key = idx[0]
35
+ assert idx._can_hold_identifiers_and_holds_name(key) is False
36
+
37
+ def test_shift_identity(self, simple_index):
38
+ idx = simple_index
39
+ tm.assert_index_equal(idx, idx.shift(0))
40
+
41
+ def test_shift_empty(self, simple_index):
42
+ # GH#14811
43
+ idx = simple_index[:0]
44
+ tm.assert_index_equal(idx, idx.shift(1))
45
+
46
+ def test_str(self, simple_index):
47
+ # test the string repr
48
+ idx = simple_index
49
+ idx.name = "foo"
50
+ assert f"length={len(idx)}" not in str(idx)
51
+ assert "'foo'" in str(idx)
52
+ assert type(idx).__name__ in str(idx)
53
+
54
+ if hasattr(idx, "tz"):
55
+ if idx.tz is not None:
56
+ assert idx.tz in str(idx)
57
+ if isinstance(idx, pd.PeriodIndex):
58
+ assert f"dtype='period[{idx.freqstr}]'" in str(idx)
59
+ else:
60
+ assert f"freq='{idx.freqstr}'" in str(idx)
61
+
62
+ def test_view(self, simple_index):
63
+ idx = simple_index
64
+
65
+ idx_view = idx.view("i8")
66
+ result = self._index_cls(idx)
67
+ tm.assert_index_equal(result, idx)
68
+
69
+ idx_view = idx.view(self._index_cls)
70
+ result = self._index_cls(idx)
71
+ tm.assert_index_equal(result, idx_view)
72
+
73
+ def test_map_callable(self, simple_index):
74
+ index = simple_index
75
+ expected = index + index.freq
76
+ result = index.map(lambda x: x + x.freq)
77
+ tm.assert_index_equal(result, expected)
78
+
79
+ # map to NaT
80
+ result = index.map(lambda x: pd.NaT if x == index[0] else x)
81
+ expected = pd.Index([pd.NaT] + index[1:].tolist())
82
+ tm.assert_index_equal(result, expected)
83
+
84
+ @pytest.mark.parametrize(
85
+ "mapper",
86
+ [
87
+ lambda values, index: {i: e for e, i in zip(values, index)},
88
+ lambda values, index: pd.Series(values, index, dtype=object),
89
+ ],
90
+ )
91
+ def test_map_dictlike(self, mapper, simple_index):
92
+ index = simple_index
93
+ expected = index + index.freq
94
+
95
+ # don't compare the freqs
96
+ if isinstance(expected, (pd.DatetimeIndex, pd.TimedeltaIndex)):
97
+ expected = expected._with_freq(None)
98
+
99
+ result = index.map(mapper(expected, index))
100
+ tm.assert_index_equal(result, expected)
101
+
102
+ expected = pd.Index([pd.NaT] + index[1:].tolist())
103
+ result = index.map(mapper(expected, index))
104
+ tm.assert_index_equal(result, expected)
105
+
106
+ # empty map; these map to np.nan because we cannot know
107
+ # to re-infer things
108
+ expected = pd.Index([np.nan] * len(index))
109
+ result = index.map(mapper([], []))
110
+ tm.assert_index_equal(result, expected)
111
+
112
+ def test_getitem_preserves_freq(self, simple_index):
113
+ index = simple_index
114
+ assert index.freq is not None
115
+
116
+ result = index[:]
117
+ assert result.freq == index.freq
118
+
119
+ def test_where_cast_str(self, simple_index):
120
+ index = simple_index
121
+
122
+ mask = np.ones(len(index), dtype=bool)
123
+ mask[-1] = False
124
+
125
+ result = index.where(mask, str(index[0]))
126
+ expected = index.where(mask, index[0])
127
+ tm.assert_index_equal(result, expected)
128
+
129
+ result = index.where(mask, [str(index[0])])
130
+ tm.assert_index_equal(result, expected)
131
+
132
+ expected = index.astype(object).where(mask, "foo")
133
+ result = index.where(mask, "foo")
134
+ tm.assert_index_equal(result, expected)
135
+
136
+ result = index.where(mask, ["foo"])
137
+ tm.assert_index_equal(result, expected)
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/numeric/__init__.py ADDED
File without changes
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/numeric/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (184 Bytes). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/numeric/__pycache__/test_astype.cpython-310.pyc ADDED
Binary file (3.84 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/numeric/__pycache__/test_indexing.cpython-310.pyc ADDED
Binary file (22.5 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/numeric/__pycache__/test_join.cpython-310.pyc ADDED
Binary file (10 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/numeric/__pycache__/test_numeric.cpython-310.pyc ADDED
Binary file (17 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/numeric/__pycache__/test_setops.cpython-310.pyc ADDED
Binary file (5.26 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/numeric/test_astype.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas import (
5
+ Index,
6
+ to_datetime,
7
+ to_timedelta,
8
+ )
9
+ import pandas._testing as tm
10
+
11
+
12
+ class TestAstype:
13
+ def test_astype_float64_to_uint64(self):
14
+ # GH#45309 used to incorrectly return Index with int64 dtype
15
+ idx = Index([0.0, 5.0, 10.0, 15.0, 20.0], dtype=np.float64)
16
+ result = idx.astype("u8")
17
+ expected = Index([0, 5, 10, 15, 20], dtype=np.uint64)
18
+ tm.assert_index_equal(result, expected, exact=True)
19
+
20
+ idx_with_negatives = idx - 10
21
+ with pytest.raises(ValueError, match="losslessly"):
22
+ idx_with_negatives.astype(np.uint64)
23
+
24
+ def test_astype_float64_to_object(self):
25
+ float_index = Index([0.0, 2.5, 5.0, 7.5, 10.0], dtype=np.float64)
26
+ result = float_index.astype(object)
27
+ assert result.equals(float_index)
28
+ assert float_index.equals(result)
29
+ assert isinstance(result, Index) and result.dtype == object
30
+
31
+ def test_astype_float64_mixed_to_object(self):
32
+ # mixed int-float
33
+ idx = Index([1.5, 2, 3, 4, 5], dtype=np.float64)
34
+ idx.name = "foo"
35
+ result = idx.astype(object)
36
+ assert result.equals(idx)
37
+ assert idx.equals(result)
38
+ assert isinstance(result, Index) and result.dtype == object
39
+
40
+ @pytest.mark.parametrize("dtype", ["int16", "int32", "int64"])
41
+ def test_astype_float64_to_int_dtype(self, dtype):
42
+ # GH#12881
43
+ # a float astype int
44
+ idx = Index([0, 1, 2], dtype=np.float64)
45
+ result = idx.astype(dtype)
46
+ expected = Index([0, 1, 2], dtype=dtype)
47
+ tm.assert_index_equal(result, expected, exact=True)
48
+
49
+ idx = Index([0, 1.1, 2], dtype=np.float64)
50
+ result = idx.astype(dtype)
51
+ expected = Index([0, 1, 2], dtype=dtype)
52
+ tm.assert_index_equal(result, expected, exact=True)
53
+
54
+ @pytest.mark.parametrize("dtype", ["float32", "float64"])
55
+ def test_astype_float64_to_float_dtype(self, dtype):
56
+ # GH#12881
57
+ # a float astype int
58
+ idx = Index([0, 1, 2], dtype=np.float64)
59
+ result = idx.astype(dtype)
60
+ assert isinstance(result, Index) and result.dtype == dtype
61
+
62
+ @pytest.mark.parametrize("dtype", ["M8[ns]", "m8[ns]"])
63
+ def test_astype_float_to_datetimelike(self, dtype):
64
+ # GH#49660 pre-2.0 Index.astype from floating to M8/m8/Period raised,
65
+ # inconsistent with Series.astype
66
+ idx = Index([0, 1.1, 2], dtype=np.float64)
67
+
68
+ result = idx.astype(dtype)
69
+ if dtype[0] == "M":
70
+ expected = to_datetime(idx.values)
71
+ else:
72
+ expected = to_timedelta(idx.values)
73
+ tm.assert_index_equal(result, expected)
74
+
75
+ # check that we match Series behavior
76
+ result = idx.to_series().set_axis(range(3)).astype(dtype)
77
+ expected = expected.to_series().set_axis(range(3))
78
+ tm.assert_series_equal(result, expected)
79
+
80
+ @pytest.mark.parametrize("dtype", [int, "int16", "int32", "int64"])
81
+ @pytest.mark.parametrize("non_finite", [np.inf, np.nan])
82
+ def test_cannot_cast_inf_to_int(self, non_finite, dtype):
83
+ # GH#13149
84
+ idx = Index([1, 2, non_finite], dtype=np.float64)
85
+
86
+ msg = r"Cannot convert non-finite values \(NA or inf\) to integer"
87
+ with pytest.raises(ValueError, match=msg):
88
+ idx.astype(dtype)
89
+
90
+ def test_astype_from_object(self):
91
+ index = Index([1.0, np.nan, 0.2], dtype="object")
92
+ result = index.astype(float)
93
+ expected = Index([1.0, np.nan, 0.2], dtype=np.float64)
94
+ assert result.dtype == expected.dtype
95
+ tm.assert_index_equal(result, expected)
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/numeric/test_indexing.py ADDED
@@ -0,0 +1,611 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas.errors import InvalidIndexError
5
+
6
+ from pandas import (
7
+ NA,
8
+ Index,
9
+ RangeIndex,
10
+ Series,
11
+ Timestamp,
12
+ )
13
+ import pandas._testing as tm
14
+ from pandas.core.arrays import (
15
+ ArrowExtensionArray,
16
+ FloatingArray,
17
+ )
18
+
19
+
20
+ @pytest.fixture
21
+ def index_large():
22
+ # large values used in Index[uint64] tests where no compat needed with Int64/Float64
23
+ large = [2**63, 2**63 + 10, 2**63 + 15, 2**63 + 20, 2**63 + 25]
24
+ return Index(large, dtype=np.uint64)
25
+
26
+
27
+ class TestGetLoc:
28
+ def test_get_loc(self):
29
+ index = Index([0, 1, 2])
30
+ assert index.get_loc(1) == 1
31
+
32
+ def test_get_loc_raises_bad_label(self):
33
+ index = Index([0, 1, 2])
34
+ with pytest.raises(InvalidIndexError, match=r"\[1, 2\]"):
35
+ index.get_loc([1, 2])
36
+
37
+ def test_get_loc_float64(self):
38
+ idx = Index([0.0, 1.0, 2.0], dtype=np.float64)
39
+
40
+ with pytest.raises(KeyError, match="^'foo'$"):
41
+ idx.get_loc("foo")
42
+ with pytest.raises(KeyError, match=r"^1\.5$"):
43
+ idx.get_loc(1.5)
44
+ with pytest.raises(KeyError, match="^True$"):
45
+ idx.get_loc(True)
46
+ with pytest.raises(KeyError, match="^False$"):
47
+ idx.get_loc(False)
48
+
49
+ def test_get_loc_na(self):
50
+ idx = Index([np.nan, 1, 2], dtype=np.float64)
51
+ assert idx.get_loc(1) == 1
52
+ assert idx.get_loc(np.nan) == 0
53
+
54
+ idx = Index([np.nan, 1, np.nan], dtype=np.float64)
55
+ assert idx.get_loc(1) == 1
56
+
57
+ # representable by slice [0:2:2]
58
+ msg = "'Cannot get left slice bound for non-unique label: nan'"
59
+ with pytest.raises(KeyError, match=msg):
60
+ idx.slice_locs(np.nan)
61
+ # not representable by slice
62
+ idx = Index([np.nan, 1, np.nan, np.nan], dtype=np.float64)
63
+ assert idx.get_loc(1) == 1
64
+ msg = "'Cannot get left slice bound for non-unique label: nan"
65
+ with pytest.raises(KeyError, match=msg):
66
+ idx.slice_locs(np.nan)
67
+
68
+ def test_get_loc_missing_nan(self):
69
+ # GH#8569
70
+ idx = Index([1, 2], dtype=np.float64)
71
+ assert idx.get_loc(1) == 0
72
+ with pytest.raises(KeyError, match=r"^3$"):
73
+ idx.get_loc(3)
74
+ with pytest.raises(KeyError, match="^nan$"):
75
+ idx.get_loc(np.nan)
76
+ with pytest.raises(InvalidIndexError, match=r"\[nan\]"):
77
+ # listlike/non-hashable raises TypeError
78
+ idx.get_loc([np.nan])
79
+
80
+ @pytest.mark.parametrize("vals", [[1], [1.0], [Timestamp("2019-12-31")], ["test"]])
81
+ def test_get_loc_float_index_nan_with_method(self, vals):
82
+ # GH#39382
83
+ idx = Index(vals)
84
+ with pytest.raises(KeyError, match="nan"):
85
+ idx.get_loc(np.nan)
86
+
87
+ @pytest.mark.parametrize("dtype", ["f8", "i8", "u8"])
88
+ def test_get_loc_numericindex_none_raises(self, dtype):
89
+ # case that goes through searchsorted and key is non-comparable to values
90
+ arr = np.arange(10**7, dtype=dtype)
91
+ idx = Index(arr)
92
+ with pytest.raises(KeyError, match="None"):
93
+ idx.get_loc(None)
94
+
95
+ def test_get_loc_overflows(self):
96
+ # unique but non-monotonic goes through IndexEngine.mapping.get_item
97
+ idx = Index([0, 2, 1])
98
+
99
+ val = np.iinfo(np.int64).max + 1
100
+
101
+ with pytest.raises(KeyError, match=str(val)):
102
+ idx.get_loc(val)
103
+ with pytest.raises(KeyError, match=str(val)):
104
+ idx._engine.get_loc(val)
105
+
106
+
107
+ class TestGetIndexer:
108
+ def test_get_indexer(self):
109
+ index1 = Index([1, 2, 3, 4, 5])
110
+ index2 = Index([2, 4, 6])
111
+
112
+ r1 = index1.get_indexer(index2)
113
+ e1 = np.array([1, 3, -1], dtype=np.intp)
114
+ tm.assert_almost_equal(r1, e1)
115
+
116
+ @pytest.mark.parametrize("reverse", [True, False])
117
+ @pytest.mark.parametrize(
118
+ "expected,method",
119
+ [
120
+ (np.array([-1, 0, 0, 1, 1], dtype=np.intp), "pad"),
121
+ (np.array([-1, 0, 0, 1, 1], dtype=np.intp), "ffill"),
122
+ (np.array([0, 0, 1, 1, 2], dtype=np.intp), "backfill"),
123
+ (np.array([0, 0, 1, 1, 2], dtype=np.intp), "bfill"),
124
+ ],
125
+ )
126
+ def test_get_indexer_methods(self, reverse, expected, method):
127
+ index1 = Index([1, 2, 3, 4, 5])
128
+ index2 = Index([2, 4, 6])
129
+
130
+ if reverse:
131
+ index1 = index1[::-1]
132
+ expected = expected[::-1]
133
+
134
+ result = index2.get_indexer(index1, method=method)
135
+ tm.assert_almost_equal(result, expected)
136
+
137
+ def test_get_indexer_invalid(self):
138
+ # GH10411
139
+ index = Index(np.arange(10))
140
+
141
+ with pytest.raises(ValueError, match="tolerance argument"):
142
+ index.get_indexer([1, 0], tolerance=1)
143
+
144
+ with pytest.raises(ValueError, match="limit argument"):
145
+ index.get_indexer([1, 0], limit=1)
146
+
147
+ @pytest.mark.parametrize(
148
+ "method, tolerance, indexer, expected",
149
+ [
150
+ ("pad", None, [0, 5, 9], [0, 5, 9]),
151
+ ("backfill", None, [0, 5, 9], [0, 5, 9]),
152
+ ("nearest", None, [0, 5, 9], [0, 5, 9]),
153
+ ("pad", 0, [0, 5, 9], [0, 5, 9]),
154
+ ("backfill", 0, [0, 5, 9], [0, 5, 9]),
155
+ ("nearest", 0, [0, 5, 9], [0, 5, 9]),
156
+ ("pad", None, [0.2, 1.8, 8.5], [0, 1, 8]),
157
+ ("backfill", None, [0.2, 1.8, 8.5], [1, 2, 9]),
158
+ ("nearest", None, [0.2, 1.8, 8.5], [0, 2, 9]),
159
+ ("pad", 1, [0.2, 1.8, 8.5], [0, 1, 8]),
160
+ ("backfill", 1, [0.2, 1.8, 8.5], [1, 2, 9]),
161
+ ("nearest", 1, [0.2, 1.8, 8.5], [0, 2, 9]),
162
+ ("pad", 0.2, [0.2, 1.8, 8.5], [0, -1, -1]),
163
+ ("backfill", 0.2, [0.2, 1.8, 8.5], [-1, 2, -1]),
164
+ ("nearest", 0.2, [0.2, 1.8, 8.5], [0, 2, -1]),
165
+ ],
166
+ )
167
+ def test_get_indexer_nearest(self, method, tolerance, indexer, expected):
168
+ index = Index(np.arange(10))
169
+
170
+ actual = index.get_indexer(indexer, method=method, tolerance=tolerance)
171
+ tm.assert_numpy_array_equal(actual, np.array(expected, dtype=np.intp))
172
+
173
+ @pytest.mark.parametrize("listtype", [list, tuple, Series, np.array])
174
+ @pytest.mark.parametrize(
175
+ "tolerance, expected",
176
+ list(
177
+ zip(
178
+ [[0.3, 0.3, 0.1], [0.2, 0.1, 0.1], [0.1, 0.5, 0.5]],
179
+ [[0, 2, -1], [0, -1, -1], [-1, 2, 9]],
180
+ )
181
+ ),
182
+ )
183
+ def test_get_indexer_nearest_listlike_tolerance(
184
+ self, tolerance, expected, listtype
185
+ ):
186
+ index = Index(np.arange(10))
187
+
188
+ actual = index.get_indexer(
189
+ [0.2, 1.8, 8.5], method="nearest", tolerance=listtype(tolerance)
190
+ )
191
+ tm.assert_numpy_array_equal(actual, np.array(expected, dtype=np.intp))
192
+
193
+ def test_get_indexer_nearest_error(self):
194
+ index = Index(np.arange(10))
195
+ with pytest.raises(ValueError, match="limit argument"):
196
+ index.get_indexer([1, 0], method="nearest", limit=1)
197
+
198
+ with pytest.raises(ValueError, match="tolerance size must match"):
199
+ index.get_indexer([1, 0], method="nearest", tolerance=[1, 2, 3])
200
+
201
+ @pytest.mark.parametrize(
202
+ "method,expected",
203
+ [("pad", [8, 7, 0]), ("backfill", [9, 8, 1]), ("nearest", [9, 7, 0])],
204
+ )
205
+ def test_get_indexer_nearest_decreasing(self, method, expected):
206
+ index = Index(np.arange(10))[::-1]
207
+
208
+ actual = index.get_indexer([0, 5, 9], method=method)
209
+ tm.assert_numpy_array_equal(actual, np.array([9, 4, 0], dtype=np.intp))
210
+
211
+ actual = index.get_indexer([0.2, 1.8, 8.5], method=method)
212
+ tm.assert_numpy_array_equal(actual, np.array(expected, dtype=np.intp))
213
+
214
+ @pytest.mark.parametrize("idx_dtype", ["int64", "float64", "uint64", "range"])
215
+ @pytest.mark.parametrize("method", ["get_indexer", "get_indexer_non_unique"])
216
+ def test_get_indexer_numeric_index_boolean_target(self, method, idx_dtype):
217
+ # GH 16877
218
+
219
+ if idx_dtype == "range":
220
+ numeric_index = RangeIndex(4)
221
+ else:
222
+ numeric_index = Index(np.arange(4, dtype=idx_dtype))
223
+
224
+ other = Index([True, False, True])
225
+
226
+ result = getattr(numeric_index, method)(other)
227
+ expected = np.array([-1, -1, -1], dtype=np.intp)
228
+ if method == "get_indexer":
229
+ tm.assert_numpy_array_equal(result, expected)
230
+ else:
231
+ missing = np.arange(3, dtype=np.intp)
232
+ tm.assert_numpy_array_equal(result[0], expected)
233
+ tm.assert_numpy_array_equal(result[1], missing)
234
+
235
+ @pytest.mark.parametrize("method", ["pad", "backfill", "nearest"])
236
+ def test_get_indexer_with_method_numeric_vs_bool(self, method):
237
+ left = Index([1, 2, 3])
238
+ right = Index([True, False])
239
+
240
+ with pytest.raises(TypeError, match="Cannot compare"):
241
+ left.get_indexer(right, method=method)
242
+
243
+ with pytest.raises(TypeError, match="Cannot compare"):
244
+ right.get_indexer(left, method=method)
245
+
246
+ def test_get_indexer_numeric_vs_bool(self):
247
+ left = Index([1, 2, 3])
248
+ right = Index([True, False])
249
+
250
+ res = left.get_indexer(right)
251
+ expected = -1 * np.ones(len(right), dtype=np.intp)
252
+ tm.assert_numpy_array_equal(res, expected)
253
+
254
+ res = right.get_indexer(left)
255
+ expected = -1 * np.ones(len(left), dtype=np.intp)
256
+ tm.assert_numpy_array_equal(res, expected)
257
+
258
+ res = left.get_indexer_non_unique(right)[0]
259
+ expected = -1 * np.ones(len(right), dtype=np.intp)
260
+ tm.assert_numpy_array_equal(res, expected)
261
+
262
+ res = right.get_indexer_non_unique(left)[0]
263
+ expected = -1 * np.ones(len(left), dtype=np.intp)
264
+ tm.assert_numpy_array_equal(res, expected)
265
+
266
+ def test_get_indexer_float64(self):
267
+ idx = Index([0.0, 1.0, 2.0], dtype=np.float64)
268
+ tm.assert_numpy_array_equal(
269
+ idx.get_indexer(idx), np.array([0, 1, 2], dtype=np.intp)
270
+ )
271
+
272
+ target = [-0.1, 0.5, 1.1]
273
+ tm.assert_numpy_array_equal(
274
+ idx.get_indexer(target, "pad"), np.array([-1, 0, 1], dtype=np.intp)
275
+ )
276
+ tm.assert_numpy_array_equal(
277
+ idx.get_indexer(target, "backfill"), np.array([0, 1, 2], dtype=np.intp)
278
+ )
279
+ tm.assert_numpy_array_equal(
280
+ idx.get_indexer(target, "nearest"), np.array([0, 1, 1], dtype=np.intp)
281
+ )
282
+
283
+ def test_get_indexer_nan(self):
284
+ # GH#7820
285
+ result = Index([1, 2, np.nan], dtype=np.float64).get_indexer([np.nan])
286
+ expected = np.array([2], dtype=np.intp)
287
+ tm.assert_numpy_array_equal(result, expected)
288
+
289
+ def test_get_indexer_int64(self):
290
+ index = Index(range(0, 20, 2), dtype=np.int64)
291
+ target = Index(np.arange(10), dtype=np.int64)
292
+ indexer = index.get_indexer(target)
293
+ expected = np.array([0, -1, 1, -1, 2, -1, 3, -1, 4, -1], dtype=np.intp)
294
+ tm.assert_numpy_array_equal(indexer, expected)
295
+
296
+ target = Index(np.arange(10), dtype=np.int64)
297
+ indexer = index.get_indexer(target, method="pad")
298
+ expected = np.array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4], dtype=np.intp)
299
+ tm.assert_numpy_array_equal(indexer, expected)
300
+
301
+ target = Index(np.arange(10), dtype=np.int64)
302
+ indexer = index.get_indexer(target, method="backfill")
303
+ expected = np.array([0, 1, 1, 2, 2, 3, 3, 4, 4, 5], dtype=np.intp)
304
+ tm.assert_numpy_array_equal(indexer, expected)
305
+
306
+ def test_get_indexer_uint64(self, index_large):
307
+ target = Index(np.arange(10).astype("uint64") * 5 + 2**63)
308
+ indexer = index_large.get_indexer(target)
309
+ expected = np.array([0, -1, 1, 2, 3, 4, -1, -1, -1, -1], dtype=np.intp)
310
+ tm.assert_numpy_array_equal(indexer, expected)
311
+
312
+ target = Index(np.arange(10).astype("uint64") * 5 + 2**63)
313
+ indexer = index_large.get_indexer(target, method="pad")
314
+ expected = np.array([0, 0, 1, 2, 3, 4, 4, 4, 4, 4], dtype=np.intp)
315
+ tm.assert_numpy_array_equal(indexer, expected)
316
+
317
+ target = Index(np.arange(10).astype("uint64") * 5 + 2**63)
318
+ indexer = index_large.get_indexer(target, method="backfill")
319
+ expected = np.array([0, 1, 1, 2, 3, 4, -1, -1, -1, -1], dtype=np.intp)
320
+ tm.assert_numpy_array_equal(indexer, expected)
321
+
322
+ @pytest.mark.parametrize("val, val2", [(4, 5), (4, 4), (4, NA), (NA, NA)])
323
+ def test_get_loc_masked(self, val, val2, any_numeric_ea_and_arrow_dtype):
324
+ # GH#39133
325
+ idx = Index([1, 2, 3, val, val2], dtype=any_numeric_ea_and_arrow_dtype)
326
+ result = idx.get_loc(2)
327
+ assert result == 1
328
+
329
+ with pytest.raises(KeyError, match="9"):
330
+ idx.get_loc(9)
331
+
332
+ def test_get_loc_masked_na(self, any_numeric_ea_and_arrow_dtype):
333
+ # GH#39133
334
+ idx = Index([1, 2, NA], dtype=any_numeric_ea_and_arrow_dtype)
335
+ result = idx.get_loc(NA)
336
+ assert result == 2
337
+
338
+ idx = Index([1, 2, NA, NA], dtype=any_numeric_ea_and_arrow_dtype)
339
+ result = idx.get_loc(NA)
340
+ tm.assert_numpy_array_equal(result, np.array([False, False, True, True]))
341
+
342
+ idx = Index([1, 2, 3], dtype=any_numeric_ea_and_arrow_dtype)
343
+ with pytest.raises(KeyError, match="NA"):
344
+ idx.get_loc(NA)
345
+
346
+ def test_get_loc_masked_na_and_nan(self):
347
+ # GH#39133
348
+ idx = Index(
349
+ FloatingArray(
350
+ np.array([1, 2, 1, np.nan]), mask=np.array([False, False, True, False])
351
+ )
352
+ )
353
+ result = idx.get_loc(NA)
354
+ assert result == 2
355
+ result = idx.get_loc(np.nan)
356
+ assert result == 3
357
+
358
+ idx = Index(
359
+ FloatingArray(np.array([1, 2, 1.0]), mask=np.array([False, False, True]))
360
+ )
361
+ result = idx.get_loc(NA)
362
+ assert result == 2
363
+ with pytest.raises(KeyError, match="nan"):
364
+ idx.get_loc(np.nan)
365
+
366
+ idx = Index(
367
+ FloatingArray(
368
+ np.array([1, 2, np.nan]), mask=np.array([False, False, False])
369
+ )
370
+ )
371
+ result = idx.get_loc(np.nan)
372
+ assert result == 2
373
+ with pytest.raises(KeyError, match="NA"):
374
+ idx.get_loc(NA)
375
+
376
+ @pytest.mark.parametrize("val", [4, 2])
377
+ def test_get_indexer_masked_na(self, any_numeric_ea_and_arrow_dtype, val):
378
+ # GH#39133
379
+ idx = Index([1, 2, NA, 3, val], dtype=any_numeric_ea_and_arrow_dtype)
380
+ result = idx.get_indexer_for([1, NA, 5])
381
+ expected = np.array([0, 2, -1])
382
+ tm.assert_numpy_array_equal(result, expected, check_dtype=False)
383
+
384
+ @pytest.mark.parametrize("dtype", ["boolean", "bool[pyarrow]"])
385
+ def test_get_indexer_masked_na_boolean(self, dtype):
386
+ # GH#39133
387
+ if dtype == "bool[pyarrow]":
388
+ pytest.importorskip("pyarrow")
389
+ idx = Index([True, False, NA], dtype=dtype)
390
+ result = idx.get_loc(False)
391
+ assert result == 1
392
+ result = idx.get_loc(NA)
393
+ assert result == 2
394
+
395
+ def test_get_indexer_arrow_dictionary_target(self):
396
+ pa = pytest.importorskip("pyarrow")
397
+ target = Index(
398
+ ArrowExtensionArray(
399
+ pa.array([1, 2], type=pa.dictionary(pa.int8(), pa.int8()))
400
+ )
401
+ )
402
+ idx = Index([1])
403
+
404
+ result = idx.get_indexer(target)
405
+ expected = np.array([0, -1], dtype=np.int64)
406
+ tm.assert_numpy_array_equal(result, expected)
407
+
408
+ result_1, result_2 = idx.get_indexer_non_unique(target)
409
+ expected_1, expected_2 = np.array([0, -1], dtype=np.int64), np.array(
410
+ [1], dtype=np.int64
411
+ )
412
+ tm.assert_numpy_array_equal(result_1, expected_1)
413
+ tm.assert_numpy_array_equal(result_2, expected_2)
414
+
415
+
416
+ class TestWhere:
417
+ @pytest.mark.parametrize(
418
+ "index",
419
+ [
420
+ Index(np.arange(5, dtype="float64")),
421
+ Index(range(0, 20, 2), dtype=np.int64),
422
+ Index(np.arange(5, dtype="uint64")),
423
+ ],
424
+ )
425
+ def test_where(self, listlike_box, index):
426
+ cond = [True] * len(index)
427
+ expected = index
428
+ result = index.where(listlike_box(cond))
429
+
430
+ cond = [False] + [True] * (len(index) - 1)
431
+ expected = Index([index._na_value] + index[1:].tolist(), dtype=np.float64)
432
+ result = index.where(listlike_box(cond))
433
+ tm.assert_index_equal(result, expected)
434
+
435
+ def test_where_uint64(self):
436
+ idx = Index([0, 6, 2], dtype=np.uint64)
437
+ mask = np.array([False, True, False])
438
+ other = np.array([1], dtype=np.int64)
439
+
440
+ expected = Index([1, 6, 1], dtype=np.uint64)
441
+
442
+ result = idx.where(mask, other)
443
+ tm.assert_index_equal(result, expected)
444
+
445
+ result = idx.putmask(~mask, other)
446
+ tm.assert_index_equal(result, expected)
447
+
448
+ def test_where_infers_type_instead_of_trying_to_convert_string_to_float(self):
449
+ # GH 32413
450
+ index = Index([1, np.nan])
451
+ cond = index.notna()
452
+ other = Index(["a", "b"], dtype="string")
453
+
454
+ expected = Index([1.0, "b"])
455
+ result = index.where(cond, other)
456
+
457
+ tm.assert_index_equal(result, expected)
458
+
459
+
460
+ class TestTake:
461
+ @pytest.mark.parametrize("idx_dtype", [np.float64, np.int64, np.uint64])
462
+ def test_take_preserve_name(self, idx_dtype):
463
+ index = Index([1, 2, 3, 4], dtype=idx_dtype, name="foo")
464
+ taken = index.take([3, 0, 1])
465
+ assert index.name == taken.name
466
+
467
+ def test_take_fill_value_float64(self):
468
+ # GH 12631
469
+ idx = Index([1.0, 2.0, 3.0], name="xxx", dtype=np.float64)
470
+ result = idx.take(np.array([1, 0, -1]))
471
+ expected = Index([2.0, 1.0, 3.0], dtype=np.float64, name="xxx")
472
+ tm.assert_index_equal(result, expected)
473
+
474
+ # fill_value
475
+ result = idx.take(np.array([1, 0, -1]), fill_value=True)
476
+ expected = Index([2.0, 1.0, np.nan], dtype=np.float64, name="xxx")
477
+ tm.assert_index_equal(result, expected)
478
+
479
+ # allow_fill=False
480
+ result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True)
481
+ expected = Index([2.0, 1.0, 3.0], dtype=np.float64, name="xxx")
482
+ tm.assert_index_equal(result, expected)
483
+
484
+ msg = (
485
+ "When allow_fill=True and fill_value is not None, "
486
+ "all indices must be >= -1"
487
+ )
488
+ with pytest.raises(ValueError, match=msg):
489
+ idx.take(np.array([1, 0, -2]), fill_value=True)
490
+ with pytest.raises(ValueError, match=msg):
491
+ idx.take(np.array([1, 0, -5]), fill_value=True)
492
+
493
+ msg = "index -5 is out of bounds for (axis 0 with )?size 3"
494
+ with pytest.raises(IndexError, match=msg):
495
+ idx.take(np.array([1, -5]))
496
+
497
+ @pytest.mark.parametrize("dtype", [np.int64, np.uint64])
498
+ def test_take_fill_value_ints(self, dtype):
499
+ # see gh-12631
500
+ idx = Index([1, 2, 3], dtype=dtype, name="xxx")
501
+ result = idx.take(np.array([1, 0, -1]))
502
+ expected = Index([2, 1, 3], dtype=dtype, name="xxx")
503
+ tm.assert_index_equal(result, expected)
504
+
505
+ name = type(idx).__name__
506
+ msg = f"Unable to fill values because {name} cannot contain NA"
507
+
508
+ # fill_value=True
509
+ with pytest.raises(ValueError, match=msg):
510
+ idx.take(np.array([1, 0, -1]), fill_value=True)
511
+
512
+ # allow_fill=False
513
+ result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True)
514
+ expected = Index([2, 1, 3], dtype=dtype, name="xxx")
515
+ tm.assert_index_equal(result, expected)
516
+
517
+ with pytest.raises(ValueError, match=msg):
518
+ idx.take(np.array([1, 0, -2]), fill_value=True)
519
+ with pytest.raises(ValueError, match=msg):
520
+ idx.take(np.array([1, 0, -5]), fill_value=True)
521
+
522
+ msg = "index -5 is out of bounds for (axis 0 with )?size 3"
523
+ with pytest.raises(IndexError, match=msg):
524
+ idx.take(np.array([1, -5]))
525
+
526
+
527
+ class TestContains:
528
+ @pytest.mark.parametrize("dtype", [np.float64, np.int64, np.uint64])
529
+ def test_contains_none(self, dtype):
530
+ # GH#35788 should return False, not raise TypeError
531
+ index = Index([0, 1, 2, 3, 4], dtype=dtype)
532
+ assert None not in index
533
+
534
+ def test_contains_float64_nans(self):
535
+ index = Index([1.0, 2.0, np.nan], dtype=np.float64)
536
+ assert np.nan in index
537
+
538
+ def test_contains_float64_not_nans(self):
539
+ index = Index([1.0, 2.0, np.nan], dtype=np.float64)
540
+ assert 1.0 in index
541
+
542
+
543
+ class TestSliceLocs:
544
+ @pytest.mark.parametrize("dtype", [int, float])
545
+ def test_slice_locs(self, dtype):
546
+ index = Index(np.array([0, 1, 2, 5, 6, 7, 9, 10], dtype=dtype))
547
+ n = len(index)
548
+
549
+ assert index.slice_locs(start=2) == (2, n)
550
+ assert index.slice_locs(start=3) == (3, n)
551
+ assert index.slice_locs(3, 8) == (3, 6)
552
+ assert index.slice_locs(5, 10) == (3, n)
553
+ assert index.slice_locs(end=8) == (0, 6)
554
+ assert index.slice_locs(end=9) == (0, 7)
555
+
556
+ # reversed
557
+ index2 = index[::-1]
558
+ assert index2.slice_locs(8, 2) == (2, 6)
559
+ assert index2.slice_locs(7, 3) == (2, 5)
560
+
561
+ @pytest.mark.parametrize("dtype", [int, float])
562
+ def test_slice_locs_float_locs(self, dtype):
563
+ index = Index(np.array([0, 1, 2, 5, 6, 7, 9, 10], dtype=dtype))
564
+ n = len(index)
565
+ assert index.slice_locs(5.0, 10.0) == (3, n)
566
+ assert index.slice_locs(4.5, 10.5) == (3, 8)
567
+
568
+ index2 = index[::-1]
569
+ assert index2.slice_locs(8.5, 1.5) == (2, 6)
570
+ assert index2.slice_locs(10.5, -1) == (0, n)
571
+
572
+ @pytest.mark.parametrize("dtype", [int, float])
573
+ def test_slice_locs_dup_numeric(self, dtype):
574
+ index = Index(np.array([10, 12, 12, 14], dtype=dtype))
575
+ assert index.slice_locs(12, 12) == (1, 3)
576
+ assert index.slice_locs(11, 13) == (1, 3)
577
+
578
+ index2 = index[::-1]
579
+ assert index2.slice_locs(12, 12) == (1, 3)
580
+ assert index2.slice_locs(13, 11) == (1, 3)
581
+
582
+ def test_slice_locs_na(self):
583
+ index = Index([np.nan, 1, 2])
584
+ assert index.slice_locs(1) == (1, 3)
585
+ assert index.slice_locs(np.nan) == (0, 3)
586
+
587
+ index = Index([0, np.nan, np.nan, 1, 2])
588
+ assert index.slice_locs(np.nan) == (1, 5)
589
+
590
+ def test_slice_locs_na_raises(self):
591
+ index = Index([np.nan, 1, 2])
592
+ with pytest.raises(KeyError, match=""):
593
+ index.slice_locs(start=1.5)
594
+
595
+ with pytest.raises(KeyError, match=""):
596
+ index.slice_locs(end=1.5)
597
+
598
+
599
+ class TestGetSliceBounds:
600
+ @pytest.mark.parametrize("side, expected", [("left", 4), ("right", 5)])
601
+ def test_get_slice_bounds_within(self, side, expected):
602
+ index = Index(range(6))
603
+ result = index.get_slice_bound(4, side=side)
604
+ assert result == expected
605
+
606
+ @pytest.mark.parametrize("side", ["left", "right"])
607
+ @pytest.mark.parametrize("bound, expected", [(-1, 0), (10, 6)])
608
+ def test_get_slice_bounds_outside(self, side, expected, bound):
609
+ index = Index(range(6))
610
+ result = index.get_slice_bound(bound, side=side)
611
+ assert result == expected
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/numeric/test_join.py ADDED
@@ -0,0 +1,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ import pandas._testing as tm
5
+ from pandas.core.indexes.api import Index
6
+
7
+
8
+ class TestJoinInt64Index:
9
+ def test_join_non_unique(self):
10
+ left = Index([4, 4, 3, 3])
11
+
12
+ joined, lidx, ridx = left.join(left, return_indexers=True)
13
+
14
+ exp_joined = Index([3, 3, 3, 3, 4, 4, 4, 4])
15
+ tm.assert_index_equal(joined, exp_joined)
16
+
17
+ exp_lidx = np.array([2, 2, 3, 3, 0, 0, 1, 1], dtype=np.intp)
18
+ tm.assert_numpy_array_equal(lidx, exp_lidx)
19
+
20
+ exp_ridx = np.array([2, 3, 2, 3, 0, 1, 0, 1], dtype=np.intp)
21
+ tm.assert_numpy_array_equal(ridx, exp_ridx)
22
+
23
+ def test_join_inner(self):
24
+ index = Index(range(0, 20, 2), dtype=np.int64)
25
+ other = Index([7, 12, 25, 1, 2, 5], dtype=np.int64)
26
+ other_mono = Index([1, 2, 5, 7, 12, 25], dtype=np.int64)
27
+
28
+ # not monotonic
29
+ res, lidx, ridx = index.join(other, how="inner", return_indexers=True)
30
+
31
+ # no guarantee of sortedness, so sort for comparison purposes
32
+ ind = res.argsort()
33
+ res = res.take(ind)
34
+ lidx = lidx.take(ind)
35
+ ridx = ridx.take(ind)
36
+
37
+ eres = Index([2, 12], dtype=np.int64)
38
+ elidx = np.array([1, 6], dtype=np.intp)
39
+ eridx = np.array([4, 1], dtype=np.intp)
40
+
41
+ assert isinstance(res, Index) and res.dtype == np.int64
42
+ tm.assert_index_equal(res, eres)
43
+ tm.assert_numpy_array_equal(lidx, elidx)
44
+ tm.assert_numpy_array_equal(ridx, eridx)
45
+
46
+ # monotonic
47
+ res, lidx, ridx = index.join(other_mono, how="inner", return_indexers=True)
48
+
49
+ res2 = index.intersection(other_mono)
50
+ tm.assert_index_equal(res, res2)
51
+
52
+ elidx = np.array([1, 6], dtype=np.intp)
53
+ eridx = np.array([1, 4], dtype=np.intp)
54
+ assert isinstance(res, Index) and res.dtype == np.int64
55
+ tm.assert_index_equal(res, eres)
56
+ tm.assert_numpy_array_equal(lidx, elidx)
57
+ tm.assert_numpy_array_equal(ridx, eridx)
58
+
59
+ def test_join_left(self):
60
+ index = Index(range(0, 20, 2), dtype=np.int64)
61
+ other = Index([7, 12, 25, 1, 2, 5], dtype=np.int64)
62
+ other_mono = Index([1, 2, 5, 7, 12, 25], dtype=np.int64)
63
+
64
+ # not monotonic
65
+ res, lidx, ridx = index.join(other, how="left", return_indexers=True)
66
+ eres = index
67
+ eridx = np.array([-1, 4, -1, -1, -1, -1, 1, -1, -1, -1], dtype=np.intp)
68
+
69
+ assert isinstance(res, Index) and res.dtype == np.int64
70
+ tm.assert_index_equal(res, eres)
71
+ assert lidx is None
72
+ tm.assert_numpy_array_equal(ridx, eridx)
73
+
74
+ # monotonic
75
+ res, lidx, ridx = index.join(other_mono, how="left", return_indexers=True)
76
+ eridx = np.array([-1, 1, -1, -1, -1, -1, 4, -1, -1, -1], dtype=np.intp)
77
+ assert isinstance(res, Index) and res.dtype == np.int64
78
+ tm.assert_index_equal(res, eres)
79
+ assert lidx is None
80
+ tm.assert_numpy_array_equal(ridx, eridx)
81
+
82
+ # non-unique
83
+ idx = Index([1, 1, 2, 5])
84
+ idx2 = Index([1, 2, 5, 7, 9])
85
+ res, lidx, ridx = idx2.join(idx, how="left", return_indexers=True)
86
+ eres = Index([1, 1, 2, 5, 7, 9]) # 1 is in idx2, so it should be x2
87
+ eridx = np.array([0, 1, 2, 3, -1, -1], dtype=np.intp)
88
+ elidx = np.array([0, 0, 1, 2, 3, 4], dtype=np.intp)
89
+ tm.assert_index_equal(res, eres)
90
+ tm.assert_numpy_array_equal(lidx, elidx)
91
+ tm.assert_numpy_array_equal(ridx, eridx)
92
+
93
+ def test_join_right(self):
94
+ index = Index(range(0, 20, 2), dtype=np.int64)
95
+ other = Index([7, 12, 25, 1, 2, 5], dtype=np.int64)
96
+ other_mono = Index([1, 2, 5, 7, 12, 25], dtype=np.int64)
97
+
98
+ # not monotonic
99
+ res, lidx, ridx = index.join(other, how="right", return_indexers=True)
100
+ eres = other
101
+ elidx = np.array([-1, 6, -1, -1, 1, -1], dtype=np.intp)
102
+
103
+ assert isinstance(other, Index) and other.dtype == np.int64
104
+ tm.assert_index_equal(res, eres)
105
+ tm.assert_numpy_array_equal(lidx, elidx)
106
+ assert ridx is None
107
+
108
+ # monotonic
109
+ res, lidx, ridx = index.join(other_mono, how="right", return_indexers=True)
110
+ eres = other_mono
111
+ elidx = np.array([-1, 1, -1, -1, 6, -1], dtype=np.intp)
112
+ assert isinstance(other, Index) and other.dtype == np.int64
113
+ tm.assert_index_equal(res, eres)
114
+ tm.assert_numpy_array_equal(lidx, elidx)
115
+ assert ridx is None
116
+
117
+ # non-unique
118
+ idx = Index([1, 1, 2, 5])
119
+ idx2 = Index([1, 2, 5, 7, 9])
120
+ res, lidx, ridx = idx.join(idx2, how="right", return_indexers=True)
121
+ eres = Index([1, 1, 2, 5, 7, 9]) # 1 is in idx2, so it should be x2
122
+ elidx = np.array([0, 1, 2, 3, -1, -1], dtype=np.intp)
123
+ eridx = np.array([0, 0, 1, 2, 3, 4], dtype=np.intp)
124
+ tm.assert_index_equal(res, eres)
125
+ tm.assert_numpy_array_equal(lidx, elidx)
126
+ tm.assert_numpy_array_equal(ridx, eridx)
127
+
128
+ def test_join_non_int_index(self):
129
+ index = Index(range(0, 20, 2), dtype=np.int64)
130
+ other = Index([3, 6, 7, 8, 10], dtype=object)
131
+
132
+ outer = index.join(other, how="outer")
133
+ outer2 = other.join(index, how="outer")
134
+ expected = Index([0, 2, 3, 4, 6, 7, 8, 10, 12, 14, 16, 18])
135
+ tm.assert_index_equal(outer, outer2)
136
+ tm.assert_index_equal(outer, expected)
137
+
138
+ inner = index.join(other, how="inner")
139
+ inner2 = other.join(index, how="inner")
140
+ expected = Index([6, 8, 10])
141
+ tm.assert_index_equal(inner, inner2)
142
+ tm.assert_index_equal(inner, expected)
143
+
144
+ left = index.join(other, how="left")
145
+ tm.assert_index_equal(left, index.astype(object))
146
+
147
+ left2 = other.join(index, how="left")
148
+ tm.assert_index_equal(left2, other)
149
+
150
+ right = index.join(other, how="right")
151
+ tm.assert_index_equal(right, other)
152
+
153
+ right2 = other.join(index, how="right")
154
+ tm.assert_index_equal(right2, index.astype(object))
155
+
156
+ def test_join_outer(self):
157
+ index = Index(range(0, 20, 2), dtype=np.int64)
158
+ other = Index([7, 12, 25, 1, 2, 5], dtype=np.int64)
159
+ other_mono = Index([1, 2, 5, 7, 12, 25], dtype=np.int64)
160
+
161
+ # not monotonic
162
+ # guarantee of sortedness
163
+ res, lidx, ridx = index.join(other, how="outer", return_indexers=True)
164
+ noidx_res = index.join(other, how="outer")
165
+ tm.assert_index_equal(res, noidx_res)
166
+
167
+ eres = Index([0, 1, 2, 4, 5, 6, 7, 8, 10, 12, 14, 16, 18, 25], dtype=np.int64)
168
+ elidx = np.array([0, -1, 1, 2, -1, 3, -1, 4, 5, 6, 7, 8, 9, -1], dtype=np.intp)
169
+ eridx = np.array(
170
+ [-1, 3, 4, -1, 5, -1, 0, -1, -1, 1, -1, -1, -1, 2], dtype=np.intp
171
+ )
172
+
173
+ assert isinstance(res, Index) and res.dtype == np.int64
174
+ tm.assert_index_equal(res, eres)
175
+ tm.assert_numpy_array_equal(lidx, elidx)
176
+ tm.assert_numpy_array_equal(ridx, eridx)
177
+
178
+ # monotonic
179
+ res, lidx, ridx = index.join(other_mono, how="outer", return_indexers=True)
180
+ noidx_res = index.join(other_mono, how="outer")
181
+ tm.assert_index_equal(res, noidx_res)
182
+
183
+ elidx = np.array([0, -1, 1, 2, -1, 3, -1, 4, 5, 6, 7, 8, 9, -1], dtype=np.intp)
184
+ eridx = np.array(
185
+ [-1, 0, 1, -1, 2, -1, 3, -1, -1, 4, -1, -1, -1, 5], dtype=np.intp
186
+ )
187
+ assert isinstance(res, Index) and res.dtype == np.int64
188
+ tm.assert_index_equal(res, eres)
189
+ tm.assert_numpy_array_equal(lidx, elidx)
190
+ tm.assert_numpy_array_equal(ridx, eridx)
191
+
192
+
193
+ class TestJoinUInt64Index:
194
+ @pytest.fixture
195
+ def index_large(self):
196
+ # large values used in TestUInt64Index where no compat needed with int64/float64
197
+ large = [2**63, 2**63 + 10, 2**63 + 15, 2**63 + 20, 2**63 + 25]
198
+ return Index(large, dtype=np.uint64)
199
+
200
+ def test_join_inner(self, index_large):
201
+ other = Index(2**63 + np.array([7, 12, 25, 1, 2, 10], dtype="uint64"))
202
+ other_mono = Index(2**63 + np.array([1, 2, 7, 10, 12, 25], dtype="uint64"))
203
+
204
+ # not monotonic
205
+ res, lidx, ridx = index_large.join(other, how="inner", return_indexers=True)
206
+
207
+ # no guarantee of sortedness, so sort for comparison purposes
208
+ ind = res.argsort()
209
+ res = res.take(ind)
210
+ lidx = lidx.take(ind)
211
+ ridx = ridx.take(ind)
212
+
213
+ eres = Index(2**63 + np.array([10, 25], dtype="uint64"))
214
+ elidx = np.array([1, 4], dtype=np.intp)
215
+ eridx = np.array([5, 2], dtype=np.intp)
216
+
217
+ assert isinstance(res, Index) and res.dtype == np.uint64
218
+ tm.assert_index_equal(res, eres)
219
+ tm.assert_numpy_array_equal(lidx, elidx)
220
+ tm.assert_numpy_array_equal(ridx, eridx)
221
+
222
+ # monotonic
223
+ res, lidx, ridx = index_large.join(
224
+ other_mono, how="inner", return_indexers=True
225
+ )
226
+
227
+ res2 = index_large.intersection(other_mono)
228
+ tm.assert_index_equal(res, res2)
229
+
230
+ elidx = np.array([1, 4], dtype=np.intp)
231
+ eridx = np.array([3, 5], dtype=np.intp)
232
+
233
+ assert isinstance(res, Index) and res.dtype == np.uint64
234
+ tm.assert_index_equal(res, eres)
235
+ tm.assert_numpy_array_equal(lidx, elidx)
236
+ tm.assert_numpy_array_equal(ridx, eridx)
237
+
238
+ def test_join_left(self, index_large):
239
+ other = Index(2**63 + np.array([7, 12, 25, 1, 2, 10], dtype="uint64"))
240
+ other_mono = Index(2**63 + np.array([1, 2, 7, 10, 12, 25], dtype="uint64"))
241
+
242
+ # not monotonic
243
+ res, lidx, ridx = index_large.join(other, how="left", return_indexers=True)
244
+ eres = index_large
245
+ eridx = np.array([-1, 5, -1, -1, 2], dtype=np.intp)
246
+
247
+ assert isinstance(res, Index) and res.dtype == np.uint64
248
+ tm.assert_index_equal(res, eres)
249
+ assert lidx is None
250
+ tm.assert_numpy_array_equal(ridx, eridx)
251
+
252
+ # monotonic
253
+ res, lidx, ridx = index_large.join(other_mono, how="left", return_indexers=True)
254
+ eridx = np.array([-1, 3, -1, -1, 5], dtype=np.intp)
255
+
256
+ assert isinstance(res, Index) and res.dtype == np.uint64
257
+ tm.assert_index_equal(res, eres)
258
+ assert lidx is None
259
+ tm.assert_numpy_array_equal(ridx, eridx)
260
+
261
+ # non-unique
262
+ idx = Index(2**63 + np.array([1, 1, 2, 5], dtype="uint64"))
263
+ idx2 = Index(2**63 + np.array([1, 2, 5, 7, 9], dtype="uint64"))
264
+ res, lidx, ridx = idx2.join(idx, how="left", return_indexers=True)
265
+
266
+ # 1 is in idx2, so it should be x2
267
+ eres = Index(2**63 + np.array([1, 1, 2, 5, 7, 9], dtype="uint64"))
268
+ eridx = np.array([0, 1, 2, 3, -1, -1], dtype=np.intp)
269
+ elidx = np.array([0, 0, 1, 2, 3, 4], dtype=np.intp)
270
+
271
+ tm.assert_index_equal(res, eres)
272
+ tm.assert_numpy_array_equal(lidx, elidx)
273
+ tm.assert_numpy_array_equal(ridx, eridx)
274
+
275
+ def test_join_right(self, index_large):
276
+ other = Index(2**63 + np.array([7, 12, 25, 1, 2, 10], dtype="uint64"))
277
+ other_mono = Index(2**63 + np.array([1, 2, 7, 10, 12, 25], dtype="uint64"))
278
+
279
+ # not monotonic
280
+ res, lidx, ridx = index_large.join(other, how="right", return_indexers=True)
281
+ eres = other
282
+ elidx = np.array([-1, -1, 4, -1, -1, 1], dtype=np.intp)
283
+
284
+ tm.assert_numpy_array_equal(lidx, elidx)
285
+ assert isinstance(other, Index) and other.dtype == np.uint64
286
+ tm.assert_index_equal(res, eres)
287
+ assert ridx is None
288
+
289
+ # monotonic
290
+ res, lidx, ridx = index_large.join(
291
+ other_mono, how="right", return_indexers=True
292
+ )
293
+ eres = other_mono
294
+ elidx = np.array([-1, -1, -1, 1, -1, 4], dtype=np.intp)
295
+
296
+ assert isinstance(other, Index) and other.dtype == np.uint64
297
+ tm.assert_numpy_array_equal(lidx, elidx)
298
+ tm.assert_index_equal(res, eres)
299
+ assert ridx is None
300
+
301
+ # non-unique
302
+ idx = Index(2**63 + np.array([1, 1, 2, 5], dtype="uint64"))
303
+ idx2 = Index(2**63 + np.array([1, 2, 5, 7, 9], dtype="uint64"))
304
+ res, lidx, ridx = idx.join(idx2, how="right", return_indexers=True)
305
+
306
+ # 1 is in idx2, so it should be x2
307
+ eres = Index(2**63 + np.array([1, 1, 2, 5, 7, 9], dtype="uint64"))
308
+ elidx = np.array([0, 1, 2, 3, -1, -1], dtype=np.intp)
309
+ eridx = np.array([0, 0, 1, 2, 3, 4], dtype=np.intp)
310
+
311
+ tm.assert_index_equal(res, eres)
312
+ tm.assert_numpy_array_equal(lidx, elidx)
313
+ tm.assert_numpy_array_equal(ridx, eridx)
314
+
315
+ def test_join_non_int_index(self, index_large):
316
+ other = Index(
317
+ 2**63 + np.array([1, 5, 7, 10, 20], dtype="uint64"), dtype=object
318
+ )
319
+
320
+ outer = index_large.join(other, how="outer")
321
+ outer2 = other.join(index_large, how="outer")
322
+ expected = Index(
323
+ 2**63 + np.array([0, 1, 5, 7, 10, 15, 20, 25], dtype="uint64")
324
+ )
325
+ tm.assert_index_equal(outer, outer2)
326
+ tm.assert_index_equal(outer, expected)
327
+
328
+ inner = index_large.join(other, how="inner")
329
+ inner2 = other.join(index_large, how="inner")
330
+ expected = Index(2**63 + np.array([10, 20], dtype="uint64"))
331
+ tm.assert_index_equal(inner, inner2)
332
+ tm.assert_index_equal(inner, expected)
333
+
334
+ left = index_large.join(other, how="left")
335
+ tm.assert_index_equal(left, index_large.astype(object))
336
+
337
+ left2 = other.join(index_large, how="left")
338
+ tm.assert_index_equal(left2, other)
339
+
340
+ right = index_large.join(other, how="right")
341
+ tm.assert_index_equal(right, other)
342
+
343
+ right2 = other.join(index_large, how="right")
344
+ tm.assert_index_equal(right2, index_large.astype(object))
345
+
346
+ def test_join_outer(self, index_large):
347
+ other = Index(2**63 + np.array([7, 12, 25, 1, 2, 10], dtype="uint64"))
348
+ other_mono = Index(2**63 + np.array([1, 2, 7, 10, 12, 25], dtype="uint64"))
349
+
350
+ # not monotonic
351
+ # guarantee of sortedness
352
+ res, lidx, ridx = index_large.join(other, how="outer", return_indexers=True)
353
+ noidx_res = index_large.join(other, how="outer")
354
+ tm.assert_index_equal(res, noidx_res)
355
+
356
+ eres = Index(
357
+ 2**63 + np.array([0, 1, 2, 7, 10, 12, 15, 20, 25], dtype="uint64")
358
+ )
359
+ elidx = np.array([0, -1, -1, -1, 1, -1, 2, 3, 4], dtype=np.intp)
360
+ eridx = np.array([-1, 3, 4, 0, 5, 1, -1, -1, 2], dtype=np.intp)
361
+
362
+ assert isinstance(res, Index) and res.dtype == np.uint64
363
+ tm.assert_index_equal(res, eres)
364
+ tm.assert_numpy_array_equal(lidx, elidx)
365
+ tm.assert_numpy_array_equal(ridx, eridx)
366
+
367
+ # monotonic
368
+ res, lidx, ridx = index_large.join(
369
+ other_mono, how="outer", return_indexers=True
370
+ )
371
+ noidx_res = index_large.join(other_mono, how="outer")
372
+ tm.assert_index_equal(res, noidx_res)
373
+
374
+ elidx = np.array([0, -1, -1, -1, 1, -1, 2, 3, 4], dtype=np.intp)
375
+ eridx = np.array([-1, 0, 1, 2, 3, 4, -1, -1, 5], dtype=np.intp)
376
+
377
+ assert isinstance(res, Index) and res.dtype == np.uint64
378
+ tm.assert_index_equal(res, eres)
379
+ tm.assert_numpy_array_equal(lidx, elidx)
380
+ tm.assert_numpy_array_equal(ridx, eridx)
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/numeric/test_numeric.py ADDED
@@ -0,0 +1,551 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from pandas.tests.indexes.common import NumericBase
11
+
12
+
13
+ class TestFloatNumericIndex(NumericBase):
14
+ _index_cls = Index
15
+
16
+ @pytest.fixture(params=[np.float64, np.float32])
17
+ def dtype(self, request):
18
+ return request.param
19
+
20
+ @pytest.fixture
21
+ def simple_index(self, dtype):
22
+ values = np.arange(5, dtype=dtype)
23
+ return self._index_cls(values)
24
+
25
+ @pytest.fixture(
26
+ params=[
27
+ [1.5, 2, 3, 4, 5],
28
+ [0.0, 2.5, 5.0, 7.5, 10.0],
29
+ [5, 4, 3, 2, 1.5],
30
+ [10.0, 7.5, 5.0, 2.5, 0.0],
31
+ ],
32
+ ids=["mixed", "float", "mixed_dec", "float_dec"],
33
+ )
34
+ def index(self, request, dtype):
35
+ return self._index_cls(request.param, dtype=dtype)
36
+
37
+ @pytest.fixture
38
+ def mixed_index(self, dtype):
39
+ return self._index_cls([1.5, 2, 3, 4, 5], dtype=dtype)
40
+
41
+ @pytest.fixture
42
+ def float_index(self, dtype):
43
+ return self._index_cls([0.0, 2.5, 5.0, 7.5, 10.0], dtype=dtype)
44
+
45
+ def test_repr_roundtrip(self, index):
46
+ tm.assert_index_equal(eval(repr(index)), index, exact=True)
47
+
48
+ def check_coerce(self, a, b, is_float_index=True):
49
+ assert a.equals(b)
50
+ tm.assert_index_equal(a, b, exact=False)
51
+ if is_float_index:
52
+ assert isinstance(b, self._index_cls)
53
+ else:
54
+ assert type(b) is Index
55
+
56
+ def test_constructor_from_list_no_dtype(self):
57
+ index = self._index_cls([1.5, 2.5, 3.5])
58
+ assert index.dtype == np.float64
59
+
60
+ def test_constructor(self, dtype):
61
+ index_cls = self._index_cls
62
+
63
+ # explicit construction
64
+ index = index_cls([1, 2, 3, 4, 5], dtype=dtype)
65
+
66
+ assert isinstance(index, index_cls)
67
+ assert index.dtype == dtype
68
+
69
+ expected = np.array([1, 2, 3, 4, 5], dtype=dtype)
70
+ tm.assert_numpy_array_equal(index.values, expected)
71
+
72
+ index = index_cls(np.array([1, 2, 3, 4, 5]), dtype=dtype)
73
+ assert isinstance(index, index_cls)
74
+ assert index.dtype == dtype
75
+
76
+ index = index_cls([1.0, 2, 3, 4, 5], dtype=dtype)
77
+ assert isinstance(index, index_cls)
78
+ assert index.dtype == dtype
79
+
80
+ index = index_cls(np.array([1.0, 2, 3, 4, 5]), dtype=dtype)
81
+ assert isinstance(index, index_cls)
82
+ assert index.dtype == dtype
83
+
84
+ index = index_cls([1.0, 2, 3, 4, 5], dtype=dtype)
85
+ assert isinstance(index, index_cls)
86
+ assert index.dtype == dtype
87
+
88
+ index = index_cls(np.array([1.0, 2, 3, 4, 5]), dtype=dtype)
89
+ assert isinstance(index, index_cls)
90
+ assert index.dtype == dtype
91
+
92
+ # nan handling
93
+ result = index_cls([np.nan, np.nan], dtype=dtype)
94
+ assert pd.isna(result.values).all()
95
+
96
+ result = index_cls(np.array([np.nan]), dtype=dtype)
97
+ assert pd.isna(result.values).all()
98
+
99
+ def test_constructor_invalid(self):
100
+ index_cls = self._index_cls
101
+ cls_name = index_cls.__name__
102
+ # invalid
103
+ msg = (
104
+ rf"{cls_name}\(\.\.\.\) must be called with a collection of "
105
+ r"some kind, 0\.0 was passed"
106
+ )
107
+ with pytest.raises(TypeError, match=msg):
108
+ index_cls(0.0)
109
+
110
+ def test_constructor_coerce(self, mixed_index, float_index):
111
+ self.check_coerce(mixed_index, Index([1.5, 2, 3, 4, 5]))
112
+ self.check_coerce(float_index, Index(np.arange(5) * 2.5))
113
+
114
+ result = Index(np.array(np.arange(5) * 2.5, dtype=object))
115
+ assert result.dtype == object # as of 2.0 to match Series
116
+ self.check_coerce(float_index, result.astype("float64"))
117
+
118
+ def test_constructor_explicit(self, mixed_index, float_index):
119
+ # these don't auto convert
120
+ self.check_coerce(
121
+ float_index, Index((np.arange(5) * 2.5), dtype=object), is_float_index=False
122
+ )
123
+ self.check_coerce(
124
+ mixed_index, Index([1.5, 2, 3, 4, 5], dtype=object), is_float_index=False
125
+ )
126
+
127
+ def test_type_coercion_fail(self, any_int_numpy_dtype):
128
+ # see gh-15832
129
+ msg = "Trying to coerce float values to integers"
130
+ with pytest.raises(ValueError, match=msg):
131
+ Index([1, 2, 3.5], dtype=any_int_numpy_dtype)
132
+
133
+ def test_equals_numeric(self):
134
+ index_cls = self._index_cls
135
+
136
+ idx = index_cls([1.0, 2.0])
137
+ assert idx.equals(idx)
138
+ assert idx.identical(idx)
139
+
140
+ idx2 = index_cls([1.0, 2.0])
141
+ assert idx.equals(idx2)
142
+
143
+ idx = index_cls([1.0, np.nan])
144
+ assert idx.equals(idx)
145
+ assert idx.identical(idx)
146
+
147
+ idx2 = index_cls([1.0, np.nan])
148
+ assert idx.equals(idx2)
149
+
150
+ @pytest.mark.parametrize(
151
+ "other",
152
+ (
153
+ Index([1, 2], dtype=np.int64),
154
+ Index([1.0, 2.0], dtype=object),
155
+ Index([1, 2], dtype=object),
156
+ ),
157
+ )
158
+ def test_equals_numeric_other_index_type(self, other):
159
+ idx = self._index_cls([1.0, 2.0])
160
+ assert idx.equals(other)
161
+ assert other.equals(idx)
162
+
163
+ @pytest.mark.parametrize(
164
+ "vals",
165
+ [
166
+ pd.date_range("2016-01-01", periods=3),
167
+ pd.timedelta_range("1 Day", periods=3),
168
+ ],
169
+ )
170
+ def test_lookups_datetimelike_values(self, vals, dtype):
171
+ # If we have datetime64 or timedelta64 values, make sure they are
172
+ # wrapped correctly GH#31163
173
+ ser = Series(vals, index=range(3, 6))
174
+ ser.index = ser.index.astype(dtype)
175
+
176
+ expected = vals[1]
177
+
178
+ result = ser[4.0]
179
+ assert isinstance(result, type(expected)) and result == expected
180
+ result = ser[4]
181
+ assert isinstance(result, type(expected)) and result == expected
182
+
183
+ result = ser.loc[4.0]
184
+ assert isinstance(result, type(expected)) and result == expected
185
+ result = ser.loc[4]
186
+ assert isinstance(result, type(expected)) and result == expected
187
+
188
+ result = ser.at[4.0]
189
+ assert isinstance(result, type(expected)) and result == expected
190
+ # GH#31329 .at[4] should cast to 4.0, matching .loc behavior
191
+ result = ser.at[4]
192
+ assert isinstance(result, type(expected)) and result == expected
193
+
194
+ result = ser.iloc[1]
195
+ assert isinstance(result, type(expected)) and result == expected
196
+
197
+ result = ser.iat[1]
198
+ assert isinstance(result, type(expected)) and result == expected
199
+
200
+ def test_doesnt_contain_all_the_things(self):
201
+ idx = self._index_cls([np.nan])
202
+ assert not idx.isin([0]).item()
203
+ assert not idx.isin([1]).item()
204
+ assert idx.isin([np.nan]).item()
205
+
206
+ def test_nan_multiple_containment(self):
207
+ index_cls = self._index_cls
208
+
209
+ idx = index_cls([1.0, np.nan])
210
+ tm.assert_numpy_array_equal(idx.isin([1.0]), np.array([True, False]))
211
+ tm.assert_numpy_array_equal(idx.isin([2.0, np.pi]), np.array([False, False]))
212
+ tm.assert_numpy_array_equal(idx.isin([np.nan]), np.array([False, True]))
213
+ tm.assert_numpy_array_equal(idx.isin([1.0, np.nan]), np.array([True, True]))
214
+ idx = index_cls([1.0, 2.0])
215
+ tm.assert_numpy_array_equal(idx.isin([np.nan]), np.array([False, False]))
216
+
217
+ def test_fillna_float64(self):
218
+ index_cls = self._index_cls
219
+ # GH 11343
220
+ idx = Index([1.0, np.nan, 3.0], dtype=float, name="x")
221
+ # can't downcast
222
+ exp = Index([1.0, 0.1, 3.0], name="x")
223
+ tm.assert_index_equal(idx.fillna(0.1), exp, exact=True)
224
+
225
+ # downcast
226
+ exp = index_cls([1.0, 2.0, 3.0], name="x")
227
+ tm.assert_index_equal(idx.fillna(2), exp)
228
+
229
+ # object
230
+ exp = Index([1.0, "obj", 3.0], name="x")
231
+ tm.assert_index_equal(idx.fillna("obj"), exp, exact=True)
232
+
233
+
234
+ class NumericInt(NumericBase):
235
+ _index_cls = Index
236
+
237
+ def test_is_monotonic(self):
238
+ index_cls = self._index_cls
239
+
240
+ index = index_cls([1, 2, 3, 4])
241
+ assert index.is_monotonic_increasing is True
242
+ assert index.is_monotonic_increasing is True
243
+ assert index._is_strictly_monotonic_increasing is True
244
+ assert index.is_monotonic_decreasing is False
245
+ assert index._is_strictly_monotonic_decreasing is False
246
+
247
+ index = index_cls([4, 3, 2, 1])
248
+ assert index.is_monotonic_increasing is False
249
+ assert index._is_strictly_monotonic_increasing is False
250
+ assert index._is_strictly_monotonic_decreasing is True
251
+
252
+ index = index_cls([1])
253
+ assert index.is_monotonic_increasing is True
254
+ assert index.is_monotonic_increasing is True
255
+ assert index.is_monotonic_decreasing is True
256
+ assert index._is_strictly_monotonic_increasing is True
257
+ assert index._is_strictly_monotonic_decreasing is True
258
+
259
+ def test_is_strictly_monotonic(self):
260
+ index_cls = self._index_cls
261
+
262
+ index = index_cls([1, 1, 2, 3])
263
+ assert index.is_monotonic_increasing is True
264
+ assert index._is_strictly_monotonic_increasing is False
265
+
266
+ index = index_cls([3, 2, 1, 1])
267
+ assert index.is_monotonic_decreasing is True
268
+ assert index._is_strictly_monotonic_decreasing is False
269
+
270
+ index = index_cls([1, 1])
271
+ assert index.is_monotonic_increasing
272
+ assert index.is_monotonic_decreasing
273
+ assert not index._is_strictly_monotonic_increasing
274
+ assert not index._is_strictly_monotonic_decreasing
275
+
276
+ def test_logical_compat(self, simple_index):
277
+ idx = simple_index
278
+ assert idx.all() == idx.values.all()
279
+ assert idx.any() == idx.values.any()
280
+
281
+ def test_identical(self, simple_index, dtype):
282
+ index = simple_index
283
+
284
+ idx = Index(index.copy())
285
+ assert idx.identical(index)
286
+
287
+ same_values_different_type = Index(idx, dtype=object)
288
+ assert not idx.identical(same_values_different_type)
289
+
290
+ idx = index.astype(dtype=object)
291
+ idx = idx.rename("foo")
292
+ same_values = Index(idx, dtype=object)
293
+ assert same_values.identical(idx)
294
+
295
+ assert not idx.identical(index)
296
+ assert Index(same_values, name="foo", dtype=object).identical(idx)
297
+
298
+ assert not index.astype(dtype=object).identical(index.astype(dtype=dtype))
299
+
300
+ def test_cant_or_shouldnt_cast(self, dtype):
301
+ msg = r"invalid literal for int\(\) with base 10: 'foo'"
302
+
303
+ # can't
304
+ data = ["foo", "bar", "baz"]
305
+ with pytest.raises(ValueError, match=msg):
306
+ self._index_cls(data, dtype=dtype)
307
+
308
+ def test_view_index(self, simple_index):
309
+ index = simple_index
310
+ index.view(Index)
311
+
312
+ def test_prevent_casting(self, simple_index):
313
+ index = simple_index
314
+ result = index.astype("O")
315
+ assert result.dtype == np.object_
316
+
317
+
318
+ class TestIntNumericIndex(NumericInt):
319
+ @pytest.fixture(params=[np.int64, np.int32, np.int16, np.int8])
320
+ def dtype(self, request):
321
+ return request.param
322
+
323
+ @pytest.fixture
324
+ def simple_index(self, dtype):
325
+ return self._index_cls(range(0, 20, 2), dtype=dtype)
326
+
327
+ @pytest.fixture(
328
+ params=[range(0, 20, 2), range(19, -1, -1)], ids=["index_inc", "index_dec"]
329
+ )
330
+ def index(self, request, dtype):
331
+ return self._index_cls(request.param, dtype=dtype)
332
+
333
+ def test_constructor_from_list_no_dtype(self):
334
+ index = self._index_cls([1, 2, 3])
335
+ assert index.dtype == np.int64
336
+
337
+ def test_constructor(self, dtype):
338
+ index_cls = self._index_cls
339
+
340
+ # scalar raise Exception
341
+ msg = (
342
+ rf"{index_cls.__name__}\(\.\.\.\) must be called with a collection of some "
343
+ "kind, 5 was passed"
344
+ )
345
+ with pytest.raises(TypeError, match=msg):
346
+ index_cls(5)
347
+
348
+ # copy
349
+ # pass list, coerce fine
350
+ index = index_cls([-5, 0, 1, 2], dtype=dtype)
351
+ arr = index.values
352
+ new_index = index_cls(arr, copy=True)
353
+ tm.assert_index_equal(new_index, index, exact=True)
354
+ val = arr[0] + 3000
355
+
356
+ # this should not change index
357
+ arr[0] = val
358
+ assert new_index[0] != val
359
+
360
+ if dtype == np.int64:
361
+ # pass list, coerce fine
362
+ index = index_cls([-5, 0, 1, 2], dtype=dtype)
363
+ expected = Index([-5, 0, 1, 2], dtype=dtype)
364
+ tm.assert_index_equal(index, expected)
365
+
366
+ # from iterable
367
+ index = index_cls(iter([-5, 0, 1, 2]), dtype=dtype)
368
+ expected = index_cls([-5, 0, 1, 2], dtype=dtype)
369
+ tm.assert_index_equal(index, expected, exact=True)
370
+
371
+ # interpret list-like
372
+ expected = index_cls([5, 0], dtype=dtype)
373
+ for cls in [Index, index_cls]:
374
+ for idx in [
375
+ cls([5, 0], dtype=dtype),
376
+ cls(np.array([5, 0]), dtype=dtype),
377
+ cls(Series([5, 0]), dtype=dtype),
378
+ ]:
379
+ tm.assert_index_equal(idx, expected)
380
+
381
+ def test_constructor_corner(self, dtype):
382
+ index_cls = self._index_cls
383
+
384
+ arr = np.array([1, 2, 3, 4], dtype=object)
385
+
386
+ index = index_cls(arr, dtype=dtype)
387
+ assert index.values.dtype == index.dtype
388
+ if dtype == np.int64:
389
+ without_dtype = Index(arr)
390
+ # as of 2.0 we do not infer a dtype when we get an object-dtype
391
+ # ndarray of numbers, matching Series behavior
392
+ assert without_dtype.dtype == object
393
+
394
+ tm.assert_index_equal(index, without_dtype.astype(np.int64))
395
+
396
+ # preventing casting
397
+ arr = np.array([1, "2", 3, "4"], dtype=object)
398
+ msg = "Trying to coerce float values to integers"
399
+ with pytest.raises(ValueError, match=msg):
400
+ index_cls(arr, dtype=dtype)
401
+
402
+ def test_constructor_coercion_signed_to_unsigned(
403
+ self,
404
+ any_unsigned_int_numpy_dtype,
405
+ ):
406
+ # see gh-15832
407
+ msg = "Trying to coerce negative values to unsigned integers"
408
+
409
+ with pytest.raises(OverflowError, match=msg):
410
+ Index([-1], dtype=any_unsigned_int_numpy_dtype)
411
+
412
+ def test_constructor_np_signed(self, any_signed_int_numpy_dtype):
413
+ # GH#47475
414
+ scalar = np.dtype(any_signed_int_numpy_dtype).type(1)
415
+ result = Index([scalar])
416
+ expected = Index([1], dtype=any_signed_int_numpy_dtype)
417
+ tm.assert_index_equal(result, expected, exact=True)
418
+
419
+ def test_constructor_np_unsigned(self, any_unsigned_int_numpy_dtype):
420
+ # GH#47475
421
+ scalar = np.dtype(any_unsigned_int_numpy_dtype).type(1)
422
+ result = Index([scalar])
423
+ expected = Index([1], dtype=any_unsigned_int_numpy_dtype)
424
+ tm.assert_index_equal(result, expected, exact=True)
425
+
426
+ def test_coerce_list(self):
427
+ # coerce things
428
+ arr = Index([1, 2, 3, 4])
429
+ assert isinstance(arr, self._index_cls)
430
+
431
+ # but not if explicit dtype passed
432
+ arr = Index([1, 2, 3, 4], dtype=object)
433
+ assert type(arr) is Index
434
+
435
+
436
+ class TestFloat16Index:
437
+ # float 16 indexes not supported
438
+ # GH 49535
439
+ _index_cls = Index
440
+
441
+ def test_constructor(self):
442
+ index_cls = self._index_cls
443
+ dtype = np.float16
444
+
445
+ msg = "float16 indexes are not supported"
446
+
447
+ # explicit construction
448
+ with pytest.raises(NotImplementedError, match=msg):
449
+ index_cls([1, 2, 3, 4, 5], dtype=dtype)
450
+
451
+ with pytest.raises(NotImplementedError, match=msg):
452
+ index_cls(np.array([1, 2, 3, 4, 5]), dtype=dtype)
453
+
454
+ with pytest.raises(NotImplementedError, match=msg):
455
+ index_cls([1.0, 2, 3, 4, 5], dtype=dtype)
456
+
457
+ with pytest.raises(NotImplementedError, match=msg):
458
+ index_cls(np.array([1.0, 2, 3, 4, 5]), dtype=dtype)
459
+
460
+ with pytest.raises(NotImplementedError, match=msg):
461
+ index_cls([1.0, 2, 3, 4, 5], dtype=dtype)
462
+
463
+ with pytest.raises(NotImplementedError, match=msg):
464
+ index_cls(np.array([1.0, 2, 3, 4, 5]), dtype=dtype)
465
+
466
+ # nan handling
467
+ with pytest.raises(NotImplementedError, match=msg):
468
+ index_cls([np.nan, np.nan], dtype=dtype)
469
+
470
+ with pytest.raises(NotImplementedError, match=msg):
471
+ index_cls(np.array([np.nan]), dtype=dtype)
472
+
473
+
474
+ class TestUIntNumericIndex(NumericInt):
475
+ @pytest.fixture(params=[np.uint64])
476
+ def dtype(self, request):
477
+ return request.param
478
+
479
+ @pytest.fixture
480
+ def simple_index(self, dtype):
481
+ # compat with shared Int64/Float64 tests
482
+ return self._index_cls(np.arange(5, dtype=dtype))
483
+
484
+ @pytest.fixture(
485
+ params=[
486
+ [2**63, 2**63 + 10, 2**63 + 15, 2**63 + 20, 2**63 + 25],
487
+ [2**63 + 25, 2**63 + 20, 2**63 + 15, 2**63 + 10, 2**63],
488
+ ],
489
+ ids=["index_inc", "index_dec"],
490
+ )
491
+ def index(self, request):
492
+ return self._index_cls(request.param, dtype=np.uint64)
493
+
494
+
495
+ @pytest.mark.parametrize(
496
+ "box",
497
+ [list, lambda x: np.array(x, dtype=object), lambda x: Index(x, dtype=object)],
498
+ )
499
+ def test_uint_index_does_not_convert_to_float64(box):
500
+ # https://github.com/pandas-dev/pandas/issues/28279
501
+ # https://github.com/pandas-dev/pandas/issues/28023
502
+ series = Series(
503
+ [0, 1, 2, 3, 4, 5],
504
+ index=[
505
+ 7606741985629028552,
506
+ 17876870360202815256,
507
+ 17876870360202815256,
508
+ 13106359306506049338,
509
+ 8991270399732411471,
510
+ 8991270399732411472,
511
+ ],
512
+ )
513
+
514
+ result = series.loc[box([7606741985629028552, 17876870360202815256])]
515
+
516
+ expected = Index(
517
+ [7606741985629028552, 17876870360202815256, 17876870360202815256],
518
+ dtype="uint64",
519
+ )
520
+ tm.assert_index_equal(result.index, expected)
521
+
522
+ tm.assert_equal(result, series.iloc[:3])
523
+
524
+
525
+ def test_float64_index_equals():
526
+ # https://github.com/pandas-dev/pandas/issues/35217
527
+ float_index = Index([1.0, 2, 3])
528
+ string_index = Index(["1", "2", "3"])
529
+
530
+ result = float_index.equals(string_index)
531
+ assert result is False
532
+
533
+ result = string_index.equals(float_index)
534
+ assert result is False
535
+
536
+
537
+ def test_map_dtype_inference_unsigned_to_signed():
538
+ # GH#44609 cases where we don't retain dtype
539
+ idx = Index([1, 2, 3], dtype=np.uint64)
540
+ result = idx.map(lambda x: -x)
541
+ expected = Index([-1, -2, -3], dtype=np.int64)
542
+ tm.assert_index_equal(result, expected)
543
+
544
+
545
+ def test_map_dtype_inference_overflows():
546
+ # GH#44609 case where we have to upcast
547
+ idx = Index(np.array([1, 2, 3], dtype=np.int8))
548
+ result = idx.map(lambda x: x * 1000)
549
+ # TODO: we could plausibly try to infer down to int16 here
550
+ expected = Index([1000, 2000, 3000], dtype=np.int64)
551
+ tm.assert_index_equal(result, expected)
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/numeric/test_setops.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import (
2
+ datetime,
3
+ timedelta,
4
+ )
5
+
6
+ import numpy as np
7
+ import pytest
8
+
9
+ import pandas._testing as tm
10
+ from pandas.core.indexes.api import (
11
+ Index,
12
+ RangeIndex,
13
+ )
14
+
15
+
16
+ @pytest.fixture
17
+ def index_large():
18
+ # large values used in TestUInt64Index where no compat needed with int64/float64
19
+ large = [2**63, 2**63 + 10, 2**63 + 15, 2**63 + 20, 2**63 + 25]
20
+ return Index(large, dtype=np.uint64)
21
+
22
+
23
+ class TestSetOps:
24
+ @pytest.mark.parametrize("dtype", ["f8", "u8", "i8"])
25
+ def test_union_non_numeric(self, dtype):
26
+ # corner case, non-numeric
27
+ index = Index(np.arange(5, dtype=dtype), dtype=dtype)
28
+ assert index.dtype == dtype
29
+
30
+ other = Index([datetime.now() + timedelta(i) for i in range(4)], dtype=object)
31
+ result = index.union(other)
32
+ expected = Index(np.concatenate((index, other)))
33
+ tm.assert_index_equal(result, expected)
34
+
35
+ result = other.union(index)
36
+ expected = Index(np.concatenate((other, index)))
37
+ tm.assert_index_equal(result, expected)
38
+
39
+ def test_intersection(self):
40
+ index = Index(range(5), dtype=np.int64)
41
+
42
+ other = Index([1, 2, 3, 4, 5])
43
+ result = index.intersection(other)
44
+ expected = Index(np.sort(np.intersect1d(index.values, other.values)))
45
+ tm.assert_index_equal(result, expected)
46
+
47
+ result = other.intersection(index)
48
+ expected = Index(
49
+ np.sort(np.asarray(np.intersect1d(index.values, other.values)))
50
+ )
51
+ tm.assert_index_equal(result, expected)
52
+
53
+ @pytest.mark.parametrize("dtype", ["int64", "uint64"])
54
+ def test_int_float_union_dtype(self, dtype):
55
+ # https://github.com/pandas-dev/pandas/issues/26778
56
+ # [u]int | float -> float
57
+ index = Index([0, 2, 3], dtype=dtype)
58
+ other = Index([0.5, 1.5], dtype=np.float64)
59
+ expected = Index([0.0, 0.5, 1.5, 2.0, 3.0], dtype=np.float64)
60
+ result = index.union(other)
61
+ tm.assert_index_equal(result, expected)
62
+
63
+ result = other.union(index)
64
+ tm.assert_index_equal(result, expected)
65
+
66
+ def test_range_float_union_dtype(self):
67
+ # https://github.com/pandas-dev/pandas/issues/26778
68
+ index = RangeIndex(start=0, stop=3)
69
+ other = Index([0.5, 1.5], dtype=np.float64)
70
+ result = index.union(other)
71
+ expected = Index([0.0, 0.5, 1, 1.5, 2.0], dtype=np.float64)
72
+ tm.assert_index_equal(result, expected)
73
+
74
+ result = other.union(index)
75
+ tm.assert_index_equal(result, expected)
76
+
77
+ def test_float64_index_difference(self):
78
+ # https://github.com/pandas-dev/pandas/issues/35217
79
+ float_index = Index([1.0, 2, 3])
80
+ string_index = Index(["1", "2", "3"])
81
+
82
+ result = float_index.difference(string_index)
83
+ tm.assert_index_equal(result, float_index)
84
+
85
+ result = string_index.difference(float_index)
86
+ tm.assert_index_equal(result, string_index)
87
+
88
+ def test_intersection_uint64_outside_int64_range(self, index_large):
89
+ other = Index([2**63, 2**63 + 5, 2**63 + 10, 2**63 + 15, 2**63 + 20])
90
+ result = index_large.intersection(other)
91
+ expected = Index(np.sort(np.intersect1d(index_large.values, other.values)))
92
+ tm.assert_index_equal(result, expected)
93
+
94
+ result = other.intersection(index_large)
95
+ expected = Index(
96
+ np.sort(np.asarray(np.intersect1d(index_large.values, other.values)))
97
+ )
98
+ tm.assert_index_equal(result, expected)
99
+
100
+ @pytest.mark.parametrize(
101
+ "index2,keeps_name",
102
+ [
103
+ (Index([4, 7, 6, 5, 3], name="index"), True),
104
+ (Index([4, 7, 6, 5, 3], name="other"), False),
105
+ ],
106
+ )
107
+ def test_intersection_monotonic(self, index2, keeps_name, sort):
108
+ index1 = Index([5, 3, 2, 4, 1], name="index")
109
+ expected = Index([5, 3, 4])
110
+
111
+ if keeps_name:
112
+ expected.name = "index"
113
+
114
+ result = index1.intersection(index2, sort=sort)
115
+ if sort is None:
116
+ expected = expected.sort_values()
117
+ tm.assert_index_equal(result, expected)
118
+
119
+ def test_symmetric_difference(self, sort):
120
+ # smoke
121
+ index1 = Index([5, 2, 3, 4], name="index1")
122
+ index2 = Index([2, 3, 4, 1])
123
+ result = index1.symmetric_difference(index2, sort=sort)
124
+ expected = Index([5, 1])
125
+ assert tm.equalContents(result, expected)
126
+ assert result.name is None
127
+ if sort is None:
128
+ expected = expected.sort_values()
129
+ tm.assert_index_equal(result, expected)
130
+
131
+
132
+ class TestSetOpsSort:
133
+ @pytest.mark.parametrize("slice_", [slice(None), slice(0)])
134
+ def test_union_sort_other_special(self, slice_):
135
+ # https://github.com/pandas-dev/pandas/issues/24959
136
+
137
+ idx = Index([1, 0, 2])
138
+ # default, sort=None
139
+ other = idx[slice_]
140
+ tm.assert_index_equal(idx.union(other), idx)
141
+ tm.assert_index_equal(other.union(idx), idx)
142
+
143
+ # sort=False
144
+ tm.assert_index_equal(idx.union(other, sort=False), idx)
145
+
146
+ @pytest.mark.parametrize("slice_", [slice(None), slice(0)])
147
+ def test_union_sort_special_true(self, slice_):
148
+ idx = Index([1, 0, 2])
149
+ # default, sort=None
150
+ other = idx[slice_]
151
+
152
+ result = idx.union(other, sort=True)
153
+ expected = Index([0, 1, 2])
154
+ tm.assert_index_equal(result, expected)
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/test_any_index.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ return
38
+ msg = "Index does not support mutable operations"
39
+ with pytest.raises(TypeError, match=msg):
40
+ index[0] = index[0]
41
+
42
+
43
+ def test_map_identity_mapping(index, request):
44
+ # GH#12766
45
+
46
+ result = index.map(lambda x: x)
47
+ if index.dtype == object and result.dtype == bool:
48
+ assert (index == result).all()
49
+ # TODO: could work that into the 'exact="equiv"'?
50
+ return # FIXME: doesn't belong in this file anymore!
51
+ tm.assert_index_equal(result, index, exact="equiv")
52
+
53
+
54
+ def test_wrong_number_names(index):
55
+ names = index.nlevels * ["apple", "banana", "carrot"]
56
+ with pytest.raises(ValueError, match="^Length"):
57
+ index.names = names
58
+
59
+
60
+ def test_view_preserves_name(index):
61
+ assert index.view().name == index.name
62
+
63
+
64
+ def test_ravel(index):
65
+ # GH#19956 ravel returning ndarray is deprecated, in 2.0 returns a view on self
66
+ res = index.ravel()
67
+ tm.assert_index_equal(res, index)
68
+
69
+
70
+ class TestConversion:
71
+ def test_to_series(self, index):
72
+ # assert that we are creating a copy of the index
73
+
74
+ ser = index.to_series()
75
+ assert ser.values is not index.values
76
+ assert ser.index is not index
77
+ assert ser.name == index.name
78
+
79
+ def test_to_series_with_arguments(self, index):
80
+ # GH#18699
81
+
82
+ # index kwarg
83
+ ser = index.to_series(index=index)
84
+
85
+ assert ser.values is not index.values
86
+ assert ser.index is index
87
+ assert ser.name == index.name
88
+
89
+ # name kwarg
90
+ ser = index.to_series(name="__test")
91
+
92
+ assert ser.values is not index.values
93
+ assert ser.index is not index
94
+ assert ser.name != index.name
95
+
96
+ def test_tolist_matches_list(self, index):
97
+ assert index.tolist() == list(index)
98
+
99
+
100
+ class TestRoundTrips:
101
+ def test_pickle_roundtrip(self, index):
102
+ result = tm.round_trip_pickle(index)
103
+ tm.assert_index_equal(result, index, exact=True)
104
+ if result.nlevels > 1:
105
+ # GH#8367 round-trip with timezone
106
+ assert index.equal_levels(result)
107
+
108
+ def test_pickle_preserves_name(self, index):
109
+ original_name, index.name = index.name, "foo"
110
+ unpickled = tm.round_trip_pickle(index)
111
+ assert index.equals(unpickled)
112
+ index.name = original_name
113
+
114
+
115
+ class TestIndexing:
116
+ def test_get_loc_listlike_raises_invalid_index_error(self, index):
117
+ # and never TypeError
118
+ key = np.array([0, 1], dtype=np.intp)
119
+
120
+ with pytest.raises(InvalidIndexError, match=r"\[0 1\]"):
121
+ index.get_loc(key)
122
+
123
+ with pytest.raises(InvalidIndexError, match=r"\[False True\]"):
124
+ index.get_loc(key.astype(bool))
125
+
126
+ def test_getitem_ellipsis(self, index):
127
+ # GH#21282
128
+ result = index[...]
129
+ assert result.equals(index)
130
+ assert result is not index
131
+
132
+ def test_slice_keeps_name(self, index):
133
+ assert index.name == index[1:].name
134
+
135
+ @pytest.mark.parametrize("item", [101, "no_int", 2.5])
136
+ def test_getitem_error(self, index, item):
137
+ msg = "|".join(
138
+ [
139
+ r"index 101 is out of bounds for axis 0 with size [\d]+",
140
+ re.escape(
141
+ "only integers, slices (`:`), ellipsis (`...`), "
142
+ "numpy.newaxis (`None`) and integer or boolean arrays "
143
+ "are valid indices"
144
+ ),
145
+ "index out of bounds", # string[pyarrow]
146
+ ]
147
+ )
148
+ with pytest.raises(IndexError, match=msg):
149
+ index[item]
150
+
151
+
152
+ class TestRendering:
153
+ def test_str(self, index):
154
+ # test the string repr
155
+ index.name = "foo"
156
+ assert "'foo'" in str(index)
157
+ assert type(index).__name__ in str(index)
158
+
159
+
160
+ class TestReductions:
161
+ def test_argmax_axis_invalid(self, index):
162
+ # GH#23081
163
+ msg = r"`axis` must be fewer than the number of dimensions \(1\)"
164
+ with pytest.raises(ValueError, match=msg):
165
+ index.argmax(axis=1)
166
+ with pytest.raises(ValueError, match=msg):
167
+ index.argmin(axis=2)
168
+ with pytest.raises(ValueError, match=msg):
169
+ index.min(axis=-2)
170
+ with pytest.raises(ValueError, match=msg):
171
+ index.max(axis=-3)
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/test_common.py ADDED
@@ -0,0 +1,488 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
17
+ from pandas.core.dtypes.common import (
18
+ is_integer_dtype,
19
+ is_numeric_dtype,
20
+ )
21
+
22
+ import pandas as pd
23
+ from pandas import (
24
+ CategoricalIndex,
25
+ MultiIndex,
26
+ PeriodIndex,
27
+ RangeIndex,
28
+ )
29
+ import pandas._testing as tm
30
+
31
+
32
+ class TestCommon:
33
+ @pytest.mark.parametrize("name", [None, "new_name"])
34
+ def test_to_frame(self, name, index_flat):
35
+ # see GH#15230, GH#22580
36
+ idx = index_flat
37
+
38
+ if name:
39
+ idx_name = name
40
+ else:
41
+ idx_name = idx.name or 0
42
+
43
+ df = idx.to_frame(name=idx_name)
44
+
45
+ assert df.index is idx
46
+ assert len(df.columns) == 1
47
+ assert df.columns[0] == idx_name
48
+ assert df[idx_name].values is not idx.values
49
+
50
+ df = idx.to_frame(index=False, name=idx_name)
51
+ assert df.index is not idx
52
+
53
+ def test_droplevel(self, index_flat):
54
+ # GH 21115
55
+ # MultiIndex is tested separately in test_multi.py
56
+ index = index_flat
57
+
58
+ assert index.droplevel([]).equals(index)
59
+
60
+ for level in [index.name, [index.name]]:
61
+ if isinstance(index.name, tuple) and level is index.name:
62
+ # GH 21121 : droplevel with tuple name
63
+ continue
64
+ msg = (
65
+ "Cannot remove 1 levels from an index with 1 levels: at least one "
66
+ "level must be left."
67
+ )
68
+ with pytest.raises(ValueError, match=msg):
69
+ index.droplevel(level)
70
+
71
+ for level in "wrong", ["wrong"]:
72
+ with pytest.raises(
73
+ KeyError,
74
+ match=r"'Requested level \(wrong\) does not match index name \(None\)'",
75
+ ):
76
+ index.droplevel(level)
77
+
78
+ def test_constructor_non_hashable_name(self, index_flat):
79
+ # GH 20527
80
+ index = index_flat
81
+
82
+ message = "Index.name must be a hashable type"
83
+ renamed = [["1"]]
84
+
85
+ # With .rename()
86
+ with pytest.raises(TypeError, match=message):
87
+ index.rename(name=renamed)
88
+
89
+ # With .set_names()
90
+ with pytest.raises(TypeError, match=message):
91
+ index.set_names(names=renamed)
92
+
93
+ def test_constructor_unwraps_index(self, index_flat):
94
+ a = index_flat
95
+ # Passing dtype is necessary for Index([True, False], dtype=object)
96
+ # case.
97
+ b = type(a)(a, dtype=a.dtype)
98
+ tm.assert_equal(a._data, b._data)
99
+
100
+ def test_to_flat_index(self, index_flat):
101
+ # 22866
102
+ index = index_flat
103
+
104
+ result = index.to_flat_index()
105
+ tm.assert_index_equal(result, index)
106
+
107
+ def test_set_name_methods(self, index_flat):
108
+ # MultiIndex tested separately
109
+ index = index_flat
110
+ new_name = "This is the new name for this index"
111
+
112
+ original_name = index.name
113
+ new_ind = index.set_names([new_name])
114
+ assert new_ind.name == new_name
115
+ assert index.name == original_name
116
+ res = index.rename(new_name, inplace=True)
117
+
118
+ # should return None
119
+ assert res is None
120
+ assert index.name == new_name
121
+ assert index.names == [new_name]
122
+ # FIXME: dont leave commented-out
123
+ # with pytest.raises(TypeError, match="list-like"):
124
+ # # should still fail even if it would be the right length
125
+ # ind.set_names("a")
126
+ with pytest.raises(ValueError, match="Level must be None"):
127
+ index.set_names("a", level=0)
128
+
129
+ # rename in place just leaves tuples and other containers alone
130
+ name = ("A", "B")
131
+ index.rename(name, inplace=True)
132
+ assert index.name == name
133
+ assert index.names == [name]
134
+
135
+ def test_copy_and_deepcopy(self, index_flat):
136
+ index = index_flat
137
+
138
+ for func in (copy, deepcopy):
139
+ idx_copy = func(index)
140
+ assert idx_copy is not index
141
+ assert idx_copy.equals(index)
142
+
143
+ new_copy = index.copy(deep=True, name="banana")
144
+ assert new_copy.name == "banana"
145
+
146
+ def test_copy_name(self, index_flat):
147
+ # GH#12309: Check that the "name" argument
148
+ # passed at initialization is honored.
149
+ index = index_flat
150
+
151
+ first = type(index)(index, copy=True, name="mario")
152
+ second = type(first)(first, copy=False)
153
+
154
+ # Even though "copy=False", we want a new object.
155
+ assert first is not second
156
+ tm.assert_index_equal(first, second)
157
+
158
+ # Not using tm.assert_index_equal() since names differ.
159
+ assert index.equals(first)
160
+
161
+ assert first.name == "mario"
162
+ assert second.name == "mario"
163
+
164
+ # TODO: belongs in series arithmetic tests?
165
+ s1 = pd.Series(2, index=first)
166
+ s2 = pd.Series(3, index=second[:-1])
167
+ # See GH#13365
168
+ s3 = s1 * s2
169
+ assert s3.index.name == "mario"
170
+
171
+ def test_copy_name2(self, index_flat):
172
+ # GH#35592
173
+ index = index_flat
174
+
175
+ assert index.copy(name="mario").name == "mario"
176
+
177
+ with pytest.raises(ValueError, match="Length of new names must be 1, got 2"):
178
+ index.copy(name=["mario", "luigi"])
179
+
180
+ msg = f"{type(index).__name__}.name must be a hashable type"
181
+ with pytest.raises(TypeError, match=msg):
182
+ index.copy(name=[["mario"]])
183
+
184
+ def test_unique_level(self, index_flat):
185
+ # don't test a MultiIndex here (as its tested separated)
186
+ index = index_flat
187
+
188
+ # GH 17896
189
+ expected = index.drop_duplicates()
190
+ for level in [0, index.name, None]:
191
+ result = index.unique(level=level)
192
+ tm.assert_index_equal(result, expected)
193
+
194
+ msg = "Too many levels: Index has only 1 level, not 4"
195
+ with pytest.raises(IndexError, match=msg):
196
+ index.unique(level=3)
197
+
198
+ msg = (
199
+ rf"Requested level \(wrong\) does not match index name "
200
+ rf"\({re.escape(index.name.__repr__())}\)"
201
+ )
202
+ with pytest.raises(KeyError, match=msg):
203
+ index.unique(level="wrong")
204
+
205
+ def test_unique(self, index_flat):
206
+ # MultiIndex tested separately
207
+ index = index_flat
208
+ if not len(index):
209
+ pytest.skip("Skip check for empty Index and MultiIndex")
210
+
211
+ idx = index[[0] * 5]
212
+ idx_unique = index[[0]]
213
+
214
+ # We test against `idx_unique`, so first we make sure it's unique
215
+ # and doesn't contain nans.
216
+ assert idx_unique.is_unique is True
217
+ try:
218
+ assert idx_unique.hasnans is False
219
+ except NotImplementedError:
220
+ pass
221
+
222
+ result = idx.unique()
223
+ tm.assert_index_equal(result, idx_unique)
224
+
225
+ # nans:
226
+ if not index._can_hold_na:
227
+ pytest.skip("Skip na-check if index cannot hold na")
228
+
229
+ vals = index._values[[0] * 5]
230
+ vals[0] = np.nan
231
+
232
+ vals_unique = vals[:2]
233
+ idx_nan = index._shallow_copy(vals)
234
+ idx_unique_nan = index._shallow_copy(vals_unique)
235
+ assert idx_unique_nan.is_unique is True
236
+
237
+ assert idx_nan.dtype == index.dtype
238
+ assert idx_unique_nan.dtype == index.dtype
239
+
240
+ expected = idx_unique_nan
241
+ for pos, i in enumerate([idx_nan, idx_unique_nan]):
242
+ result = i.unique()
243
+ tm.assert_index_equal(result, expected)
244
+
245
+ def test_searchsorted_monotonic(self, index_flat, request):
246
+ # GH17271
247
+ index = index_flat
248
+ # not implemented for tuple searches in MultiIndex
249
+ # or Intervals searches in IntervalIndex
250
+ if isinstance(index, pd.IntervalIndex):
251
+ mark = pytest.mark.xfail(
252
+ reason="IntervalIndex.searchsorted does not support Interval arg",
253
+ raises=NotImplementedError,
254
+ )
255
+ request.node.add_marker(mark)
256
+
257
+ # nothing to test if the index is empty
258
+ if index.empty:
259
+ pytest.skip("Skip check for empty Index")
260
+ value = index[0]
261
+
262
+ # determine the expected results (handle dupes for 'right')
263
+ expected_left, expected_right = 0, (index == value).argmin()
264
+ if expected_right == 0:
265
+ # all values are the same, expected_right should be length
266
+ expected_right = len(index)
267
+
268
+ # test _searchsorted_monotonic in all cases
269
+ # test searchsorted only for increasing
270
+ if index.is_monotonic_increasing:
271
+ ssm_left = index._searchsorted_monotonic(value, side="left")
272
+ assert expected_left == ssm_left
273
+
274
+ ssm_right = index._searchsorted_monotonic(value, side="right")
275
+ assert expected_right == ssm_right
276
+
277
+ ss_left = index.searchsorted(value, side="left")
278
+ assert expected_left == ss_left
279
+
280
+ ss_right = index.searchsorted(value, side="right")
281
+ assert expected_right == ss_right
282
+
283
+ elif index.is_monotonic_decreasing:
284
+ ssm_left = index._searchsorted_monotonic(value, side="left")
285
+ assert expected_left == ssm_left
286
+
287
+ ssm_right = index._searchsorted_monotonic(value, side="right")
288
+ assert expected_right == ssm_right
289
+ else:
290
+ # non-monotonic should raise.
291
+ msg = "index must be monotonic increasing or decreasing"
292
+ with pytest.raises(ValueError, match=msg):
293
+ index._searchsorted_monotonic(value, side="left")
294
+
295
+ def test_drop_duplicates(self, index_flat, keep):
296
+ # MultiIndex is tested separately
297
+ index = index_flat
298
+ if isinstance(index, RangeIndex):
299
+ pytest.skip(
300
+ "RangeIndex is tested in test_drop_duplicates_no_duplicates "
301
+ "as it cannot hold duplicates"
302
+ )
303
+ if len(index) == 0:
304
+ pytest.skip(
305
+ "empty index is tested in test_drop_duplicates_no_duplicates "
306
+ "as it cannot hold duplicates"
307
+ )
308
+
309
+ # make unique index
310
+ holder = type(index)
311
+ unique_values = list(set(index))
312
+ dtype = index.dtype if is_numeric_dtype(index) else None
313
+ unique_idx = holder(unique_values, dtype=dtype)
314
+
315
+ # make duplicated index
316
+ n = len(unique_idx)
317
+ duplicated_selection = np.random.choice(n, int(n * 1.5))
318
+ idx = holder(unique_idx.values[duplicated_selection])
319
+
320
+ # Series.duplicated is tested separately
321
+ expected_duplicated = (
322
+ pd.Series(duplicated_selection).duplicated(keep=keep).values
323
+ )
324
+ tm.assert_numpy_array_equal(idx.duplicated(keep=keep), expected_duplicated)
325
+
326
+ # Series.drop_duplicates is tested separately
327
+ expected_dropped = holder(pd.Series(idx).drop_duplicates(keep=keep))
328
+ tm.assert_index_equal(idx.drop_duplicates(keep=keep), expected_dropped)
329
+
330
+ def test_drop_duplicates_no_duplicates(self, index_flat):
331
+ # MultiIndex is tested separately
332
+ index = index_flat
333
+
334
+ # make unique index
335
+ if isinstance(index, RangeIndex):
336
+ # RangeIndex cannot have duplicates
337
+ unique_idx = index
338
+ else:
339
+ holder = type(index)
340
+ unique_values = list(set(index))
341
+ dtype = index.dtype if is_numeric_dtype(index) else None
342
+ unique_idx = holder(unique_values, dtype=dtype)
343
+
344
+ # check on unique index
345
+ expected_duplicated = np.array([False] * len(unique_idx), dtype="bool")
346
+ tm.assert_numpy_array_equal(unique_idx.duplicated(), expected_duplicated)
347
+ result_dropped = unique_idx.drop_duplicates()
348
+ tm.assert_index_equal(result_dropped, unique_idx)
349
+ # validate shallow copy
350
+ assert result_dropped is not unique_idx
351
+
352
+ def test_drop_duplicates_inplace(self, index):
353
+ msg = r"drop_duplicates\(\) got an unexpected keyword argument"
354
+ with pytest.raises(TypeError, match=msg):
355
+ index.drop_duplicates(inplace=True)
356
+
357
+ def test_has_duplicates(self, index_flat):
358
+ # MultiIndex tested separately in:
359
+ # tests/indexes/multi/test_unique_and_duplicates.
360
+ index = index_flat
361
+ holder = type(index)
362
+ if not len(index) or isinstance(index, RangeIndex):
363
+ # MultiIndex tested separately in:
364
+ # tests/indexes/multi/test_unique_and_duplicates.
365
+ # RangeIndex is unique by definition.
366
+ pytest.skip("Skip check for empty Index, MultiIndex, and RangeIndex")
367
+
368
+ idx = holder([index[0]] * 5)
369
+ assert idx.is_unique is False
370
+ assert idx.has_duplicates is True
371
+
372
+ @pytest.mark.parametrize(
373
+ "dtype",
374
+ ["int64", "uint64", "float64", "category", "datetime64[ns]", "timedelta64[ns]"],
375
+ )
376
+ def test_astype_preserves_name(self, index, dtype):
377
+ # https://github.com/pandas-dev/pandas/issues/32013
378
+ if isinstance(index, MultiIndex):
379
+ index.names = ["idx" + str(i) for i in range(index.nlevels)]
380
+ else:
381
+ index.name = "idx"
382
+
383
+ warn = None
384
+ if index.dtype.kind == "c" and dtype in ["float64", "int64", "uint64"]:
385
+ # imaginary components discarded
386
+ warn = np.ComplexWarning
387
+
388
+ is_pyarrow_str = str(index.dtype) == "string[pyarrow]" and dtype == "category"
389
+ try:
390
+ # Some of these conversions cannot succeed so we use a try / except
391
+ with tm.assert_produces_warning(
392
+ warn,
393
+ raise_on_extra_warnings=is_pyarrow_str,
394
+ check_stacklevel=False,
395
+ ):
396
+ result = index.astype(dtype)
397
+ except (ValueError, TypeError, NotImplementedError, SystemError):
398
+ return
399
+
400
+ if isinstance(index, MultiIndex):
401
+ assert result.names == index.names
402
+ else:
403
+ assert result.name == index.name
404
+
405
+ def test_hasnans_isnans(self, index_flat):
406
+ # GH#11343, added tests for hasnans / isnans
407
+ index = index_flat
408
+
409
+ # cases in indices doesn't include NaN
410
+ idx = index.copy(deep=True)
411
+ expected = np.array([False] * len(idx), dtype=bool)
412
+ tm.assert_numpy_array_equal(idx._isnan, expected)
413
+ assert idx.hasnans is False
414
+
415
+ idx = index.copy(deep=True)
416
+ values = idx._values
417
+
418
+ if len(index) == 0:
419
+ return
420
+ elif is_integer_dtype(index.dtype):
421
+ return
422
+ elif index.dtype == bool:
423
+ # values[1] = np.nan below casts to True!
424
+ return
425
+
426
+ values[1] = np.nan
427
+
428
+ idx = type(index)(values)
429
+
430
+ expected = np.array([False] * len(idx), dtype=bool)
431
+ expected[1] = True
432
+ tm.assert_numpy_array_equal(idx._isnan, expected)
433
+ assert idx.hasnans is True
434
+
435
+
436
+ @pytest.mark.parametrize("na_position", [None, "middle"])
437
+ def test_sort_values_invalid_na_position(index_with_missing, na_position):
438
+ with pytest.raises(ValueError, match=f"invalid na_position: {na_position}"):
439
+ index_with_missing.sort_values(na_position=na_position)
440
+
441
+
442
+ @pytest.mark.parametrize("na_position", ["first", "last"])
443
+ def test_sort_values_with_missing(index_with_missing, na_position, request):
444
+ # GH 35584. Test that sort_values works with missing values,
445
+ # sort non-missing and place missing according to na_position
446
+
447
+ if isinstance(index_with_missing, CategoricalIndex):
448
+ request.node.add_marker(
449
+ pytest.mark.xfail(
450
+ reason="missing value sorting order not well-defined", strict=False
451
+ )
452
+ )
453
+
454
+ missing_count = np.sum(index_with_missing.isna())
455
+ not_na_vals = index_with_missing[index_with_missing.notna()].values
456
+ sorted_values = np.sort(not_na_vals)
457
+ if na_position == "first":
458
+ sorted_values = np.concatenate([[None] * missing_count, sorted_values])
459
+ else:
460
+ sorted_values = np.concatenate([sorted_values, [None] * missing_count])
461
+
462
+ # Explicitly pass dtype needed for Index backed by EA e.g. IntegerArray
463
+ expected = type(index_with_missing)(sorted_values, dtype=index_with_missing.dtype)
464
+
465
+ result = index_with_missing.sort_values(na_position=na_position)
466
+ tm.assert_index_equal(result, expected)
467
+
468
+
469
+ def test_ndarray_compat_properties(index):
470
+ if isinstance(index, PeriodIndex) and not IS64:
471
+ pytest.skip("Overflow")
472
+ idx = index
473
+ assert idx.T.equals(idx)
474
+ assert idx.transpose().equals(idx)
475
+
476
+ values = idx.values
477
+
478
+ assert idx.shape == values.shape
479
+ assert idx.ndim == values.ndim
480
+ assert idx.size == values.size
481
+
482
+ if not isinstance(index, (RangeIndex, MultiIndex)):
483
+ # These two are not backed by an ndarray
484
+ assert idx.nbytes == values.nbytes
485
+
486
+ # test for validity
487
+ idx.nbytes
488
+ idx.values.nbytes
videochat2/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()
videochat2/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)
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/test_indexing.py ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # not enough elements; ignore
60
+ return
61
+
62
+ result = index.take(indexer)
63
+ expected = index[indexer]
64
+ assert result.equals(expected)
65
+
66
+ if not isinstance(index, (DatetimeIndex, PeriodIndex, TimedeltaIndex)):
67
+ # GH 10791
68
+ msg = r"'(.*Index)' object has no attribute 'freq'"
69
+ with pytest.raises(AttributeError, match=msg):
70
+ index.freq
71
+
72
+ def test_take_indexer_type(self):
73
+ # GH#42875
74
+ integer_index = Index([0, 1, 2, 3])
75
+ scalar_index = 1
76
+ msg = "Expected indices to be array-like"
77
+ with pytest.raises(TypeError, match=msg):
78
+ integer_index.take(scalar_index)
79
+
80
+ def test_take_minus1_without_fill(self, index):
81
+ # -1 does not get treated as NA unless allow_fill=True is passed
82
+ if len(index) == 0:
83
+ # Test is not applicable
84
+ return
85
+
86
+ result = index.take([0, 0, -1])
87
+
88
+ expected = index.take([0, 0, len(index) - 1])
89
+ tm.assert_index_equal(result, expected)
90
+
91
+
92
+ class TestContains:
93
+ @pytest.mark.parametrize(
94
+ "index,val",
95
+ [
96
+ (Index([0, 1, 2]), 2),
97
+ (Index([0, 1, "2"]), "2"),
98
+ (Index([0, 1, 2, np.inf, 4]), 4),
99
+ (Index([0, 1, 2, np.nan, 4]), 4),
100
+ (Index([0, 1, 2, np.inf]), np.inf),
101
+ (Index([0, 1, 2, np.nan]), np.nan),
102
+ ],
103
+ )
104
+ def test_index_contains(self, index, val):
105
+ assert val in index
106
+
107
+ @pytest.mark.parametrize(
108
+ "index,val",
109
+ [
110
+ (Index([0, 1, 2]), "2"),
111
+ (Index([0, 1, "2"]), 2),
112
+ (Index([0, 1, 2, np.inf]), 4),
113
+ (Index([0, 1, 2, np.nan]), 4),
114
+ (Index([0, 1, 2, np.inf]), np.nan),
115
+ (Index([0, 1, 2, np.nan]), np.inf),
116
+ # Checking if np.inf in int64 Index should not cause an OverflowError
117
+ # Related to GH 16957
118
+ (Index([0, 1, 2], dtype=np.int64), np.inf),
119
+ (Index([0, 1, 2], dtype=np.int64), np.nan),
120
+ (Index([0, 1, 2], dtype=np.uint64), np.inf),
121
+ (Index([0, 1, 2], dtype=np.uint64), np.nan),
122
+ ],
123
+ )
124
+ def test_index_not_contains(self, index, val):
125
+ assert val not in index
126
+
127
+ @pytest.mark.parametrize(
128
+ "index,val", [(Index([0, 1, "2"]), 0), (Index([0, 1, "2"]), "2")]
129
+ )
130
+ def test_mixed_index_contains(self, index, val):
131
+ # GH#19860
132
+ assert val in index
133
+
134
+ @pytest.mark.parametrize(
135
+ "index,val", [(Index([0, 1, "2"]), "1"), (Index([0, 1, "2"]), 2)]
136
+ )
137
+ def test_mixed_index_not_contains(self, index, val):
138
+ # GH#19860
139
+ assert val not in index
140
+
141
+ def test_contains_with_float_index(self, any_real_numpy_dtype):
142
+ # GH#22085
143
+ dtype = any_real_numpy_dtype
144
+ data = [0, 1, 2, 3] if not is_float_dtype(dtype) else [0.1, 1.1, 2.2, 3.3]
145
+ index = Index(data, dtype=dtype)
146
+
147
+ if not is_float_dtype(index.dtype):
148
+ assert 1.1 not in index
149
+ assert 1.0 in index
150
+ assert 1 in index
151
+ else:
152
+ assert 1.1 in index
153
+ assert 1.0 not in index
154
+ assert 1 not in index
155
+
156
+ def test_contains_requires_hashable_raises(self, index):
157
+ if isinstance(index, MultiIndex):
158
+ return # TODO: do we want this to raise?
159
+
160
+ msg = "unhashable type: 'list'"
161
+ with pytest.raises(TypeError, match=msg):
162
+ [] in index
163
+
164
+ msg = "|".join(
165
+ [
166
+ r"unhashable type: 'dict'",
167
+ r"must be real number, not dict",
168
+ r"an integer is required",
169
+ r"\{\}",
170
+ r"pandas\._libs\.interval\.IntervalTree' is not iterable",
171
+ ]
172
+ )
173
+ with pytest.raises(TypeError, match=msg):
174
+ {} in index._engine
175
+
176
+
177
+ class TestGetLoc:
178
+ def test_get_loc_non_hashable(self, index):
179
+ # MultiIndex and Index raise TypeError, others InvalidIndexError
180
+
181
+ with pytest.raises((TypeError, InvalidIndexError), match="slice"):
182
+ index.get_loc(slice(0, 1))
183
+
184
+ def test_get_loc_non_scalar_hashable(self, index):
185
+ # GH52877
186
+ from enum import Enum
187
+
188
+ class E(Enum):
189
+ X1 = "x1"
190
+
191
+ assert not is_scalar(E.X1)
192
+
193
+ exc = KeyError
194
+ msg = "<E.X1: 'x1'>"
195
+ if isinstance(
196
+ index,
197
+ (
198
+ DatetimeIndex,
199
+ TimedeltaIndex,
200
+ PeriodIndex,
201
+ IntervalIndex,
202
+ ),
203
+ ):
204
+ # TODO: make these more consistent?
205
+ exc = InvalidIndexError
206
+ msg = "E.X1"
207
+ with pytest.raises(exc, match=msg):
208
+ index.get_loc(E.X1)
209
+
210
+ def test_get_loc_generator(self, index):
211
+ exc = KeyError
212
+ if isinstance(
213
+ index,
214
+ (
215
+ DatetimeIndex,
216
+ TimedeltaIndex,
217
+ PeriodIndex,
218
+ IntervalIndex,
219
+ MultiIndex,
220
+ ),
221
+ ):
222
+ # TODO: make these more consistent?
223
+ exc = InvalidIndexError
224
+ with pytest.raises(exc, match="generator object"):
225
+ # MultiIndex specifically checks for generator; others for scalar
226
+ index.get_loc(x for x in range(5))
227
+
228
+ def test_get_loc_masked_duplicated_na(self):
229
+ # GH#48411
230
+ idx = Index([1, 2, NA, NA], dtype="Int64")
231
+ result = idx.get_loc(NA)
232
+ expected = np.array([False, False, True, True])
233
+ tm.assert_numpy_array_equal(result, expected)
234
+
235
+
236
+ class TestGetIndexer:
237
+ def test_get_indexer_base(self, index):
238
+ if index._index_as_unique:
239
+ expected = np.arange(index.size, dtype=np.intp)
240
+ actual = index.get_indexer(index)
241
+ tm.assert_numpy_array_equal(expected, actual)
242
+ else:
243
+ msg = "Reindexing only valid with uniquely valued Index objects"
244
+ with pytest.raises(InvalidIndexError, match=msg):
245
+ index.get_indexer(index)
246
+
247
+ with pytest.raises(ValueError, match="Invalid fill method"):
248
+ index.get_indexer(index, method="invalid")
249
+
250
+ def test_get_indexer_consistency(self, index):
251
+ # See GH#16819
252
+
253
+ if index._index_as_unique:
254
+ indexer = index.get_indexer(index[0:2])
255
+ assert isinstance(indexer, np.ndarray)
256
+ assert indexer.dtype == np.intp
257
+ else:
258
+ msg = "Reindexing only valid with uniquely valued Index objects"
259
+ with pytest.raises(InvalidIndexError, match=msg):
260
+ index.get_indexer(index[0:2])
261
+
262
+ indexer, _ = index.get_indexer_non_unique(index[0:2])
263
+ assert isinstance(indexer, np.ndarray)
264
+ assert indexer.dtype == np.intp
265
+
266
+ def test_get_indexer_masked_duplicated_na(self):
267
+ # GH#48411
268
+ idx = Index([1, 2, NA, NA], dtype="Int64")
269
+ result = idx.get_indexer_for(Index([1, NA], dtype="Int64"))
270
+ expected = np.array([0, 2, 3], dtype=result.dtype)
271
+ tm.assert_numpy_array_equal(result, expected)
272
+
273
+
274
+ class TestConvertSliceIndexer:
275
+ def test_convert_almost_null_slice(self, index):
276
+ # slice with None at both ends, but not step
277
+
278
+ key = slice(None, None, "foo")
279
+
280
+ if isinstance(index, IntervalIndex):
281
+ msg = "label-based slicing with step!=1 is not supported for IntervalIndex"
282
+ with pytest.raises(ValueError, match=msg):
283
+ index._convert_slice_indexer(key, "loc")
284
+ else:
285
+ msg = "'>=' not supported between instances of 'str' and 'int'"
286
+ with pytest.raises(TypeError, match=msg):
287
+ index._convert_slice_indexer(key, "loc")
288
+
289
+
290
+ class TestPutmask:
291
+ def test_putmask_with_wrong_mask(self, index):
292
+ # GH#18368
293
+ if not len(index):
294
+ return
295
+
296
+ fill = index[0]
297
+
298
+ msg = "putmask: mask and data must be the same size"
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(np.ones(len(index) - 1, np.bool_), fill)
304
+
305
+ with pytest.raises(ValueError, match=msg):
306
+ index.putmask("foo", fill)
307
+
308
+
309
+ @pytest.mark.parametrize(
310
+ "idx", [Index([1, 2, 3]), Index([0.1, 0.2, 0.3]), Index(["a", "b", "c"])]
311
+ )
312
+ def test_getitem_deprecated_float(idx):
313
+ # https://github.com/pandas-dev/pandas/issues/34191
314
+
315
+ msg = "Indexing with a float is no longer supported"
316
+ with pytest.raises(IndexError, match=msg):
317
+ idx[1.0]
318
+
319
+
320
+ @pytest.mark.parametrize(
321
+ "idx,target,expected",
322
+ [
323
+ ([np.nan, "var1", np.nan], [np.nan], np.array([0, 2], dtype=np.intp)),
324
+ (
325
+ [np.nan, "var1", np.nan],
326
+ [np.nan, "var1"],
327
+ np.array([0, 2, 1], dtype=np.intp),
328
+ ),
329
+ (
330
+ np.array([np.nan, "var1", np.nan], dtype=object),
331
+ [np.nan],
332
+ np.array([0, 2], dtype=np.intp),
333
+ ),
334
+ (
335
+ DatetimeIndex(["2020-08-05", NaT, NaT]),
336
+ [NaT],
337
+ np.array([1, 2], dtype=np.intp),
338
+ ),
339
+ (["a", "b", "a", np.nan], [np.nan], np.array([3], dtype=np.intp)),
340
+ (
341
+ np.array(["b", np.nan, float("NaN"), "b"], dtype=object),
342
+ Index([np.nan], dtype=object),
343
+ np.array([1, 2], dtype=np.intp),
344
+ ),
345
+ ],
346
+ )
347
+ def test_get_indexer_non_unique_multiple_nans(idx, target, expected):
348
+ # GH 35392
349
+ axis = Index(idx)
350
+ actual = axis.get_indexer_for(target)
351
+ tm.assert_numpy_array_equal(actual, expected)
352
+
353
+
354
+ def test_get_indexer_non_unique_nans_in_object_dtype_target(nulls_fixture):
355
+ idx = Index([1.0, 2.0])
356
+ target = Index([1, nulls_fixture], dtype="object")
357
+
358
+ result_idx, result_missing = idx.get_indexer_non_unique(target)
359
+ tm.assert_numpy_array_equal(result_idx, np.array([0, -1], dtype=np.intp))
360
+ tm.assert_numpy_array_equal(result_missing, np.array([1], dtype=np.intp))
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/test_numpy_compat.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ else:
96
+ # raise AttributeError or TypeError
97
+ if len(index) == 0:
98
+ pass
99
+ else:
100
+ with tm.external_error_raised((TypeError, AttributeError)):
101
+ with np.errstate(all="ignore"):
102
+ func(index)
103
+
104
+
105
+ @pytest.mark.parametrize(
106
+ "func", [np.isfinite, np.isinf, np.isnan, np.signbit], ids=lambda x: x.__name__
107
+ )
108
+ def test_numpy_ufuncs_other(index, func):
109
+ # test ufuncs of numpy, see:
110
+ # https://numpy.org/doc/stable/reference/ufuncs.html
111
+ if isinstance(index, (DatetimeIndex, TimedeltaIndex)):
112
+ if func in (np.isfinite, np.isinf, np.isnan):
113
+ # numpy 1.18 changed isinf and isnan to not raise on dt64/td64
114
+ result = func(index)
115
+ assert isinstance(result, np.ndarray)
116
+
117
+ out = np.empty(index.shape, dtype=bool)
118
+ func(index, out=out)
119
+ tm.assert_numpy_array_equal(out, result)
120
+ else:
121
+ with tm.external_error_raised(TypeError):
122
+ func(index)
123
+
124
+ elif isinstance(index, PeriodIndex):
125
+ with tm.external_error_raised(TypeError):
126
+ func(index)
127
+
128
+ elif is_numeric_dtype(index) and not (
129
+ is_complex_dtype(index) and func is np.signbit
130
+ ):
131
+ # Results in bool array
132
+ result = func(index)
133
+ if not isinstance(index.dtype, np.dtype):
134
+ # e.g. Int64 we expect to get BooleanArray back
135
+ assert isinstance(result, BooleanArray)
136
+ else:
137
+ assert isinstance(result, np.ndarray)
138
+
139
+ out = np.empty(index.shape, dtype=bool)
140
+ func(index, out=out)
141
+
142
+ if not isinstance(index.dtype, np.dtype):
143
+ tm.assert_numpy_array_equal(out, result._data)
144
+ else:
145
+ tm.assert_numpy_array_equal(out, result)
146
+
147
+ else:
148
+ if len(index) == 0:
149
+ pass
150
+ else:
151
+ with tm.external_error_raised(TypeError):
152
+ func(index)
153
+
154
+
155
+ @pytest.mark.parametrize("func", [np.maximum, np.minimum])
156
+ def test_numpy_ufuncs_reductions(index, func, request):
157
+ # TODO: overlap with tests.series.test_ufunc.test_reductions
158
+ if len(index) == 0:
159
+ return
160
+
161
+ if isinstance(index, CategoricalIndex) and index.dtype.ordered is False:
162
+ with pytest.raises(TypeError, match="is not ordered for"):
163
+ func.reduce(index)
164
+ return
165
+ else:
166
+ result = func.reduce(index)
167
+
168
+ if func is np.maximum:
169
+ expected = index.max(skipna=False)
170
+ else:
171
+ expected = index.min(skipna=False)
172
+ # TODO: do we have cases both with and without NAs?
173
+
174
+ assert type(result) is type(expected)
175
+ if isna(result):
176
+ assert isna(expected)
177
+ else:
178
+ assert result == expected
179
+
180
+
181
+ @pytest.mark.parametrize("func", [np.bitwise_and, np.bitwise_or, np.bitwise_xor])
182
+ def test_numpy_ufuncs_bitwise(func):
183
+ # https://github.com/pandas-dev/pandas/issues/46769
184
+ idx1 = Index([1, 2, 3, 4], dtype="int64")
185
+ idx2 = Index([3, 4, 5, 6], dtype="int64")
186
+
187
+ with tm.assert_produces_warning(None):
188
+ result = func(idx1, idx2)
189
+
190
+ expected = Index(func(idx1.values, idx2.values))
191
+ tm.assert_index_equal(result, expected)
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/test_setops.py ADDED
@@ -0,0 +1,888 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.core.dtypes.cast import find_common_type
12
+
13
+ from pandas import (
14
+ CategoricalIndex,
15
+ Index,
16
+ MultiIndex,
17
+ RangeIndex,
18
+ Series,
19
+ Timestamp,
20
+ )
21
+ import pandas._testing as tm
22
+ from pandas.api.types import (
23
+ is_bool_dtype,
24
+ is_datetime64tz_dtype,
25
+ is_signed_integer_dtype,
26
+ pandas_dtype,
27
+ )
28
+
29
+
30
+ def test_union_same_types(index):
31
+ # Union with a non-unique, non-monotonic index raises error
32
+ # Only needed for bool index factory
33
+ idx1 = index.sort_values()
34
+ idx2 = index.sort_values()
35
+ assert idx1.union(idx2).dtype == idx1.dtype
36
+
37
+
38
+ def test_union_different_types(index_flat, index_flat2, request):
39
+ # This test only considers combinations of indices
40
+ # GH 23525
41
+ idx1 = index_flat
42
+ idx2 = index_flat2
43
+
44
+ if (
45
+ not idx1.is_unique
46
+ and not idx2.is_unique
47
+ and idx1.dtype.kind == "i"
48
+ and idx2.dtype.kind == "b"
49
+ ) or (
50
+ not idx2.is_unique
51
+ and not idx1.is_unique
52
+ and idx2.dtype.kind == "i"
53
+ and idx1.dtype.kind == "b"
54
+ ):
55
+ # Each condition had idx[1|2].is_monotonic_decreasing
56
+ # but failed when e.g.
57
+ # idx1 = Index(
58
+ # [True, True, True, True, True, True, True, True, False, False], dtype='bool'
59
+ # )
60
+ # idx2 = Index([0, 0, 1, 1, 2, 2], dtype='int64')
61
+ mark = pytest.mark.xfail(
62
+ reason="GH#44000 True==1", raises=ValueError, strict=False
63
+ )
64
+ request.node.add_marker(mark)
65
+
66
+ common_dtype = find_common_type([idx1.dtype, idx2.dtype])
67
+
68
+ warn = None
69
+ if not len(idx1) or not len(idx2):
70
+ pass
71
+ elif (
72
+ idx1.dtype.kind == "c"
73
+ and (
74
+ idx2.dtype.kind not in ["i", "u", "f", "c"]
75
+ or not isinstance(idx2.dtype, np.dtype)
76
+ )
77
+ ) or (
78
+ idx2.dtype.kind == "c"
79
+ and (
80
+ idx1.dtype.kind not in ["i", "u", "f", "c"]
81
+ or not isinstance(idx1.dtype, np.dtype)
82
+ )
83
+ ):
84
+ # complex objects non-sortable
85
+ warn = RuntimeWarning
86
+
87
+ any_uint64 = np.uint64 in (idx1.dtype, idx2.dtype)
88
+ idx1_signed = is_signed_integer_dtype(idx1.dtype)
89
+ idx2_signed = is_signed_integer_dtype(idx2.dtype)
90
+
91
+ # Union with a non-unique, non-monotonic index raises error
92
+ # This applies to the boolean index
93
+ idx1 = idx1.sort_values()
94
+ idx2 = idx2.sort_values()
95
+
96
+ with tm.assert_produces_warning(warn, match="'<' not supported between"):
97
+ res1 = idx1.union(idx2)
98
+ res2 = idx2.union(idx1)
99
+
100
+ if any_uint64 and (idx1_signed or idx2_signed):
101
+ assert res1.dtype == np.dtype("O")
102
+ assert res2.dtype == np.dtype("O")
103
+ else:
104
+ assert res1.dtype == common_dtype
105
+ assert res2.dtype == common_dtype
106
+
107
+
108
+ @pytest.mark.parametrize(
109
+ "idx_fact1,idx_fact2",
110
+ [
111
+ (tm.makeIntIndex, tm.makeRangeIndex),
112
+ (tm.makeFloatIndex, tm.makeIntIndex),
113
+ (tm.makeFloatIndex, tm.makeRangeIndex),
114
+ (tm.makeFloatIndex, tm.makeUIntIndex),
115
+ ],
116
+ )
117
+ def test_compatible_inconsistent_pairs(idx_fact1, idx_fact2):
118
+ # GH 23525
119
+ idx1 = idx_fact1(10)
120
+ idx2 = idx_fact2(20)
121
+
122
+ res1 = idx1.union(idx2)
123
+ res2 = idx2.union(idx1)
124
+
125
+ assert res1.dtype in (idx1.dtype, idx2.dtype)
126
+ assert res2.dtype in (idx1.dtype, idx2.dtype)
127
+
128
+
129
+ @pytest.mark.parametrize(
130
+ "left, right, expected",
131
+ [
132
+ ("int64", "int64", "int64"),
133
+ ("int64", "uint64", "object"),
134
+ ("int64", "float64", "float64"),
135
+ ("uint64", "float64", "float64"),
136
+ ("uint64", "uint64", "uint64"),
137
+ ("float64", "float64", "float64"),
138
+ ("datetime64[ns]", "int64", "object"),
139
+ ("datetime64[ns]", "uint64", "object"),
140
+ ("datetime64[ns]", "float64", "object"),
141
+ ("datetime64[ns, CET]", "int64", "object"),
142
+ ("datetime64[ns, CET]", "uint64", "object"),
143
+ ("datetime64[ns, CET]", "float64", "object"),
144
+ ("Period[D]", "int64", "object"),
145
+ ("Period[D]", "uint64", "object"),
146
+ ("Period[D]", "float64", "object"),
147
+ ],
148
+ )
149
+ @pytest.mark.parametrize("names", [("foo", "foo", "foo"), ("foo", "bar", None)])
150
+ def test_union_dtypes(left, right, expected, names):
151
+ left = pandas_dtype(left)
152
+ right = pandas_dtype(right)
153
+ a = Index([], dtype=left, name=names[0])
154
+ b = Index([], dtype=right, name=names[1])
155
+ result = a.union(b)
156
+ assert result.dtype == expected
157
+ assert result.name == names[2]
158
+
159
+ # Testing name retention
160
+ # TODO: pin down desired dtype; do we want it to be commutative?
161
+ result = a.intersection(b)
162
+ assert result.name == names[2]
163
+
164
+
165
+ @pytest.mark.parametrize("values", [[1, 2, 2, 3], [3, 3]])
166
+ def test_intersection_duplicates(values):
167
+ # GH#31326
168
+ a = Index(values)
169
+ b = Index([3, 3])
170
+ result = a.intersection(b)
171
+ expected = Index([3])
172
+ tm.assert_index_equal(result, expected)
173
+
174
+
175
+ class TestSetOps:
176
+ # Set operation tests shared by all indexes in the `index` fixture
177
+ @pytest.mark.parametrize("case", [0.5, "xxx"])
178
+ @pytest.mark.parametrize(
179
+ "method", ["intersection", "union", "difference", "symmetric_difference"]
180
+ )
181
+ def test_set_ops_error_cases(self, case, method, index):
182
+ # non-iterable input
183
+ msg = "Input must be Index or array-like"
184
+ with pytest.raises(TypeError, match=msg):
185
+ getattr(index, method)(case)
186
+
187
+ def test_intersection_base(self, index):
188
+ if isinstance(index, CategoricalIndex):
189
+ return
190
+
191
+ first = index[:5]
192
+ second = index[:3]
193
+ intersect = first.intersection(second)
194
+ assert tm.equalContents(intersect, second)
195
+
196
+ if is_datetime64tz_dtype(index.dtype):
197
+ # The second.values below will drop tz, so the rest of this test
198
+ # is not applicable.
199
+ return
200
+
201
+ # GH#10149
202
+ cases = [second.to_numpy(), second.to_series(), second.to_list()]
203
+ for case in cases:
204
+ result = first.intersection(case)
205
+ assert tm.equalContents(result, second)
206
+
207
+ if isinstance(index, MultiIndex):
208
+ msg = "other must be a MultiIndex or a list of tuples"
209
+ with pytest.raises(TypeError, match=msg):
210
+ first.intersection([1, 2, 3])
211
+
212
+ @pytest.mark.filterwarnings(
213
+ "ignore:Falling back on a non-pyarrow:pandas.errors.PerformanceWarning"
214
+ )
215
+ def test_union_base(self, index):
216
+ first = index[3:]
217
+ second = index[:5]
218
+ everything = index
219
+
220
+ union = first.union(second)
221
+ assert tm.equalContents(union, everything)
222
+
223
+ if is_datetime64tz_dtype(index.dtype):
224
+ # The second.values below will drop tz, so the rest of this test
225
+ # is not applicable.
226
+ return
227
+
228
+ # GH#10149
229
+ cases = [second.to_numpy(), second.to_series(), second.to_list()]
230
+ for case in cases:
231
+ result = first.union(case)
232
+ assert tm.equalContents(result, everything)
233
+
234
+ if isinstance(index, MultiIndex):
235
+ msg = "other must be a MultiIndex or a list of tuples"
236
+ with pytest.raises(TypeError, match=msg):
237
+ first.union([1, 2, 3])
238
+
239
+ @pytest.mark.filterwarnings(
240
+ "ignore:Falling back on a non-pyarrow:pandas.errors.PerformanceWarning"
241
+ )
242
+ def test_difference_base(self, sort, index):
243
+ first = index[2:]
244
+ second = index[:4]
245
+ if is_bool_dtype(index):
246
+ # i think (TODO: be sure) there assumptions baked in about
247
+ # the index fixture that don't hold here?
248
+ answer = set(first).difference(set(second))
249
+ elif isinstance(index, CategoricalIndex):
250
+ answer = []
251
+ else:
252
+ answer = index[4:]
253
+ result = first.difference(second, sort)
254
+ assert tm.equalContents(result, answer)
255
+
256
+ # GH#10149
257
+ cases = [second.to_numpy(), second.to_series(), second.to_list()]
258
+ for case in cases:
259
+ result = first.difference(case, sort)
260
+ assert tm.equalContents(result, answer)
261
+
262
+ if isinstance(index, MultiIndex):
263
+ msg = "other must be a MultiIndex or a list of tuples"
264
+ with pytest.raises(TypeError, match=msg):
265
+ first.difference([1, 2, 3], sort)
266
+
267
+ @pytest.mark.filterwarnings(
268
+ "ignore:Falling back on a non-pyarrow:pandas.errors.PerformanceWarning"
269
+ )
270
+ def test_symmetric_difference(self, index):
271
+ if isinstance(index, CategoricalIndex):
272
+ return
273
+ if len(index) < 2:
274
+ return
275
+ if index[0] in index[1:] or index[-1] in index[:-1]:
276
+ # index fixture has e.g. an index of bools that does not satisfy this,
277
+ # another with [0, 0, 1, 1, 2, 2]
278
+ return
279
+
280
+ first = index[1:]
281
+ second = index[:-1]
282
+ answer = index[[0, -1]]
283
+ result = first.symmetric_difference(second)
284
+ assert tm.equalContents(result, answer)
285
+
286
+ # GH#10149
287
+ cases = [second.to_numpy(), second.to_series(), second.to_list()]
288
+ for case in cases:
289
+ result = first.symmetric_difference(case)
290
+ assert tm.equalContents(result, answer)
291
+
292
+ if isinstance(index, MultiIndex):
293
+ msg = "other must be a MultiIndex or a list of tuples"
294
+ with pytest.raises(TypeError, match=msg):
295
+ first.symmetric_difference([1, 2, 3])
296
+
297
+ @pytest.mark.parametrize(
298
+ "fname, sname, expected_name",
299
+ [
300
+ ("A", "A", "A"),
301
+ ("A", "B", None),
302
+ ("A", None, None),
303
+ (None, "B", None),
304
+ (None, None, None),
305
+ ],
306
+ )
307
+ def test_corner_union(self, index_flat, fname, sname, expected_name):
308
+ # GH#9943, GH#9862
309
+ # Test unions with various name combinations
310
+ # Do not test MultiIndex or repeats
311
+ if not index_flat.is_unique:
312
+ pytest.skip("Randomly generated index_flat was not unique.")
313
+ index = index_flat
314
+
315
+ # Test copy.union(copy)
316
+ first = index.copy().set_names(fname)
317
+ second = index.copy().set_names(sname)
318
+ union = first.union(second)
319
+ expected = index.copy().set_names(expected_name)
320
+ tm.assert_index_equal(union, expected)
321
+
322
+ # Test copy.union(empty)
323
+ first = index.copy().set_names(fname)
324
+ second = index.drop(index).set_names(sname)
325
+ union = first.union(second)
326
+ expected = index.copy().set_names(expected_name)
327
+ tm.assert_index_equal(union, expected)
328
+
329
+ # Test empty.union(copy)
330
+ first = index.drop(index).set_names(fname)
331
+ second = index.copy().set_names(sname)
332
+ union = first.union(second)
333
+ expected = index.copy().set_names(expected_name)
334
+ tm.assert_index_equal(union, expected)
335
+
336
+ # Test empty.union(empty)
337
+ first = index.drop(index).set_names(fname)
338
+ second = index.drop(index).set_names(sname)
339
+ union = first.union(second)
340
+ expected = index.drop(index).set_names(expected_name)
341
+ tm.assert_index_equal(union, expected)
342
+
343
+ @pytest.mark.parametrize(
344
+ "fname, sname, expected_name",
345
+ [
346
+ ("A", "A", "A"),
347
+ ("A", "B", None),
348
+ ("A", None, None),
349
+ (None, "B", None),
350
+ (None, None, None),
351
+ ],
352
+ )
353
+ def test_union_unequal(self, index_flat, fname, sname, expected_name):
354
+ if not index_flat.is_unique:
355
+ pytest.skip("Randomly generated index_flat was not unique.")
356
+ index = index_flat
357
+
358
+ # test copy.union(subset) - need sort for unicode and string
359
+ first = index.copy().set_names(fname)
360
+ second = index[1:].set_names(sname)
361
+ union = first.union(second).sort_values()
362
+ expected = index.set_names(expected_name).sort_values()
363
+ tm.assert_index_equal(union, expected)
364
+
365
+ @pytest.mark.parametrize(
366
+ "fname, sname, expected_name",
367
+ [
368
+ ("A", "A", "A"),
369
+ ("A", "B", None),
370
+ ("A", None, None),
371
+ (None, "B", None),
372
+ (None, None, None),
373
+ ],
374
+ )
375
+ def test_corner_intersect(self, index_flat, fname, sname, expected_name):
376
+ # GH#35847
377
+ # Test intersections with various name combinations
378
+ if not index_flat.is_unique:
379
+ pytest.skip("Randomly generated index_flat was not unique.")
380
+ index = index_flat
381
+
382
+ # Test copy.intersection(copy)
383
+ first = index.copy().set_names(fname)
384
+ second = index.copy().set_names(sname)
385
+ intersect = first.intersection(second)
386
+ expected = index.copy().set_names(expected_name)
387
+ tm.assert_index_equal(intersect, expected)
388
+
389
+ # Test copy.intersection(empty)
390
+ first = index.copy().set_names(fname)
391
+ second = index.drop(index).set_names(sname)
392
+ intersect = first.intersection(second)
393
+ expected = index.drop(index).set_names(expected_name)
394
+ tm.assert_index_equal(intersect, expected)
395
+
396
+ # Test empty.intersection(copy)
397
+ first = index.drop(index).set_names(fname)
398
+ second = index.copy().set_names(sname)
399
+ intersect = first.intersection(second)
400
+ expected = index.drop(index).set_names(expected_name)
401
+ tm.assert_index_equal(intersect, expected)
402
+
403
+ # Test empty.intersection(empty)
404
+ first = index.drop(index).set_names(fname)
405
+ second = index.drop(index).set_names(sname)
406
+ intersect = first.intersection(second)
407
+ expected = index.drop(index).set_names(expected_name)
408
+ tm.assert_index_equal(intersect, expected)
409
+
410
+ @pytest.mark.parametrize(
411
+ "fname, sname, expected_name",
412
+ [
413
+ ("A", "A", "A"),
414
+ ("A", "B", None),
415
+ ("A", None, None),
416
+ (None, "B", None),
417
+ (None, None, None),
418
+ ],
419
+ )
420
+ def test_intersect_unequal(self, index_flat, fname, sname, expected_name):
421
+ if not index_flat.is_unique:
422
+ pytest.skip("Randomly generated index_flat was not unique.")
423
+ index = index_flat
424
+
425
+ # test copy.intersection(subset) - need sort for unicode and string
426
+ first = index.copy().set_names(fname)
427
+ second = index[1:].set_names(sname)
428
+ intersect = first.intersection(second).sort_values()
429
+ expected = index[1:].set_names(expected_name).sort_values()
430
+ tm.assert_index_equal(intersect, expected)
431
+
432
+ def test_intersection_name_retention_with_nameless(self, index):
433
+ if isinstance(index, MultiIndex):
434
+ index = index.rename(list(range(index.nlevels)))
435
+ else:
436
+ index = index.rename("foo")
437
+
438
+ other = np.asarray(index)
439
+
440
+ result = index.intersection(other)
441
+ assert result.name == index.name
442
+
443
+ # empty other, same dtype
444
+ result = index.intersection(other[:0])
445
+ assert result.name == index.name
446
+
447
+ # empty `self`
448
+ result = index[:0].intersection(other)
449
+ assert result.name == index.name
450
+
451
+ def test_difference_preserves_type_empty(self, index, sort):
452
+ # GH#20040
453
+ # If taking difference of a set and itself, it
454
+ # needs to preserve the type of the index
455
+ if not index.is_unique:
456
+ return
457
+ result = index.difference(index, sort=sort)
458
+ expected = index[:0]
459
+ tm.assert_index_equal(result, expected, exact=True)
460
+
461
+ def test_difference_name_retention_equals(self, index, names):
462
+ if isinstance(index, MultiIndex):
463
+ names = [[x] * index.nlevels for x in names]
464
+ index = index.rename(names[0])
465
+ other = index.rename(names[1])
466
+
467
+ assert index.equals(other)
468
+
469
+ result = index.difference(other)
470
+ expected = index[:0].rename(names[2])
471
+ tm.assert_index_equal(result, expected)
472
+
473
+ def test_intersection_difference_match_empty(self, index, sort):
474
+ # GH#20040
475
+ # Test that the intersection of an index with an
476
+ # empty index produces the same index as the difference
477
+ # of an index with itself. Test for all types
478
+ if not index.is_unique:
479
+ return
480
+ inter = index.intersection(index[:0])
481
+ diff = index.difference(index, sort=sort)
482
+ tm.assert_index_equal(inter, diff, exact=True)
483
+
484
+
485
+ @pytest.mark.filterwarnings(
486
+ "ignore:Falling back on a non-pyarrow:pandas.errors.PerformanceWarning"
487
+ )
488
+ @pytest.mark.parametrize(
489
+ "method", ["intersection", "union", "difference", "symmetric_difference"]
490
+ )
491
+ def test_setop_with_categorical(index_flat, sort, method):
492
+ # MultiIndex tested separately in tests.indexes.multi.test_setops
493
+ index = index_flat
494
+
495
+ other = index.astype("category")
496
+ exact = "equiv" if isinstance(index, RangeIndex) else True
497
+
498
+ result = getattr(index, method)(other, sort=sort)
499
+ expected = getattr(index, method)(index, sort=sort)
500
+ tm.assert_index_equal(result, expected, exact=exact)
501
+
502
+ result = getattr(index, method)(other[:5], sort=sort)
503
+ expected = getattr(index, method)(index[:5], sort=sort)
504
+ tm.assert_index_equal(result, expected, exact=exact)
505
+
506
+
507
+ def test_intersection_duplicates_all_indexes(index):
508
+ # GH#38743
509
+ if index.empty:
510
+ # No duplicates in empty indexes
511
+ return
512
+
513
+ idx = index
514
+ idx_non_unique = idx[[0, 0, 1, 2]]
515
+
516
+ assert idx.intersection(idx_non_unique).equals(idx_non_unique.intersection(idx))
517
+ assert idx.intersection(idx_non_unique).is_unique
518
+
519
+
520
+ def test_union_duplicate_index_subsets_of_each_other(
521
+ any_dtype_for_small_pos_integer_indexes,
522
+ ):
523
+ # GH#31326
524
+ dtype = any_dtype_for_small_pos_integer_indexes
525
+ a = Index([1, 2, 2, 3], dtype=dtype)
526
+ b = Index([3, 3, 4], dtype=dtype)
527
+
528
+ expected = Index([1, 2, 2, 3, 3, 4], dtype=dtype)
529
+ if isinstance(a, CategoricalIndex):
530
+ expected = Index([1, 2, 2, 3, 3, 4])
531
+ result = a.union(b)
532
+ tm.assert_index_equal(result, expected)
533
+ result = a.union(b, sort=False)
534
+ tm.assert_index_equal(result, expected)
535
+
536
+
537
+ def test_union_with_duplicate_index_and_non_monotonic(
538
+ any_dtype_for_small_pos_integer_indexes,
539
+ ):
540
+ # GH#36289
541
+ dtype = any_dtype_for_small_pos_integer_indexes
542
+ a = Index([1, 0, 0], dtype=dtype)
543
+ b = Index([0, 1], dtype=dtype)
544
+ expected = Index([0, 0, 1], dtype=dtype)
545
+
546
+ result = a.union(b)
547
+ tm.assert_index_equal(result, expected)
548
+
549
+ result = b.union(a)
550
+ tm.assert_index_equal(result, expected)
551
+
552
+
553
+ def test_union_duplicate_index_different_dtypes():
554
+ # GH#36289
555
+ a = Index([1, 2, 2, 3])
556
+ b = Index(["1", "0", "0"])
557
+ expected = Index([1, 2, 2, 3, "1", "0", "0"])
558
+ result = a.union(b, sort=False)
559
+ tm.assert_index_equal(result, expected)
560
+
561
+
562
+ def test_union_same_value_duplicated_in_both():
563
+ # GH#36289
564
+ a = Index([0, 0, 1])
565
+ b = Index([0, 0, 1, 2])
566
+ result = a.union(b)
567
+ expected = Index([0, 0, 1, 2])
568
+ tm.assert_index_equal(result, expected)
569
+
570
+
571
+ @pytest.mark.parametrize("dup", [1, np.nan])
572
+ def test_union_nan_in_both(dup):
573
+ # GH#36289
574
+ a = Index([np.nan, 1, 2, 2])
575
+ b = Index([np.nan, dup, 1, 2])
576
+ result = a.union(b, sort=False)
577
+ expected = Index([np.nan, dup, 1.0, 2.0, 2.0])
578
+ tm.assert_index_equal(result, expected)
579
+
580
+
581
+ def test_union_rangeindex_sort_true():
582
+ # GH 53490
583
+ idx1 = RangeIndex(1, 100, 6)
584
+ idx2 = RangeIndex(1, 50, 3)
585
+ result = idx1.union(idx2, sort=True)
586
+ expected = Index(
587
+ [
588
+ 1,
589
+ 4,
590
+ 7,
591
+ 10,
592
+ 13,
593
+ 16,
594
+ 19,
595
+ 22,
596
+ 25,
597
+ 28,
598
+ 31,
599
+ 34,
600
+ 37,
601
+ 40,
602
+ 43,
603
+ 46,
604
+ 49,
605
+ 55,
606
+ 61,
607
+ 67,
608
+ 73,
609
+ 79,
610
+ 85,
611
+ 91,
612
+ 97,
613
+ ]
614
+ )
615
+ tm.assert_index_equal(result, expected)
616
+
617
+
618
+ def test_union_with_duplicate_index_not_subset_and_non_monotonic(
619
+ any_dtype_for_small_pos_integer_indexes,
620
+ ):
621
+ # GH#36289
622
+ dtype = any_dtype_for_small_pos_integer_indexes
623
+ a = Index([1, 0, 2], dtype=dtype)
624
+ b = Index([0, 0, 1], dtype=dtype)
625
+ expected = Index([0, 0, 1, 2], dtype=dtype)
626
+ if isinstance(a, CategoricalIndex):
627
+ expected = Index([0, 0, 1, 2])
628
+
629
+ result = a.union(b)
630
+ tm.assert_index_equal(result, expected)
631
+
632
+ result = b.union(a)
633
+ tm.assert_index_equal(result, expected)
634
+
635
+
636
+ def test_union_int_categorical_with_nan():
637
+ ci = CategoricalIndex([1, 2, np.nan])
638
+ assert ci.categories.dtype.kind == "i"
639
+
640
+ idx = Index([1, 2])
641
+
642
+ result = idx.union(ci)
643
+ expected = Index([1, 2, np.nan], dtype=np.float64)
644
+ tm.assert_index_equal(result, expected)
645
+
646
+ result = ci.union(idx)
647
+ tm.assert_index_equal(result, expected)
648
+
649
+
650
+ class TestSetOpsUnsorted:
651
+ # These may eventually belong in a dtype-specific test_setops, or
652
+ # parametrized over a more general fixture
653
+ def test_intersect_str_dates(self):
654
+ dt_dates = [datetime(2012, 2, 9), datetime(2012, 2, 22)]
655
+
656
+ index1 = Index(dt_dates, dtype=object)
657
+ index2 = Index(["aa"], dtype=object)
658
+ result = index2.intersection(index1)
659
+
660
+ expected = Index([], dtype=object)
661
+ tm.assert_index_equal(result, expected)
662
+
663
+ @pytest.mark.parametrize("index", ["string"], indirect=True)
664
+ def test_intersection(self, index, sort):
665
+ first = index[:20]
666
+ second = index[:10]
667
+ intersect = first.intersection(second, sort=sort)
668
+ if sort is None:
669
+ tm.assert_index_equal(intersect, second.sort_values())
670
+ assert tm.equalContents(intersect, second)
671
+
672
+ # Corner cases
673
+ inter = first.intersection(first, sort=sort)
674
+ assert inter is first
675
+
676
+ @pytest.mark.parametrize(
677
+ "index2,keeps_name",
678
+ [
679
+ (Index([3, 4, 5, 6, 7], name="index"), True), # preserve same name
680
+ (Index([3, 4, 5, 6, 7], name="other"), False), # drop diff names
681
+ (Index([3, 4, 5, 6, 7]), False),
682
+ ],
683
+ )
684
+ def test_intersection_name_preservation(self, index2, keeps_name, sort):
685
+ index1 = Index([1, 2, 3, 4, 5], name="index")
686
+ expected = Index([3, 4, 5])
687
+ result = index1.intersection(index2, sort)
688
+
689
+ if keeps_name:
690
+ expected.name = "index"
691
+
692
+ assert result.name == expected.name
693
+ tm.assert_index_equal(result, expected)
694
+
695
+ @pytest.mark.parametrize("index", ["string"], indirect=True)
696
+ @pytest.mark.parametrize(
697
+ "first_name,second_name,expected_name",
698
+ [("A", "A", "A"), ("A", "B", None), (None, "B", None)],
699
+ )
700
+ def test_intersection_name_preservation2(
701
+ self, index, first_name, second_name, expected_name, sort
702
+ ):
703
+ first = index[5:20]
704
+ second = index[:10]
705
+ first.name = first_name
706
+ second.name = second_name
707
+ intersect = first.intersection(second, sort=sort)
708
+ assert intersect.name == expected_name
709
+
710
+ def test_chained_union(self, sort):
711
+ # Chained unions handles names correctly
712
+ i1 = Index([1, 2], name="i1")
713
+ i2 = Index([5, 6], name="i2")
714
+ i3 = Index([3, 4], name="i3")
715
+ union = i1.union(i2.union(i3, sort=sort), sort=sort)
716
+ expected = i1.union(i2, sort=sort).union(i3, sort=sort)
717
+ tm.assert_index_equal(union, expected)
718
+
719
+ j1 = Index([1, 2], name="j1")
720
+ j2 = Index([], name="j2")
721
+ j3 = Index([], name="j3")
722
+ union = j1.union(j2.union(j3, sort=sort), sort=sort)
723
+ expected = j1.union(j2, sort=sort).union(j3, sort=sort)
724
+ tm.assert_index_equal(union, expected)
725
+
726
+ @pytest.mark.parametrize("index", ["string"], indirect=True)
727
+ def test_union(self, index, sort):
728
+ first = index[5:20]
729
+ second = index[:10]
730
+ everything = index[:20]
731
+
732
+ union = first.union(second, sort=sort)
733
+ if sort is None:
734
+ tm.assert_index_equal(union, everything.sort_values())
735
+ assert tm.equalContents(union, everything)
736
+
737
+ @pytest.mark.parametrize("klass", [np.array, Series, list])
738
+ @pytest.mark.parametrize("index", ["string"], indirect=True)
739
+ def test_union_from_iterables(self, index, klass, sort):
740
+ # GH#10149
741
+ first = index[5:20]
742
+ second = index[:10]
743
+ everything = index[:20]
744
+
745
+ case = klass(second.values)
746
+ result = first.union(case, sort=sort)
747
+ if sort is None:
748
+ tm.assert_index_equal(result, everything.sort_values())
749
+ assert tm.equalContents(result, everything)
750
+
751
+ @pytest.mark.parametrize("index", ["string"], indirect=True)
752
+ def test_union_identity(self, index, sort):
753
+ first = index[5:20]
754
+
755
+ union = first.union(first, sort=sort)
756
+ # i.e. identity is not preserved when sort is True
757
+ assert (union is first) is (not sort)
758
+
759
+ # This should no longer be the same object, since [] is not consistent,
760
+ # both objects will be recast to dtype('O')
761
+ union = first.union([], sort=sort)
762
+ assert (union is first) is (not sort)
763
+
764
+ union = Index([]).union(first, sort=sort)
765
+ assert (union is first) is (not sort)
766
+
767
+ @pytest.mark.parametrize("index", ["string"], indirect=True)
768
+ @pytest.mark.parametrize("second_name,expected", [(None, None), ("name", "name")])
769
+ def test_difference_name_preservation(self, index, second_name, expected, sort):
770
+ first = index[5:20]
771
+ second = index[:10]
772
+ answer = index[10:20]
773
+
774
+ first.name = "name"
775
+ second.name = second_name
776
+ result = first.difference(second, sort=sort)
777
+
778
+ assert tm.equalContents(result, answer)
779
+
780
+ if expected is None:
781
+ assert result.name is None
782
+ else:
783
+ assert result.name == expected
784
+
785
+ def test_difference_empty_arg(self, index, sort):
786
+ first = index[5:20]
787
+ first.name = "name"
788
+ result = first.difference([], sort)
789
+
790
+ tm.assert_index_equal(result, first)
791
+
792
+ @pytest.mark.parametrize("index", ["string"], indirect=True)
793
+ def test_difference_identity(self, index, sort):
794
+ first = index[5:20]
795
+ first.name = "name"
796
+ result = first.difference(first, sort)
797
+
798
+ assert len(result) == 0
799
+ assert result.name == first.name
800
+
801
+ @pytest.mark.parametrize("index", ["string"], indirect=True)
802
+ def test_difference_sort(self, index, sort):
803
+ first = index[5:20]
804
+ second = index[:10]
805
+
806
+ result = first.difference(second, sort)
807
+ expected = index[10:20]
808
+
809
+ if sort is None:
810
+ expected = expected.sort_values()
811
+
812
+ tm.assert_index_equal(result, expected)
813
+
814
+ @pytest.mark.parametrize("opname", ["difference", "symmetric_difference"])
815
+ def test_difference_incomparable(self, opname):
816
+ a = Index([3, Timestamp("2000"), 1])
817
+ b = Index([2, Timestamp("1999"), 1])
818
+ op = operator.methodcaller(opname, b)
819
+
820
+ with tm.assert_produces_warning(RuntimeWarning):
821
+ # sort=None, the default
822
+ result = op(a)
823
+ expected = Index([3, Timestamp("2000"), 2, Timestamp("1999")])
824
+ if opname == "difference":
825
+ expected = expected[:2]
826
+ tm.assert_index_equal(result, expected)
827
+
828
+ # sort=False
829
+ op = operator.methodcaller(opname, b, sort=False)
830
+ result = op(a)
831
+ tm.assert_index_equal(result, expected)
832
+
833
+ @pytest.mark.parametrize("opname", ["difference", "symmetric_difference"])
834
+ def test_difference_incomparable_true(self, opname):
835
+ a = Index([3, Timestamp("2000"), 1])
836
+ b = Index([2, Timestamp("1999"), 1])
837
+ op = operator.methodcaller(opname, b, sort=True)
838
+
839
+ msg = "'<' not supported between instances of 'Timestamp' and 'int'"
840
+ with pytest.raises(TypeError, match=msg):
841
+ op(a)
842
+
843
+ def test_symmetric_difference_mi(self, sort):
844
+ index1 = MultiIndex.from_tuples(zip(["foo", "bar", "baz"], [1, 2, 3]))
845
+ index2 = MultiIndex.from_tuples([("foo", 1), ("bar", 3)])
846
+ result = index1.symmetric_difference(index2, sort=sort)
847
+ expected = MultiIndex.from_tuples([("bar", 2), ("baz", 3), ("bar", 3)])
848
+ if sort is None:
849
+ expected = expected.sort_values()
850
+ tm.assert_index_equal(result, expected)
851
+ assert tm.equalContents(result, expected)
852
+
853
+ @pytest.mark.parametrize(
854
+ "index2,expected",
855
+ [
856
+ (Index([0, 1, np.nan]), Index([2.0, 3.0, 0.0])),
857
+ (Index([0, 1]), Index([np.nan, 2.0, 3.0, 0.0])),
858
+ ],
859
+ )
860
+ def test_symmetric_difference_missing(self, index2, expected, sort):
861
+ # GH#13514 change: {nan} - {nan} == {}
862
+ # (GH#6444, sorting of nans, is no longer an issue)
863
+ index1 = Index([1, np.nan, 2, 3])
864
+
865
+ result = index1.symmetric_difference(index2, sort=sort)
866
+ if sort is None:
867
+ expected = expected.sort_values()
868
+ tm.assert_index_equal(result, expected)
869
+
870
+ def test_symmetric_difference_non_index(self, sort):
871
+ index1 = Index([1, 2, 3, 4], name="index1")
872
+ index2 = np.array([2, 3, 4, 5])
873
+ expected = Index([1, 5])
874
+ result = index1.symmetric_difference(index2, sort=sort)
875
+ assert tm.equalContents(result, expected)
876
+ assert result.name == "index1"
877
+
878
+ result = index1.symmetric_difference(index2, result_name="new_name", sort=sort)
879
+ assert tm.equalContents(result, expected)
880
+ assert result.name == "new_name"
881
+
882
+ def test_union_ea_dtypes(self, any_numeric_ea_and_arrow_dtype):
883
+ # GH#51365
884
+ idx = Index([1, 2, 3], dtype=any_numeric_ea_and_arrow_dtype)
885
+ idx2 = Index([3, 4, 5], dtype=any_numeric_ea_and_arrow_dtype)
886
+ result = idx.union(idx2)
887
+ expected = Index([1, 2, 3, 4, 5], dtype=any_numeric_ea_and_arrow_dtype)
888
+ tm.assert_index_equal(result, expected)
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/test_subclass.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.randn(2, 3), columns=idx, index=Index([1, 2], name="string")
36
+ )
37
+ result = df.reset_index()
38
+ tm.assert_index_equal(result.columns, expected)
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__init__.py ADDED
File without changes
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_constructors.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import timedelta
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ import pandas as pd
7
+ from pandas import (
8
+ Timedelta,
9
+ TimedeltaIndex,
10
+ timedelta_range,
11
+ to_timedelta,
12
+ )
13
+ import pandas._testing as tm
14
+ from pandas.core.arrays.timedeltas import (
15
+ TimedeltaArray,
16
+ sequence_to_td64ns,
17
+ )
18
+
19
+
20
+ class TestTimedeltaIndex:
21
+ def test_array_of_dt64_nat_raises(self):
22
+ # GH#39462
23
+ nat = np.datetime64("NaT", "ns")
24
+ arr = np.array([nat], dtype=object)
25
+
26
+ msg = "Invalid type for timedelta scalar"
27
+ with pytest.raises(TypeError, match=msg):
28
+ TimedeltaIndex(arr)
29
+
30
+ with pytest.raises(TypeError, match=msg):
31
+ TimedeltaArray._from_sequence(arr)
32
+
33
+ with pytest.raises(TypeError, match=msg):
34
+ sequence_to_td64ns(arr)
35
+
36
+ with pytest.raises(TypeError, match=msg):
37
+ to_timedelta(arr)
38
+
39
+ @pytest.mark.parametrize("unit", ["Y", "y", "M"])
40
+ def test_unit_m_y_raises(self, unit):
41
+ msg = "Units 'M', 'Y', and 'y' are no longer supported"
42
+ with pytest.raises(ValueError, match=msg):
43
+ TimedeltaIndex([1, 3, 7], unit)
44
+
45
+ def test_int64_nocopy(self):
46
+ # GH#23539 check that a copy isn't made when we pass int64 data
47
+ # and copy=False
48
+ arr = np.arange(10, dtype=np.int64)
49
+ tdi = TimedeltaIndex(arr, copy=False)
50
+ assert tdi._data._ndarray.base is arr
51
+
52
+ def test_infer_from_tdi(self):
53
+ # GH#23539
54
+ # fast-path for inferring a frequency if the passed data already
55
+ # has one
56
+ tdi = timedelta_range("1 second", periods=10**7, freq="1s")
57
+
58
+ result = TimedeltaIndex(tdi, freq="infer")
59
+ assert result.freq == tdi.freq
60
+
61
+ # check that inferred_freq was not called by checking that the
62
+ # value has not been cached
63
+ assert "inferred_freq" not in getattr(result, "_cache", {})
64
+
65
+ def test_infer_from_tdi_mismatch(self):
66
+ # GH#23539
67
+ # fast-path for invalidating a frequency if the passed data already
68
+ # has one and it does not match the `freq` input
69
+ tdi = timedelta_range("1 second", periods=100, freq="1s")
70
+
71
+ msg = (
72
+ "Inferred frequency .* from passed values does "
73
+ "not conform to passed frequency"
74
+ )
75
+ with pytest.raises(ValueError, match=msg):
76
+ TimedeltaIndex(tdi, freq="D")
77
+
78
+ with pytest.raises(ValueError, match=msg):
79
+ # GH#23789
80
+ TimedeltaArray(tdi, freq="D")
81
+
82
+ with pytest.raises(ValueError, match=msg):
83
+ TimedeltaIndex(tdi._data, freq="D")
84
+
85
+ with pytest.raises(ValueError, match=msg):
86
+ TimedeltaArray(tdi._data, freq="D")
87
+
88
+ def test_dt64_data_invalid(self):
89
+ # GH#23539
90
+ # passing tz-aware DatetimeIndex raises, naive or ndarray[datetime64]
91
+ # raise as of GH#29794
92
+ dti = pd.date_range("2016-01-01", periods=3)
93
+
94
+ msg = "cannot be converted to timedelta64"
95
+ with pytest.raises(TypeError, match=msg):
96
+ TimedeltaIndex(dti.tz_localize("Europe/Brussels"))
97
+
98
+ with pytest.raises(TypeError, match=msg):
99
+ TimedeltaIndex(dti)
100
+
101
+ with pytest.raises(TypeError, match=msg):
102
+ TimedeltaIndex(np.asarray(dti))
103
+
104
+ def test_float64_ns_rounded(self):
105
+ # GH#23539 without specifying a unit, floats are regarded as nanos,
106
+ # and fractional portions are truncated
107
+ tdi = TimedeltaIndex([2.3, 9.7])
108
+ expected = TimedeltaIndex([2, 9])
109
+ tm.assert_index_equal(tdi, expected)
110
+
111
+ # integral floats are non-lossy
112
+ tdi = TimedeltaIndex([2.0, 9.0])
113
+ expected = TimedeltaIndex([2, 9])
114
+ tm.assert_index_equal(tdi, expected)
115
+
116
+ # NaNs get converted to NaT
117
+ tdi = TimedeltaIndex([2.0, np.nan])
118
+ expected = TimedeltaIndex([Timedelta(nanoseconds=2), pd.NaT])
119
+ tm.assert_index_equal(tdi, expected)
120
+
121
+ def test_float64_unit_conversion(self):
122
+ # GH#23539
123
+ tdi = TimedeltaIndex([1.5, 2.25], unit="D")
124
+ expected = TimedeltaIndex([Timedelta(days=1.5), Timedelta(days=2.25)])
125
+ tm.assert_index_equal(tdi, expected)
126
+
127
+ def test_construction_base_constructor(self):
128
+ arr = [Timedelta("1 days"), pd.NaT, Timedelta("3 days")]
129
+ tm.assert_index_equal(pd.Index(arr), TimedeltaIndex(arr))
130
+ tm.assert_index_equal(pd.Index(np.array(arr)), TimedeltaIndex(np.array(arr)))
131
+
132
+ arr = [np.nan, pd.NaT, Timedelta("1 days")]
133
+ tm.assert_index_equal(pd.Index(arr), TimedeltaIndex(arr))
134
+ tm.assert_index_equal(pd.Index(np.array(arr)), TimedeltaIndex(np.array(arr)))
135
+
136
+ def test_constructor(self):
137
+ expected = TimedeltaIndex(
138
+ [
139
+ "1 days",
140
+ "1 days 00:00:05",
141
+ "2 days",
142
+ "2 days 00:00:02",
143
+ "0 days 00:00:03",
144
+ ]
145
+ )
146
+ result = TimedeltaIndex(
147
+ [
148
+ "1 days",
149
+ "1 days, 00:00:05",
150
+ np.timedelta64(2, "D"),
151
+ timedelta(days=2, seconds=2),
152
+ pd.offsets.Second(3),
153
+ ]
154
+ )
155
+ tm.assert_index_equal(result, expected)
156
+
157
+ expected = TimedeltaIndex(
158
+ ["0 days 00:00:00", "0 days 00:00:01", "0 days 00:00:02"]
159
+ )
160
+ tm.assert_index_equal(TimedeltaIndex(range(3), unit="s"), expected)
161
+ expected = TimedeltaIndex(
162
+ ["0 days 00:00:00", "0 days 00:00:05", "0 days 00:00:09"]
163
+ )
164
+ tm.assert_index_equal(TimedeltaIndex([0, 5, 9], unit="s"), expected)
165
+ expected = TimedeltaIndex(
166
+ ["0 days 00:00:00.400", "0 days 00:00:00.450", "0 days 00:00:01.200"]
167
+ )
168
+ tm.assert_index_equal(TimedeltaIndex([400, 450, 1200], unit="ms"), expected)
169
+
170
+ def test_constructor_iso(self):
171
+ # GH #21877
172
+ expected = timedelta_range("1s", periods=9, freq="s")
173
+ durations = [f"P0DT0H0M{i}S" for i in range(1, 10)]
174
+ result = to_timedelta(durations)
175
+ tm.assert_index_equal(result, expected)
176
+
177
+ def test_constructor_coverage(self):
178
+ rng = timedelta_range("1 days", periods=10.5)
179
+ exp = timedelta_range("1 days", periods=10)
180
+ tm.assert_index_equal(rng, exp)
181
+
182
+ msg = "periods must be a number, got foo"
183
+ with pytest.raises(TypeError, match=msg):
184
+ timedelta_range(start="1 days", periods="foo", freq="D")
185
+
186
+ msg = (
187
+ r"TimedeltaIndex\(\.\.\.\) must be called with a collection of some kind, "
188
+ "'1 days' was passed"
189
+ )
190
+ with pytest.raises(TypeError, match=msg):
191
+ TimedeltaIndex("1 days")
192
+
193
+ # generator expression
194
+ gen = (timedelta(i) for i in range(10))
195
+ result = TimedeltaIndex(gen)
196
+ expected = TimedeltaIndex([timedelta(i) for i in range(10)])
197
+ tm.assert_index_equal(result, expected)
198
+
199
+ # NumPy string array
200
+ strings = np.array(["1 days", "2 days", "3 days"])
201
+ result = TimedeltaIndex(strings)
202
+ expected = to_timedelta([1, 2, 3], unit="d")
203
+ tm.assert_index_equal(result, expected)
204
+
205
+ from_ints = TimedeltaIndex(expected.asi8)
206
+ tm.assert_index_equal(from_ints, expected)
207
+
208
+ # non-conforming freq
209
+ msg = (
210
+ "Inferred frequency None from passed values does not conform to "
211
+ "passed frequency D"
212
+ )
213
+ with pytest.raises(ValueError, match=msg):
214
+ TimedeltaIndex(["1 days", "2 days", "4 days"], freq="D")
215
+
216
+ msg = (
217
+ "Of the four parameters: start, end, periods, and freq, exactly "
218
+ "three must be specified"
219
+ )
220
+ with pytest.raises(ValueError, match=msg):
221
+ timedelta_range(periods=10, freq="D")
222
+
223
+ def test_constructor_name(self):
224
+ idx = timedelta_range(start="1 days", periods=1, freq="D", name="TEST")
225
+ assert idx.name == "TEST"
226
+
227
+ # GH10025
228
+ idx2 = TimedeltaIndex(idx, name="something else")
229
+ assert idx2.name == "something else"
230
+
231
+ def test_constructor_no_precision_raises(self):
232
+ # GH-24753, GH-24739
233
+
234
+ msg = "with no precision is not allowed"
235
+ with pytest.raises(ValueError, match=msg):
236
+ TimedeltaIndex(["2000"], dtype="timedelta64")
237
+
238
+ msg = "The 'timedelta64' dtype has no unit. Please pass in"
239
+ with pytest.raises(ValueError, match=msg):
240
+ pd.Index(["2000"], dtype="timedelta64")
241
+
242
+ def test_constructor_wrong_precision_raises(self):
243
+ msg = r"dtype timedelta64\[D\] cannot be converted to timedelta64\[ns\]"
244
+ with pytest.raises(ValueError, match=msg):
245
+ TimedeltaIndex(["2000"], dtype="timedelta64[D]")
246
+
247
+ # "timedelta64[us]" was unsupported pre-2.0, but now this works.
248
+ tdi = TimedeltaIndex(["2000"], dtype="timedelta64[us]")
249
+ assert tdi.dtype == "m8[us]"
250
+
251
+ def test_explicit_none_freq(self):
252
+ # Explicitly passing freq=None is respected
253
+ tdi = timedelta_range(1, periods=5)
254
+ assert tdi.freq is not None
255
+
256
+ result = TimedeltaIndex(tdi, freq=None)
257
+ assert result.freq is None
258
+
259
+ result = TimedeltaIndex(tdi._data, freq=None)
260
+ assert result.freq is None
261
+
262
+ tda = TimedeltaArray(tdi, freq=None)
263
+ assert tda.freq is None
264
+
265
+ def test_from_categorical(self):
266
+ tdi = timedelta_range(1, periods=5)
267
+
268
+ cat = pd.Categorical(tdi)
269
+
270
+ result = TimedeltaIndex(cat)
271
+ tm.assert_index_equal(result, tdi)
272
+
273
+ ci = pd.CategoricalIndex(tdi)
274
+ result = TimedeltaIndex(ci)
275
+ tm.assert_index_equal(result, tdi)
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_freq_attr.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from pandas import TimedeltaIndex
4
+
5
+ from pandas.tseries.offsets import (
6
+ DateOffset,
7
+ Day,
8
+ Hour,
9
+ )
10
+
11
+
12
+ class TestFreq:
13
+ @pytest.mark.parametrize("values", [["0 days", "2 days", "4 days"], []])
14
+ @pytest.mark.parametrize("freq", ["2D", Day(2), "48H", Hour(48)])
15
+ def test_freq_setter(self, values, freq):
16
+ # GH#20678
17
+ idx = TimedeltaIndex(values)
18
+
19
+ # can set to an offset, converting from string if necessary
20
+ idx._data.freq = freq
21
+ assert idx.freq == freq
22
+ assert isinstance(idx.freq, DateOffset)
23
+
24
+ # can reset to None
25
+ idx._data.freq = None
26
+ assert idx.freq is None
27
+
28
+ def test_freq_setter_errors(self):
29
+ # GH#20678
30
+ idx = TimedeltaIndex(["0 days", "2 days", "4 days"])
31
+
32
+ # setting with an incompatible freq
33
+ msg = (
34
+ "Inferred frequency 2D from passed values does not conform to "
35
+ "passed frequency 5D"
36
+ )
37
+ with pytest.raises(ValueError, match=msg):
38
+ idx._data.freq = "5D"
39
+
40
+ # setting with a non-fixed frequency
41
+ msg = r"<2 \* BusinessDays> is a non-fixed frequency"
42
+ with pytest.raises(ValueError, match=msg):
43
+ idx._data.freq = "2B"
44
+
45
+ # setting with non-freq string
46
+ with pytest.raises(ValueError, match="Invalid frequency"):
47
+ idx._data.freq = "foo"
48
+
49
+ def test_freq_view_safe(self):
50
+ # Setting the freq for one TimedeltaIndex shouldn't alter the freq
51
+ # for another that views the same data
52
+
53
+ tdi = TimedeltaIndex(["0 days", "2 days", "4 days"], freq="2D")
54
+ tda = tdi._data
55
+
56
+ tdi2 = TimedeltaIndex(tda)._with_freq(None)
57
+ assert tdi2.freq is None
58
+
59
+ # Original was not altered
60
+ assert tdi.freq == "2D"
61
+ assert tda.freq == "2D"
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_indexing.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ import re
3
+
4
+ import numpy as np
5
+ import pytest
6
+
7
+ from pandas import (
8
+ Index,
9
+ NaT,
10
+ Timedelta,
11
+ TimedeltaIndex,
12
+ Timestamp,
13
+ notna,
14
+ offsets,
15
+ timedelta_range,
16
+ to_timedelta,
17
+ )
18
+ import pandas._testing as tm
19
+
20
+
21
+ class TestGetItem:
22
+ def test_getitem_slice_keeps_name(self):
23
+ # GH#4226
24
+ tdi = timedelta_range("1d", "5d", freq="H", name="timebucket")
25
+ assert tdi[1:].name == tdi.name
26
+
27
+ def test_getitem(self):
28
+ idx1 = timedelta_range("1 day", "31 day", freq="D", name="idx")
29
+
30
+ for idx in [idx1]:
31
+ result = idx[0]
32
+ assert result == Timedelta("1 day")
33
+
34
+ result = idx[0:5]
35
+ expected = timedelta_range("1 day", "5 day", freq="D", name="idx")
36
+ tm.assert_index_equal(result, expected)
37
+ assert result.freq == expected.freq
38
+
39
+ result = idx[0:10:2]
40
+ expected = timedelta_range("1 day", "9 day", freq="2D", name="idx")
41
+ tm.assert_index_equal(result, expected)
42
+ assert result.freq == expected.freq
43
+
44
+ result = idx[-20:-5:3]
45
+ expected = timedelta_range("12 day", "24 day", freq="3D", name="idx")
46
+ tm.assert_index_equal(result, expected)
47
+ assert result.freq == expected.freq
48
+
49
+ result = idx[4::-1]
50
+ expected = TimedeltaIndex(
51
+ ["5 day", "4 day", "3 day", "2 day", "1 day"], freq="-1D", name="idx"
52
+ )
53
+ tm.assert_index_equal(result, expected)
54
+ assert result.freq == expected.freq
55
+
56
+ @pytest.mark.parametrize(
57
+ "key",
58
+ [
59
+ Timestamp("1970-01-01"),
60
+ Timestamp("1970-01-02"),
61
+ datetime(1970, 1, 1),
62
+ Timestamp("1970-01-03").to_datetime64(),
63
+ # non-matching NA values
64
+ np.datetime64("NaT"),
65
+ ],
66
+ )
67
+ def test_timestamp_invalid_key(self, key):
68
+ # GH#20464
69
+ tdi = timedelta_range(0, periods=10)
70
+ with pytest.raises(KeyError, match=re.escape(repr(key))):
71
+ tdi.get_loc(key)
72
+
73
+
74
+ class TestGetLoc:
75
+ def test_get_loc_key_unit_mismatch(self):
76
+ idx = to_timedelta(["0 days", "1 days", "2 days"])
77
+ key = idx[1].as_unit("ms")
78
+ loc = idx.get_loc(key)
79
+ assert loc == 1
80
+
81
+ def test_get_loc_key_unit_mismatch_not_castable(self):
82
+ tdi = to_timedelta(["0 days", "1 days", "2 days"]).astype("m8[s]")
83
+ assert tdi.dtype == "m8[s]"
84
+ key = tdi[0].as_unit("ns") + Timedelta(1)
85
+
86
+ with pytest.raises(KeyError, match=r"Timedelta\('0 days 00:00:00.000000001'\)"):
87
+ tdi.get_loc(key)
88
+
89
+ assert key not in tdi
90
+
91
+ def test_get_loc(self):
92
+ idx = to_timedelta(["0 days", "1 days", "2 days"])
93
+
94
+ # GH 16909
95
+ assert idx.get_loc(idx[1].to_timedelta64()) == 1
96
+
97
+ # GH 16896
98
+ assert idx.get_loc("0 days") == 0
99
+
100
+ def test_get_loc_nat(self):
101
+ tidx = TimedeltaIndex(["1 days 01:00:00", "NaT", "2 days 01:00:00"])
102
+
103
+ assert tidx.get_loc(NaT) == 1
104
+ assert tidx.get_loc(None) == 1
105
+ assert tidx.get_loc(float("nan")) == 1
106
+ assert tidx.get_loc(np.nan) == 1
107
+
108
+
109
+ class TestGetIndexer:
110
+ def test_get_indexer(self):
111
+ idx = to_timedelta(["0 days", "1 days", "2 days"])
112
+ tm.assert_numpy_array_equal(
113
+ idx.get_indexer(idx), np.array([0, 1, 2], dtype=np.intp)
114
+ )
115
+
116
+ target = to_timedelta(["-1 hour", "12 hours", "1 day 1 hour"])
117
+ tm.assert_numpy_array_equal(
118
+ idx.get_indexer(target, "pad"), np.array([-1, 0, 1], dtype=np.intp)
119
+ )
120
+ tm.assert_numpy_array_equal(
121
+ idx.get_indexer(target, "backfill"), np.array([0, 1, 2], dtype=np.intp)
122
+ )
123
+ tm.assert_numpy_array_equal(
124
+ idx.get_indexer(target, "nearest"), np.array([0, 1, 1], dtype=np.intp)
125
+ )
126
+
127
+ res = idx.get_indexer(target, "nearest", tolerance=Timedelta("1 hour"))
128
+ tm.assert_numpy_array_equal(res, np.array([0, -1, 1], dtype=np.intp))
129
+
130
+
131
+ class TestWhere:
132
+ def test_where_doesnt_retain_freq(self):
133
+ tdi = timedelta_range("1 day", periods=3, freq="D", name="idx")
134
+ cond = [True, True, False]
135
+ expected = TimedeltaIndex([tdi[0], tdi[1], tdi[0]], freq=None, name="idx")
136
+
137
+ result = tdi.where(cond, tdi[::-1])
138
+ tm.assert_index_equal(result, expected)
139
+
140
+ def test_where_invalid_dtypes(self, fixed_now_ts):
141
+ tdi = timedelta_range("1 day", periods=3, freq="D", name="idx")
142
+
143
+ tail = tdi[2:].tolist()
144
+ i2 = Index([NaT, NaT] + tail)
145
+ mask = notna(i2)
146
+
147
+ expected = Index([NaT._value, NaT._value] + tail, dtype=object, name="idx")
148
+ assert isinstance(expected[0], int)
149
+ result = tdi.where(mask, i2.asi8)
150
+ tm.assert_index_equal(result, expected)
151
+
152
+ ts = i2 + fixed_now_ts
153
+ expected = Index([ts[0], ts[1]] + tail, dtype=object, name="idx")
154
+ result = tdi.where(mask, ts)
155
+ tm.assert_index_equal(result, expected)
156
+
157
+ per = (i2 + fixed_now_ts).to_period("D")
158
+ expected = Index([per[0], per[1]] + tail, dtype=object, name="idx")
159
+ result = tdi.where(mask, per)
160
+ tm.assert_index_equal(result, expected)
161
+
162
+ ts = fixed_now_ts
163
+ expected = Index([ts, ts] + tail, dtype=object, name="idx")
164
+ result = tdi.where(mask, ts)
165
+ tm.assert_index_equal(result, expected)
166
+
167
+ def test_where_mismatched_nat(self):
168
+ tdi = timedelta_range("1 day", periods=3, freq="D", name="idx")
169
+ cond = np.array([True, False, False])
170
+
171
+ dtnat = np.datetime64("NaT", "ns")
172
+ expected = Index([tdi[0], dtnat, dtnat], dtype=object, name="idx")
173
+ assert expected[2] is dtnat
174
+ result = tdi.where(cond, dtnat)
175
+ tm.assert_index_equal(result, expected)
176
+
177
+
178
+ class TestTake:
179
+ def test_take(self):
180
+ # GH 10295
181
+ idx1 = timedelta_range("1 day", "31 day", freq="D", name="idx")
182
+
183
+ for idx in [idx1]:
184
+ result = idx.take([0])
185
+ assert result == Timedelta("1 day")
186
+
187
+ result = idx.take([-1])
188
+ assert result == Timedelta("31 day")
189
+
190
+ result = idx.take([0, 1, 2])
191
+ expected = timedelta_range("1 day", "3 day", freq="D", name="idx")
192
+ tm.assert_index_equal(result, expected)
193
+ assert result.freq == expected.freq
194
+
195
+ result = idx.take([0, 2, 4])
196
+ expected = timedelta_range("1 day", "5 day", freq="2D", name="idx")
197
+ tm.assert_index_equal(result, expected)
198
+ assert result.freq == expected.freq
199
+
200
+ result = idx.take([7, 4, 1])
201
+ expected = timedelta_range("8 day", "2 day", freq="-3D", name="idx")
202
+ tm.assert_index_equal(result, expected)
203
+ assert result.freq == expected.freq
204
+
205
+ result = idx.take([3, 2, 5])
206
+ expected = TimedeltaIndex(["4 day", "3 day", "6 day"], name="idx")
207
+ tm.assert_index_equal(result, expected)
208
+ assert result.freq is None
209
+
210
+ result = idx.take([-3, 2, 5])
211
+ expected = TimedeltaIndex(["29 day", "3 day", "6 day"], name="idx")
212
+ tm.assert_index_equal(result, expected)
213
+ assert result.freq is None
214
+
215
+ def test_take_invalid_kwargs(self):
216
+ idx = timedelta_range("1 day", "31 day", freq="D", name="idx")
217
+ indices = [1, 6, 5, 9, 10, 13, 15, 3]
218
+
219
+ msg = r"take\(\) got an unexpected keyword argument 'foo'"
220
+ with pytest.raises(TypeError, match=msg):
221
+ idx.take(indices, foo=2)
222
+
223
+ msg = "the 'out' parameter is not supported"
224
+ with pytest.raises(ValueError, match=msg):
225
+ idx.take(indices, out=indices)
226
+
227
+ msg = "the 'mode' parameter is not supported"
228
+ with pytest.raises(ValueError, match=msg):
229
+ idx.take(indices, mode="clip")
230
+
231
+ def test_take_equiv_getitem(self):
232
+ tds = ["1day 02:00:00", "1 day 04:00:00", "1 day 10:00:00"]
233
+ idx = timedelta_range(start="1d", end="2d", freq="H", name="idx")
234
+ expected = TimedeltaIndex(tds, freq=None, name="idx")
235
+
236
+ taken1 = idx.take([2, 4, 10])
237
+ taken2 = idx[[2, 4, 10]]
238
+
239
+ for taken in [taken1, taken2]:
240
+ tm.assert_index_equal(taken, expected)
241
+ assert isinstance(taken, TimedeltaIndex)
242
+ assert taken.freq is None
243
+ assert taken.name == expected.name
244
+
245
+ def test_take_fill_value(self):
246
+ # GH 12631
247
+ idx = TimedeltaIndex(["1 days", "2 days", "3 days"], name="xxx")
248
+ result = idx.take(np.array([1, 0, -1]))
249
+ expected = TimedeltaIndex(["2 days", "1 days", "3 days"], name="xxx")
250
+ tm.assert_index_equal(result, expected)
251
+
252
+ # fill_value
253
+ result = idx.take(np.array([1, 0, -1]), fill_value=True)
254
+ expected = TimedeltaIndex(["2 days", "1 days", "NaT"], name="xxx")
255
+ tm.assert_index_equal(result, expected)
256
+
257
+ # allow_fill=False
258
+ result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True)
259
+ expected = TimedeltaIndex(["2 days", "1 days", "3 days"], name="xxx")
260
+ tm.assert_index_equal(result, expected)
261
+
262
+ msg = (
263
+ "When allow_fill=True and fill_value is not None, "
264
+ "all indices must be >= -1"
265
+ )
266
+ with pytest.raises(ValueError, match=msg):
267
+ idx.take(np.array([1, 0, -2]), fill_value=True)
268
+ with pytest.raises(ValueError, match=msg):
269
+ idx.take(np.array([1, 0, -5]), fill_value=True)
270
+
271
+ msg = "index -5 is out of bounds for (axis 0 with )?size 3"
272
+ with pytest.raises(IndexError, match=msg):
273
+ idx.take(np.array([1, -5]))
274
+
275
+
276
+ class TestMaybeCastSliceBound:
277
+ @pytest.fixture(params=["increasing", "decreasing", None])
278
+ def monotonic(self, request):
279
+ return request.param
280
+
281
+ @pytest.fixture
282
+ def tdi(self, monotonic):
283
+ tdi = timedelta_range("1 Day", periods=10)
284
+ if monotonic == "decreasing":
285
+ tdi = tdi[::-1]
286
+ elif monotonic is None:
287
+ taker = np.arange(10, dtype=np.intp)
288
+ np.random.shuffle(taker)
289
+ tdi = tdi.take(taker)
290
+ return tdi
291
+
292
+ def test_maybe_cast_slice_bound_invalid_str(self, tdi):
293
+ # test the low-level _maybe_cast_slice_bound and that we get the
294
+ # expected exception+message all the way up the stack
295
+ msg = (
296
+ "cannot do slice indexing on TimedeltaIndex with these "
297
+ r"indexers \[foo\] of type str"
298
+ )
299
+ with pytest.raises(TypeError, match=msg):
300
+ tdi._maybe_cast_slice_bound("foo", side="left")
301
+ with pytest.raises(TypeError, match=msg):
302
+ tdi.get_slice_bound("foo", side="left")
303
+ with pytest.raises(TypeError, match=msg):
304
+ tdi.slice_locs("foo", None, None)
305
+
306
+ def test_slice_invalid_str_with_timedeltaindex(
307
+ self, tdi, frame_or_series, indexer_sl
308
+ ):
309
+ obj = frame_or_series(range(10), index=tdi)
310
+
311
+ msg = (
312
+ "cannot do slice indexing on TimedeltaIndex with these "
313
+ r"indexers \[foo\] of type str"
314
+ )
315
+ with pytest.raises(TypeError, match=msg):
316
+ indexer_sl(obj)["foo":]
317
+ with pytest.raises(TypeError, match=msg):
318
+ indexer_sl(obj)["foo":-1]
319
+ with pytest.raises(TypeError, match=msg):
320
+ indexer_sl(obj)[:"foo"]
321
+ with pytest.raises(TypeError, match=msg):
322
+ indexer_sl(obj)[tdi[0] : "foo"]
323
+
324
+
325
+ class TestContains:
326
+ def test_contains_nonunique(self):
327
+ # GH#9512
328
+ for vals in (
329
+ [0, 1, 0],
330
+ [0, 0, -1],
331
+ [0, -1, -1],
332
+ ["00:01:00", "00:01:00", "00:02:00"],
333
+ ["00:01:00", "00:01:00", "00:00:01"],
334
+ ):
335
+ idx = TimedeltaIndex(vals)
336
+ assert idx[0] in idx
337
+
338
+ def test_contains(self):
339
+ # Checking for any NaT-like objects
340
+ # GH#13603
341
+ td = to_timedelta(range(5), unit="d") + offsets.Hour(1)
342
+ for v in [NaT, None, float("nan"), np.nan]:
343
+ assert v not in td
344
+
345
+ td = to_timedelta([NaT])
346
+ for v in [NaT, None, float("nan"), np.nan]:
347
+ assert v in td
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_join.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from pandas import (
4
+ Index,
5
+ Timedelta,
6
+ timedelta_range,
7
+ )
8
+ import pandas._testing as tm
9
+
10
+
11
+ class TestJoin:
12
+ def test_append_join_nondatetimeindex(self):
13
+ rng = timedelta_range("1 days", periods=10)
14
+ idx = Index(["a", "b", "c", "d"])
15
+
16
+ result = rng.append(idx)
17
+ assert isinstance(result[0], Timedelta)
18
+
19
+ # it works
20
+ rng.join(idx, how="outer")
21
+
22
+ def test_join_self(self, join_type):
23
+ index = timedelta_range("1 day", periods=10)
24
+ joined = index.join(index, how=join_type)
25
+ tm.assert_index_equal(index, joined)
26
+
27
+ def test_does_not_convert_mixed_integer(self):
28
+ df = tm.makeCustomDataframe(
29
+ 10,
30
+ 10,
31
+ data_gen_f=lambda *args, **kwargs: np.random.randn(),
32
+ r_idx_type="i",
33
+ c_idx_type="td",
34
+ )
35
+ str(df)
36
+
37
+ cols = df.columns.join(df.index, how="outer")
38
+ joined = cols.join(df.columns)
39
+ assert cols.dtype == np.dtype("O")
40
+ assert cols.dtype == joined.dtype
41
+ tm.assert_index_equal(cols, joined)
42
+
43
+ def test_join_preserves_freq(self):
44
+ # GH#32157
45
+ tdi = timedelta_range("1 day", periods=10)
46
+ result = tdi[:5].join(tdi[5:], how="outer")
47
+ assert result.freq == tdi.freq
48
+ tm.assert_index_equal(result, tdi)
49
+
50
+ result = tdi[:5].join(tdi[6:], how="outer")
51
+ assert result.freq is None
52
+ expected = tdi.delete(5)
53
+ tm.assert_index_equal(result, expected)
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_ops.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pandas import (
2
+ TimedeltaIndex,
3
+ timedelta_range,
4
+ )
5
+ import pandas._testing as tm
6
+
7
+
8
+ class TestTimedeltaIndexOps:
9
+ def test_infer_freq(self, freq_sample):
10
+ # GH#11018
11
+ idx = timedelta_range("1", freq=freq_sample, periods=10)
12
+ result = TimedeltaIndex(idx.asi8, freq="infer")
13
+ tm.assert_index_equal(idx, result)
14
+ assert result.freq == freq_sample
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_setops.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ import pandas as pd
5
+ from pandas import (
6
+ Index,
7
+ TimedeltaIndex,
8
+ timedelta_range,
9
+ )
10
+ import pandas._testing as tm
11
+
12
+ from pandas.tseries.offsets import Hour
13
+
14
+
15
+ class TestTimedeltaIndex:
16
+ def test_union(self):
17
+ i1 = timedelta_range("1day", periods=5)
18
+ i2 = timedelta_range("3day", periods=5)
19
+ result = i1.union(i2)
20
+ expected = timedelta_range("1day", periods=7)
21
+ tm.assert_index_equal(result, expected)
22
+
23
+ i1 = Index(np.arange(0, 20, 2, dtype=np.int64))
24
+ i2 = timedelta_range(start="1 day", periods=10, freq="D")
25
+ i1.union(i2) # Works
26
+ i2.union(i1) # Fails with "AttributeError: can't set attribute"
27
+
28
+ def test_union_sort_false(self):
29
+ tdi = timedelta_range("1day", periods=5)
30
+
31
+ left = tdi[3:]
32
+ right = tdi[:3]
33
+
34
+ # Check that we are testing the desired code path
35
+ assert left._can_fast_union(right)
36
+
37
+ result = left.union(right)
38
+ tm.assert_index_equal(result, tdi)
39
+
40
+ result = left.union(right, sort=False)
41
+ expected = TimedeltaIndex(["4 Days", "5 Days", "1 Days", "2 Day", "3 Days"])
42
+ tm.assert_index_equal(result, expected)
43
+
44
+ def test_union_coverage(self):
45
+ idx = TimedeltaIndex(["3d", "1d", "2d"])
46
+ ordered = TimedeltaIndex(idx.sort_values(), freq="infer")
47
+ result = ordered.union(idx)
48
+ tm.assert_index_equal(result, ordered)
49
+
50
+ result = ordered[:0].union(ordered)
51
+ tm.assert_index_equal(result, ordered)
52
+ assert result.freq == ordered.freq
53
+
54
+ def test_union_bug_1730(self):
55
+ rng_a = timedelta_range("1 day", periods=4, freq="3H")
56
+ rng_b = timedelta_range("1 day", periods=4, freq="4H")
57
+
58
+ result = rng_a.union(rng_b)
59
+ exp = TimedeltaIndex(sorted(set(rng_a) | set(rng_b)))
60
+ tm.assert_index_equal(result, exp)
61
+
62
+ def test_union_bug_1745(self):
63
+ left = TimedeltaIndex(["1 day 15:19:49.695000"])
64
+ right = TimedeltaIndex(
65
+ ["2 day 13:04:21.322000", "1 day 15:27:24.873000", "1 day 15:31:05.350000"]
66
+ )
67
+
68
+ result = left.union(right)
69
+ exp = TimedeltaIndex(sorted(set(left) | set(right)))
70
+ tm.assert_index_equal(result, exp)
71
+
72
+ def test_union_bug_4564(self):
73
+ left = timedelta_range("1 day", "30d")
74
+ right = left + pd.offsets.Minute(15)
75
+
76
+ result = left.union(right)
77
+ exp = TimedeltaIndex(sorted(set(left) | set(right)))
78
+ tm.assert_index_equal(result, exp)
79
+
80
+ def test_union_freq_infer(self):
81
+ # When taking the union of two TimedeltaIndexes, we infer
82
+ # a freq even if the arguments don't have freq. This matches
83
+ # DatetimeIndex behavior.
84
+ tdi = timedelta_range("1 Day", periods=5)
85
+ left = tdi[[0, 1, 3, 4]]
86
+ right = tdi[[2, 3, 1]]
87
+
88
+ assert left.freq is None
89
+ assert right.freq is None
90
+
91
+ result = left.union(right)
92
+ tm.assert_index_equal(result, tdi)
93
+ assert result.freq == "D"
94
+
95
+ def test_intersection_bug_1708(self):
96
+ index_1 = timedelta_range("1 day", periods=4, freq="h")
97
+ index_2 = index_1 + pd.offsets.Hour(5)
98
+
99
+ result = index_1.intersection(index_2)
100
+ assert len(result) == 0
101
+
102
+ index_1 = timedelta_range("1 day", periods=4, freq="h")
103
+ index_2 = index_1 + pd.offsets.Hour(1)
104
+
105
+ result = index_1.intersection(index_2)
106
+ expected = timedelta_range("1 day 01:00:00", periods=3, freq="h")
107
+ tm.assert_index_equal(result, expected)
108
+ assert result.freq == expected.freq
109
+
110
+ def test_intersection_equal(self, sort):
111
+ # GH 24471 Test intersection outcome given the sort keyword
112
+ # for equal indices intersection should return the original index
113
+ first = timedelta_range("1 day", periods=4, freq="h")
114
+ second = timedelta_range("1 day", periods=4, freq="h")
115
+ intersect = first.intersection(second, sort=sort)
116
+ if sort is None:
117
+ tm.assert_index_equal(intersect, second.sort_values())
118
+ assert tm.equalContents(intersect, second)
119
+
120
+ # Corner cases
121
+ inter = first.intersection(first, sort=sort)
122
+ assert inter is first
123
+
124
+ @pytest.mark.parametrize("period_1, period_2", [(0, 4), (4, 0)])
125
+ def test_intersection_zero_length(self, period_1, period_2, sort):
126
+ # GH 24471 test for non overlap the intersection should be zero length
127
+ index_1 = timedelta_range("1 day", periods=period_1, freq="h")
128
+ index_2 = timedelta_range("1 day", periods=period_2, freq="h")
129
+ expected = timedelta_range("1 day", periods=0, freq="h")
130
+ result = index_1.intersection(index_2, sort=sort)
131
+ tm.assert_index_equal(result, expected)
132
+
133
+ def test_zero_length_input_index(self, sort):
134
+ # GH 24966 test for 0-len intersections are copied
135
+ index_1 = timedelta_range("1 day", periods=0, freq="h")
136
+ index_2 = timedelta_range("1 day", periods=3, freq="h")
137
+ result = index_1.intersection(index_2, sort=sort)
138
+ assert index_1 is not result
139
+ assert index_2 is not result
140
+ tm.assert_copy(result, index_1)
141
+
142
+ @pytest.mark.parametrize(
143
+ "rng, expected",
144
+ # if target has the same name, it is preserved
145
+ [
146
+ (
147
+ timedelta_range("1 day", periods=5, freq="h", name="idx"),
148
+ timedelta_range("1 day", periods=4, freq="h", name="idx"),
149
+ ),
150
+ # if target name is different, it will be reset
151
+ (
152
+ timedelta_range("1 day", periods=5, freq="h", name="other"),
153
+ timedelta_range("1 day", periods=4, freq="h", name=None),
154
+ ),
155
+ # if no overlap exists return empty index
156
+ (
157
+ timedelta_range("1 day", periods=10, freq="h", name="idx")[5:],
158
+ TimedeltaIndex([], freq="h", name="idx"),
159
+ ),
160
+ ],
161
+ )
162
+ def test_intersection(self, rng, expected, sort):
163
+ # GH 4690 (with tz)
164
+ base = timedelta_range("1 day", periods=4, freq="h", name="idx")
165
+ result = base.intersection(rng, sort=sort)
166
+ if sort is None:
167
+ expected = expected.sort_values()
168
+ tm.assert_index_equal(result, expected)
169
+ assert result.name == expected.name
170
+ assert result.freq == expected.freq
171
+
172
+ @pytest.mark.parametrize(
173
+ "rng, expected",
174
+ # part intersection works
175
+ [
176
+ (
177
+ TimedeltaIndex(["5 hour", "2 hour", "4 hour", "9 hour"], name="idx"),
178
+ TimedeltaIndex(["2 hour", "4 hour"], name="idx"),
179
+ ),
180
+ # reordered part intersection
181
+ (
182
+ TimedeltaIndex(["2 hour", "5 hour", "5 hour", "1 hour"], name="other"),
183
+ TimedeltaIndex(["1 hour", "2 hour"], name=None),
184
+ ),
185
+ # reversed index
186
+ (
187
+ TimedeltaIndex(["1 hour", "2 hour", "4 hour", "3 hour"], name="idx")[
188
+ ::-1
189
+ ],
190
+ TimedeltaIndex(["1 hour", "2 hour", "4 hour", "3 hour"], name="idx"),
191
+ ),
192
+ ],
193
+ )
194
+ def test_intersection_non_monotonic(self, rng, expected, sort):
195
+ # 24471 non-monotonic
196
+ base = TimedeltaIndex(["1 hour", "2 hour", "4 hour", "3 hour"], name="idx")
197
+ result = base.intersection(rng, sort=sort)
198
+ if sort is None:
199
+ expected = expected.sort_values()
200
+ tm.assert_index_equal(result, expected)
201
+ assert result.name == expected.name
202
+
203
+ # if reversed order, frequency is still the same
204
+ if all(base == rng[::-1]) and sort is None:
205
+ assert isinstance(result.freq, Hour)
206
+ else:
207
+ assert result.freq is None
208
+
209
+
210
+ class TestTimedeltaIndexDifference:
211
+ def test_difference_freq(self, sort):
212
+ # GH14323: Difference of TimedeltaIndex should not preserve frequency
213
+
214
+ index = timedelta_range("0 days", "5 days", freq="D")
215
+
216
+ other = timedelta_range("1 days", "4 days", freq="D")
217
+ expected = TimedeltaIndex(["0 days", "5 days"], freq=None)
218
+ idx_diff = index.difference(other, sort)
219
+ tm.assert_index_equal(idx_diff, expected)
220
+ tm.assert_attr_equal("freq", idx_diff, expected)
221
+
222
+ other = timedelta_range("2 days", "5 days", freq="D")
223
+ idx_diff = index.difference(other, sort)
224
+ expected = TimedeltaIndex(["0 days", "1 days"], freq=None)
225
+ tm.assert_index_equal(idx_diff, expected)
226
+ tm.assert_attr_equal("freq", idx_diff, expected)
227
+
228
+ def test_difference_sort(self, sort):
229
+ index = TimedeltaIndex(
230
+ ["5 days", "3 days", "2 days", "4 days", "1 days", "0 days"]
231
+ )
232
+
233
+ other = timedelta_range("1 days", "4 days", freq="D")
234
+ idx_diff = index.difference(other, sort)
235
+
236
+ expected = TimedeltaIndex(["5 days", "0 days"], freq=None)
237
+
238
+ if sort is None:
239
+ expected = expected.sort_values()
240
+
241
+ tm.assert_index_equal(idx_diff, expected)
242
+ tm.assert_attr_equal("freq", idx_diff, expected)
243
+
244
+ other = timedelta_range("2 days", "5 days", freq="D")
245
+ idx_diff = index.difference(other, sort)
246
+ expected = TimedeltaIndex(["1 days", "0 days"], freq=None)
247
+
248
+ if sort is None:
249
+ expected = expected.sort_values()
250
+
251
+ tm.assert_index_equal(idx_diff, expected)
252
+ tm.assert_attr_equal("freq", idx_diff, expected)
videochat2/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_timedelta.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import timedelta
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ import pandas as pd
7
+ from pandas import (
8
+ Index,
9
+ NaT,
10
+ Series,
11
+ Timedelta,
12
+ TimedeltaIndex,
13
+ timedelta_range,
14
+ )
15
+ import pandas._testing as tm
16
+ from pandas.core.arrays import TimedeltaArray
17
+ from pandas.tests.indexes.datetimelike import DatetimeLike
18
+
19
+ randn = np.random.randn
20
+
21
+
22
+ class TestTimedeltaIndex(DatetimeLike):
23
+ _index_cls = TimedeltaIndex
24
+
25
+ @pytest.fixture
26
+ def simple_index(self) -> TimedeltaIndex:
27
+ index = pd.to_timedelta(range(5), unit="d")._with_freq("infer")
28
+ assert index.freq == "D"
29
+ ret = index + pd.offsets.Hour(1)
30
+ assert ret.freq == "D"
31
+ return ret
32
+
33
+ @pytest.fixture
34
+ def index(self):
35
+ return tm.makeTimedeltaIndex(10)
36
+
37
+ def test_numeric_compat(self):
38
+ # Dummy method to override super's version; this test is now done
39
+ # in test_arithmetic.py
40
+ pass
41
+
42
+ def test_shift(self):
43
+ pass # this is handled in test_arithmetic.py
44
+
45
+ def test_misc_coverage(self):
46
+ rng = timedelta_range("1 day", periods=5)
47
+ result = rng.groupby(rng.days)
48
+ assert isinstance(list(result.values())[0][0], Timedelta)
49
+
50
+ def test_map(self):
51
+ # test_map_dictlike generally tests
52
+
53
+ rng = timedelta_range("1 day", periods=10)
54
+
55
+ f = lambda x: x.days
56
+ result = rng.map(f)
57
+ exp = Index([f(x) for x in rng], dtype=np.int64)
58
+ tm.assert_index_equal(result, exp)
59
+
60
+ def test_pass_TimedeltaIndex_to_index(self):
61
+ rng = timedelta_range("1 days", "10 days")
62
+ idx = Index(rng, dtype=object)
63
+
64
+ expected = Index(rng.to_pytimedelta(), dtype=object)
65
+
66
+ tm.assert_numpy_array_equal(idx.values, expected.values)
67
+
68
+ def test_fields(self):
69
+ rng = timedelta_range("1 days, 10:11:12.100123456", periods=2, freq="s")
70
+ tm.assert_index_equal(rng.days, Index([1, 1], dtype=np.int64))
71
+ tm.assert_index_equal(
72
+ rng.seconds,
73
+ Index([10 * 3600 + 11 * 60 + 12, 10 * 3600 + 11 * 60 + 13], dtype=np.int32),
74
+ )
75
+ tm.assert_index_equal(
76
+ rng.microseconds,
77
+ Index([100 * 1000 + 123, 100 * 1000 + 123], dtype=np.int32),
78
+ )
79
+ tm.assert_index_equal(rng.nanoseconds, Index([456, 456], dtype=np.int32))
80
+
81
+ msg = "'TimedeltaIndex' object has no attribute '{}'"
82
+ with pytest.raises(AttributeError, match=msg.format("hours")):
83
+ rng.hours
84
+ with pytest.raises(AttributeError, match=msg.format("minutes")):
85
+ rng.minutes
86
+ with pytest.raises(AttributeError, match=msg.format("milliseconds")):
87
+ rng.milliseconds
88
+
89
+ # with nat
90
+ s = Series(rng)
91
+ s[1] = np.nan
92
+
93
+ tm.assert_series_equal(s.dt.days, Series([1, np.nan], index=[0, 1]))
94
+ tm.assert_series_equal(
95
+ s.dt.seconds, Series([10 * 3600 + 11 * 60 + 12, np.nan], index=[0, 1])
96
+ )
97
+
98
+ # preserve name (GH15589)
99
+ rng.name = "name"
100
+ assert rng.days.name == "name"
101
+
102
+ def test_freq_conversion_always_floating(self):
103
+ # pre-2.0 td64 astype converted to float64. now for supported units
104
+ # (s, ms, us, ns) this converts to the requested dtype.
105
+ # This matches TDA and Series
106
+ tdi = timedelta_range("1 Day", periods=30)
107
+
108
+ res = tdi.astype("m8[s]")
109
+ exp_values = np.asarray(tdi).astype("m8[s]")
110
+ exp_tda = TimedeltaArray._simple_new(
111
+ exp_values, dtype=exp_values.dtype, freq=tdi.freq
112
+ )
113
+ expected = Index(exp_tda)
114
+ assert expected.dtype == "m8[s]"
115
+ tm.assert_index_equal(res, expected)
116
+
117
+ # check this matches Series and TimedeltaArray
118
+ res = tdi._data.astype("m8[s]")
119
+ tm.assert_equal(res, expected._values)
120
+
121
+ res = tdi.to_series().astype("m8[s]")
122
+ tm.assert_equal(res._values, expected._values._with_freq(None))
123
+
124
+ def test_freq_conversion(self, index_or_series):
125
+ # doc example
126
+
127
+ scalar = Timedelta(days=31)
128
+ td = index_or_series(
129
+ [scalar, scalar, scalar + timedelta(minutes=5, seconds=3), NaT],
130
+ dtype="m8[ns]",
131
+ )
132
+
133
+ result = td / np.timedelta64(1, "D")
134
+ expected = index_or_series(
135
+ [31, 31, (31 * 86400 + 5 * 60 + 3) / 86400.0, np.nan]
136
+ )
137
+ tm.assert_equal(result, expected)
138
+
139
+ # We don't support "D" reso, so we use the pre-2.0 behavior
140
+ # casting to float64
141
+ msg = (
142
+ r"Cannot convert from timedelta64\[ns\] to timedelta64\[D\]. "
143
+ "Supported resolutions are 's', 'ms', 'us', 'ns'"
144
+ )
145
+ with pytest.raises(ValueError, match=msg):
146
+ td.astype("timedelta64[D]")
147
+
148
+ result = td / np.timedelta64(1, "s")
149
+ expected = index_or_series(
150
+ [31 * 86400, 31 * 86400, 31 * 86400 + 5 * 60 + 3, np.nan]
151
+ )
152
+ tm.assert_equal(result, expected)
153
+
154
+ exp_values = np.asarray(td).astype("m8[s]")
155
+ exp_tda = TimedeltaArray._simple_new(exp_values, dtype=exp_values.dtype)
156
+ expected = index_or_series(exp_tda)
157
+ assert expected.dtype == "m8[s]"
158
+ result = td.astype("timedelta64[s]")
159
+ tm.assert_equal(result, expected)
videochat2/lib/python3.10/site-packages/pandas/tests/tseries/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (176 Bytes). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/tseries/offsets/__init__.py ADDED
File without changes
videochat2/lib/python3.10/site-packages/pandas/tests/tseries/offsets/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (184 Bytes). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/tseries/offsets/__pycache__/common.cpython-310.pyc ADDED
Binary file (1.18 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/tseries/offsets/__pycache__/conftest.cpython-310.pyc ADDED
Binary file (1.35 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/tseries/offsets/__pycache__/test_business_day.cpython-310.pyc ADDED
Binary file (6.66 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/tseries/offsets/__pycache__/test_business_hour.cpython-310.pyc ADDED
Binary file (27.9 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/tseries/offsets/__pycache__/test_business_month.cpython-310.pyc ADDED
Binary file (4.49 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/tseries/offsets/__pycache__/test_business_quarter.cpython-310.pyc ADDED
Binary file (7.08 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/tseries/offsets/__pycache__/test_business_year.cpython-310.pyc ADDED
Binary file (4.62 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/tseries/offsets/__pycache__/test_common.cpython-310.pyc ADDED
Binary file (4.93 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/tseries/offsets/__pycache__/test_custom_business_day.cpython-310.pyc ADDED
Binary file (4.05 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/tseries/offsets/__pycache__/test_custom_business_hour.cpython-310.pyc ADDED
Binary file (9.41 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/tseries/offsets/__pycache__/test_custom_business_month.cpython-310.pyc ADDED
Binary file (12.1 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/tseries/offsets/__pycache__/test_dst.cpython-310.pyc ADDED
Binary file (5.6 kB). View file