nnilayy commited on
Commit
beecb1b
·
verified ·
1 Parent(s): 5aed742

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 +1 -0
  2. lib/python3.10/site-packages/babel/global.dat +3 -0
  3. lib/python3.10/site-packages/pandas/tests/indexes/base_class/__init__.py +0 -0
  4. lib/python3.10/site-packages/pandas/tests/indexes/base_class/test_constructors.py +80 -0
  5. lib/python3.10/site-packages/pandas/tests/indexes/base_class/test_formats.py +163 -0
  6. lib/python3.10/site-packages/pandas/tests/indexes/base_class/test_indexing.py +104 -0
  7. lib/python3.10/site-packages/pandas/tests/indexes/base_class/test_pickle.py +11 -0
  8. lib/python3.10/site-packages/pandas/tests/indexes/base_class/test_reshape.py +95 -0
  9. lib/python3.10/site-packages/pandas/tests/indexes/base_class/test_setops.py +266 -0
  10. lib/python3.10/site-packages/pandas/tests/indexes/base_class/test_where.py +13 -0
  11. lib/python3.10/site-packages/pandas/tests/indexes/categorical/__init__.py +0 -0
  12. lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_append.py +62 -0
  13. lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_astype.py +90 -0
  14. lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_category.py +394 -0
  15. lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_constructors.py +142 -0
  16. lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_equals.py +96 -0
  17. lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_fillna.py +54 -0
  18. lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_formats.py +120 -0
  19. lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_indexing.py +420 -0
  20. lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_map.py +144 -0
  21. lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_reindex.py +78 -0
  22. lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_setops.py +18 -0
  23. lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__init__.py +0 -0
  24. lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_drop_duplicates.py +89 -0
  25. lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_equals.py +181 -0
  26. lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_indexing.py +45 -0
  27. lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_is_monotonic.py +46 -0
  28. lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_nat.py +53 -0
  29. lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_sort_values.py +315 -0
  30. lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_value_counts.py +103 -0
  31. lib/python3.10/site-packages/pandas/tests/indexes/datetimes/methods/test_asof.py +30 -0
  32. lib/python3.10/site-packages/pandas/tests/indexes/datetimes/methods/test_astype.py +335 -0
  33. lib/python3.10/site-packages/pandas/tests/indexes/datetimes/methods/test_factorize.py +125 -0
  34. lib/python3.10/site-packages/pandas/tests/indexes/datetimes/methods/test_insert.py +265 -0
  35. lib/python3.10/site-packages/pandas/tests/indexes/datetimes/methods/test_map.py +47 -0
  36. lib/python3.10/site-packages/pandas/tests/indexes/datetimes/methods/test_normalize.py +95 -0
  37. lib/python3.10/site-packages/pandas/tests/indexes/datetimes/methods/test_resolution.py +31 -0
  38. lib/python3.10/site-packages/pandas/tests/indexes/datetimes/methods/test_snap.py +47 -0
  39. lib/python3.10/site-packages/pandas/tests/indexes/datetimes/methods/test_to_frame.py +28 -0
  40. lib/python3.10/site-packages/pandas/tests/indexes/datetimes/methods/test_to_period.py +225 -0
  41. lib/python3.10/site-packages/pandas/tests/indexes/datetimes/methods/test_tz_convert.py +283 -0
  42. lib/python3.10/site-packages/pandas/tests/indexes/interval/__init__.py +0 -0
  43. lib/python3.10/site-packages/pandas/tests/indexes/interval/test_astype.py +248 -0
  44. lib/python3.10/site-packages/pandas/tests/indexes/interval/test_constructors.py +535 -0
  45. lib/python3.10/site-packages/pandas/tests/indexes/interval/test_equals.py +36 -0
  46. lib/python3.10/site-packages/pandas/tests/indexes/interval/test_formats.py +119 -0
  47. lib/python3.10/site-packages/pandas/tests/indexes/interval/test_indexing.py +671 -0
  48. lib/python3.10/site-packages/pandas/tests/indexes/interval/test_interval.py +918 -0
  49. lib/python3.10/site-packages/pandas/tests/indexes/interval/test_interval_range.py +369 -0
  50. lib/python3.10/site-packages/pandas/tests/indexes/interval/test_interval_tree.py +208 -0
.gitattributes CHANGED
@@ -121,3 +121,4 @@ lib/python3.10/site-packages/av/subtitles/codeccontext.cpython-310-x86_64-linux-
121
  lib/python3.10/site-packages/babel/locale-data/ml.dat filter=lfs diff=lfs merge=lfs -text
122
  lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust.abi3.so filter=lfs diff=lfs merge=lfs -text
123
  lib/python3.10/site-packages/babel/locale-data/zu.dat filter=lfs diff=lfs merge=lfs -text
 
 
121
  lib/python3.10/site-packages/babel/locale-data/ml.dat filter=lfs diff=lfs merge=lfs -text
122
  lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust.abi3.so filter=lfs diff=lfs merge=lfs -text
123
  lib/python3.10/site-packages/babel/locale-data/zu.dat filter=lfs diff=lfs merge=lfs -text
124
+ lib/python3.10/site-packages/babel/global.dat filter=lfs diff=lfs merge=lfs -text
lib/python3.10/site-packages/babel/global.dat ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c11607a7f9d2c1993a4b54b4927de0db4cc70189b6bebed3866bd5eeea83aa03
3
+ size 459316
lib/python3.10/site-packages/pandas/tests/indexes/base_class/__init__.py ADDED
File without changes
lib/python3.10/site-packages/pandas/tests/indexes/base_class/test_constructors.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ import pandas as pd
5
+ from pandas import (
6
+ Index,
7
+ MultiIndex,
8
+ Series,
9
+ )
10
+ import pandas._testing as tm
11
+
12
+
13
+ class TestIndexConstructor:
14
+ # Tests for the Index constructor, specifically for cases that do
15
+ # not return a subclass
16
+
17
+ @pytest.mark.parametrize("value", [1, np.int64(1)])
18
+ def test_constructor_corner(self, value):
19
+ # corner case
20
+ msg = (
21
+ r"Index\(\.\.\.\) must be called with a collection of some "
22
+ f"kind, {value} was passed"
23
+ )
24
+ with pytest.raises(TypeError, match=msg):
25
+ Index(value)
26
+
27
+ @pytest.mark.parametrize("index_vals", [[("A", 1), "B"], ["B", ("A", 1)]])
28
+ def test_construction_list_mixed_tuples(self, index_vals):
29
+ # see gh-10697: if we are constructing from a mixed list of tuples,
30
+ # make sure that we are independent of the sorting order.
31
+ index = Index(index_vals)
32
+ assert isinstance(index, Index)
33
+ assert not isinstance(index, MultiIndex)
34
+
35
+ def test_constructor_cast(self):
36
+ msg = "could not convert string to float"
37
+ with pytest.raises(ValueError, match=msg):
38
+ Index(["a", "b", "c"], dtype=float)
39
+
40
+ @pytest.mark.parametrize("tuple_list", [[()], [(), ()]])
41
+ def test_construct_empty_tuples(self, tuple_list):
42
+ # GH #45608
43
+ result = Index(tuple_list)
44
+ expected = MultiIndex.from_tuples(tuple_list)
45
+
46
+ tm.assert_index_equal(result, expected)
47
+
48
+ def test_index_string_inference(self):
49
+ # GH#54430
50
+ pytest.importorskip("pyarrow")
51
+ dtype = "string[pyarrow_numpy]"
52
+ expected = Index(["a", "b"], dtype=dtype)
53
+ with pd.option_context("future.infer_string", True):
54
+ ser = Index(["a", "b"])
55
+ tm.assert_index_equal(ser, expected)
56
+
57
+ expected = Index(["a", 1], dtype="object")
58
+ with pd.option_context("future.infer_string", True):
59
+ ser = Index(["a", 1])
60
+ tm.assert_index_equal(ser, expected)
61
+
62
+ def test_inference_on_pandas_objects(self):
63
+ # GH#56012
64
+ idx = Index([pd.Timestamp("2019-12-31")], dtype=object)
65
+ with tm.assert_produces_warning(FutureWarning, match="Dtype inference"):
66
+ result = Index(idx)
67
+ assert result.dtype != np.object_
68
+
69
+ ser = Series([pd.Timestamp("2019-12-31")], dtype=object)
70
+
71
+ with tm.assert_produces_warning(FutureWarning, match="Dtype inference"):
72
+ result = Index(ser)
73
+ assert result.dtype != np.object_
74
+
75
+ def test_constructor_not_read_only(self):
76
+ # GH#57130
77
+ ser = Series([1, 2], dtype=object)
78
+ with pd.option_context("mode.copy_on_write", True):
79
+ idx = Index(ser)
80
+ assert idx._values.flags.writeable
lib/python3.10/site-packages/pandas/tests/indexes/base_class/test_formats.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas._config import using_pyarrow_string_dtype
5
+ import pandas._config.config as cf
6
+
7
+ from pandas import Index
8
+ import pandas._testing as tm
9
+
10
+
11
+ class TestIndexRendering:
12
+ def test_repr_is_valid_construction_code(self):
13
+ # for the case of Index, where the repr is traditional rather than
14
+ # stylized
15
+ idx = Index(["a", "b"])
16
+ res = eval(repr(idx))
17
+ tm.assert_index_equal(res, idx)
18
+
19
+ @pytest.mark.xfail(using_pyarrow_string_dtype(), reason="repr different")
20
+ @pytest.mark.parametrize(
21
+ "index,expected",
22
+ [
23
+ # ASCII
24
+ # short
25
+ (
26
+ Index(["a", "bb", "ccc"]),
27
+ """Index(['a', 'bb', 'ccc'], dtype='object')""",
28
+ ),
29
+ # multiple lines
30
+ (
31
+ Index(["a", "bb", "ccc"] * 10),
32
+ "Index(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', "
33
+ "'bb', 'ccc', 'a', 'bb', 'ccc',\n"
34
+ " 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', "
35
+ "'bb', 'ccc', 'a', 'bb', 'ccc',\n"
36
+ " 'a', 'bb', 'ccc', 'a', 'bb', 'ccc'],\n"
37
+ " dtype='object')",
38
+ ),
39
+ # truncated
40
+ (
41
+ Index(["a", "bb", "ccc"] * 100),
42
+ "Index(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a',\n"
43
+ " ...\n"
44
+ " 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc'],\n"
45
+ " dtype='object', length=300)",
46
+ ),
47
+ # Non-ASCII
48
+ # short
49
+ (
50
+ Index(["あ", "いい", "ううう"]),
51
+ """Index(['あ', 'いい', 'ううう'], dtype='object')""",
52
+ ),
53
+ # multiple lines
54
+ (
55
+ Index(["あ", "いい", "ううう"] * 10),
56
+ (
57
+ "Index(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', "
58
+ "'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう',\n"
59
+ " 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', "
60
+ "'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう',\n"
61
+ " 'あ', 'いい', 'ううう', 'あ', 'いい', "
62
+ "'ううう'],\n"
63
+ " dtype='object')"
64
+ ),
65
+ ),
66
+ # truncated
67
+ (
68
+ Index(["あ", "いい", "ううう"] * 100),
69
+ (
70
+ "Index(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', "
71
+ "'あ', 'いい', 'ううう', 'あ',\n"
72
+ " ...\n"
73
+ " 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', "
74
+ "'ううう', 'あ', 'いい', 'ううう'],\n"
75
+ " dtype='object', length=300)"
76
+ ),
77
+ ),
78
+ ],
79
+ )
80
+ def test_string_index_repr(self, index, expected):
81
+ result = repr(index)
82
+ assert result == expected
83
+
84
+ @pytest.mark.xfail(using_pyarrow_string_dtype(), reason="repr different")
85
+ @pytest.mark.parametrize(
86
+ "index,expected",
87
+ [
88
+ # short
89
+ (
90
+ Index(["あ", "いい", "ううう"]),
91
+ ("Index(['あ', 'いい', 'ううう'], dtype='object')"),
92
+ ),
93
+ # multiple lines
94
+ (
95
+ Index(["あ", "いい", "ううう"] * 10),
96
+ (
97
+ "Index(['あ', 'いい', 'ううう', 'あ', 'いい', "
98
+ "'ううう', 'あ', 'いい', 'ううう',\n"
99
+ " 'あ', 'いい', 'ううう', 'あ', 'いい', "
100
+ "'ううう', 'あ', 'いい', 'ううう',\n"
101
+ " 'あ', 'いい', 'ううう', 'あ', 'いい', "
102
+ "'ううう', 'あ', 'いい', 'ううう',\n"
103
+ " 'あ', 'いい', 'ううう'],\n"
104
+ " dtype='object')"
105
+ ""
106
+ ),
107
+ ),
108
+ # truncated
109
+ (
110
+ Index(["あ", "いい", "ううう"] * 100),
111
+ (
112
+ "Index(['あ', 'いい', 'ううう', 'あ', 'いい', "
113
+ "'ううう', 'あ', 'いい', 'ううう',\n"
114
+ " 'あ',\n"
115
+ " ...\n"
116
+ " 'ううう', 'あ', 'いい', 'ううう', 'あ', "
117
+ "'いい', 'ううう', 'あ', 'いい',\n"
118
+ " 'ううう'],\n"
119
+ " dtype='object', length=300)"
120
+ ),
121
+ ),
122
+ ],
123
+ )
124
+ def test_string_index_repr_with_unicode_option(self, index, expected):
125
+ # Enable Unicode option -----------------------------------------
126
+ with cf.option_context("display.unicode.east_asian_width", True):
127
+ result = repr(index)
128
+ assert result == expected
129
+
130
+ def test_repr_summary(self):
131
+ with cf.option_context("display.max_seq_items", 10):
132
+ result = repr(Index(np.arange(1000)))
133
+ assert len(result) < 200
134
+ assert "..." in result
135
+
136
+ def test_summary_bug(self):
137
+ # GH#3869
138
+ ind = Index(["{other}%s", "~:{range}:0"], name="A")
139
+ result = ind._summary()
140
+ # shouldn't be formatted accidentally.
141
+ assert "~:{range}:0" in result
142
+ assert "{other}%s" in result
143
+
144
+ def test_index_repr_bool_nan(self):
145
+ # GH32146
146
+ arr = Index([True, False, np.nan], dtype=object)
147
+ msg = "Index.format is deprecated"
148
+ with tm.assert_produces_warning(FutureWarning, match=msg):
149
+ exp1 = arr.format()
150
+ out1 = ["True", "False", "NaN"]
151
+ assert out1 == exp1
152
+
153
+ exp2 = repr(arr)
154
+ out2 = "Index([True, False, nan], dtype='object')"
155
+ assert out2 == exp2
156
+
157
+ def test_format_different_scalar_lengths(self):
158
+ # GH#35439
159
+ idx = Index(["aaaaaaaaa", "b"])
160
+ expected = ["aaaaaaaaa", "b"]
161
+ msg = r"Index\.format is deprecated"
162
+ with tm.assert_produces_warning(FutureWarning, match=msg):
163
+ assert idx.format() == expected
lib/python3.10/site-packages/pandas/tests/indexes/base_class/test_indexing.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas._libs import index as libindex
5
+
6
+ import pandas as pd
7
+ from pandas import (
8
+ Index,
9
+ NaT,
10
+ )
11
+ import pandas._testing as tm
12
+
13
+
14
+ class TestGetSliceBounds:
15
+ @pytest.mark.parametrize("side, expected", [("left", 4), ("right", 5)])
16
+ def test_get_slice_bounds_within(self, side, expected):
17
+ index = Index(list("abcdef"))
18
+ result = index.get_slice_bound("e", side=side)
19
+ assert result == expected
20
+
21
+ @pytest.mark.parametrize("side", ["left", "right"])
22
+ @pytest.mark.parametrize(
23
+ "data, bound, expected", [(list("abcdef"), "x", 6), (list("bcdefg"), "a", 0)]
24
+ )
25
+ def test_get_slice_bounds_outside(self, side, expected, data, bound):
26
+ index = Index(data)
27
+ result = index.get_slice_bound(bound, side=side)
28
+ assert result == expected
29
+
30
+ def test_get_slice_bounds_invalid_side(self):
31
+ with pytest.raises(ValueError, match="Invalid value for side kwarg"):
32
+ Index([]).get_slice_bound("a", side="middle")
33
+
34
+
35
+ class TestGetIndexerNonUnique:
36
+ def test_get_indexer_non_unique_dtype_mismatch(self):
37
+ # GH#25459
38
+ indexes, missing = Index(["A", "B"]).get_indexer_non_unique(Index([0]))
39
+ tm.assert_numpy_array_equal(np.array([-1], dtype=np.intp), indexes)
40
+ tm.assert_numpy_array_equal(np.array([0], dtype=np.intp), missing)
41
+
42
+ @pytest.mark.parametrize(
43
+ "idx_values,idx_non_unique",
44
+ [
45
+ ([np.nan, 100, 200, 100], [np.nan, 100]),
46
+ ([np.nan, 100.0, 200.0, 100.0], [np.nan, 100.0]),
47
+ ],
48
+ )
49
+ def test_get_indexer_non_unique_int_index(self, idx_values, idx_non_unique):
50
+ indexes, missing = Index(idx_values).get_indexer_non_unique(Index([np.nan]))
51
+ tm.assert_numpy_array_equal(np.array([0], dtype=np.intp), indexes)
52
+ tm.assert_numpy_array_equal(np.array([], dtype=np.intp), missing)
53
+
54
+ indexes, missing = Index(idx_values).get_indexer_non_unique(
55
+ Index(idx_non_unique)
56
+ )
57
+ tm.assert_numpy_array_equal(np.array([0, 1, 3], dtype=np.intp), indexes)
58
+ tm.assert_numpy_array_equal(np.array([], dtype=np.intp), missing)
59
+
60
+
61
+ class TestGetLoc:
62
+ @pytest.mark.slow # to_flat_index takes a while
63
+ def test_get_loc_tuple_monotonic_above_size_cutoff(self, monkeypatch):
64
+ # Go through the libindex path for which using
65
+ # _bin_search vs ndarray.searchsorted makes a difference
66
+
67
+ with monkeypatch.context():
68
+ monkeypatch.setattr(libindex, "_SIZE_CUTOFF", 100)
69
+ lev = list("ABCD")
70
+ dti = pd.date_range("2016-01-01", periods=10)
71
+
72
+ mi = pd.MultiIndex.from_product([lev, range(5), dti])
73
+ oidx = mi.to_flat_index()
74
+
75
+ loc = len(oidx) // 2
76
+ tup = oidx[loc]
77
+
78
+ res = oidx.get_loc(tup)
79
+ assert res == loc
80
+
81
+ def test_get_loc_nan_object_dtype_nonmonotonic_nonunique(self):
82
+ # case that goes through _maybe_get_bool_indexer
83
+ idx = Index(["foo", np.nan, None, "foo", 1.0, None], dtype=object)
84
+
85
+ # we dont raise KeyError on nan
86
+ res = idx.get_loc(np.nan)
87
+ assert res == 1
88
+
89
+ # we only match on None, not on np.nan
90
+ res = idx.get_loc(None)
91
+ expected = np.array([False, False, True, False, False, True])
92
+ tm.assert_numpy_array_equal(res, expected)
93
+
94
+ # we don't match at all on mismatched NA
95
+ with pytest.raises(KeyError, match="NaT"):
96
+ idx.get_loc(NaT)
97
+
98
+
99
+ def test_getitem_boolean_ea_indexer():
100
+ # GH#45806
101
+ ser = pd.Series([True, False, pd.NA], dtype="boolean")
102
+ result = ser.index[ser]
103
+ expected = Index([0])
104
+ tm.assert_index_equal(result, expected)
lib/python3.10/site-packages/pandas/tests/indexes/base_class/test_pickle.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pandas import Index
2
+ import pandas._testing as tm
3
+
4
+
5
+ def test_pickle_preserves_object_dtype():
6
+ # GH#43188, GH#43155 don't infer numeric dtype
7
+ index = Index([1, 2, 3], dtype=object)
8
+
9
+ result = tm.round_trip_pickle(index)
10
+ assert result.dtype == object
11
+ tm.assert_index_equal(index, result)
lib/python3.10/site-packages/pandas/tests/indexes/base_class/test_reshape.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests for ndarray-like method on the base Index class
3
+ """
4
+ import numpy as np
5
+ import pytest
6
+
7
+ from pandas import Index
8
+ import pandas._testing as tm
9
+
10
+
11
+ class TestReshape:
12
+ def test_repeat(self):
13
+ repeats = 2
14
+ index = Index([1, 2, 3])
15
+ expected = Index([1, 1, 2, 2, 3, 3])
16
+
17
+ result = index.repeat(repeats)
18
+ tm.assert_index_equal(result, expected)
19
+
20
+ def test_insert(self):
21
+ # GH 7256
22
+ # validate neg/pos inserts
23
+ result = Index(["b", "c", "d"])
24
+
25
+ # test 0th element
26
+ tm.assert_index_equal(Index(["a", "b", "c", "d"]), result.insert(0, "a"))
27
+
28
+ # test Nth element that follows Python list behavior
29
+ tm.assert_index_equal(Index(["b", "c", "e", "d"]), result.insert(-1, "e"))
30
+
31
+ # test loc +/- neq (0, -1)
32
+ tm.assert_index_equal(result.insert(1, "z"), result.insert(-2, "z"))
33
+
34
+ # test empty
35
+ null_index = Index([])
36
+ tm.assert_index_equal(Index(["a"], dtype=object), null_index.insert(0, "a"))
37
+
38
+ def test_insert_missing(self, nulls_fixture, using_infer_string):
39
+ # GH#22295
40
+ # test there is no mangling of NA values
41
+ expected = Index(["a", nulls_fixture, "b", "c"], dtype=object)
42
+ result = Index(list("abc"), dtype=object).insert(
43
+ 1, Index([nulls_fixture], dtype=object)
44
+ )
45
+ tm.assert_index_equal(result, expected)
46
+
47
+ @pytest.mark.parametrize(
48
+ "val", [(1, 2), np.datetime64("2019-12-31"), np.timedelta64(1, "D")]
49
+ )
50
+ @pytest.mark.parametrize("loc", [-1, 2])
51
+ def test_insert_datetime_into_object(self, loc, val):
52
+ # GH#44509
53
+ idx = Index(["1", "2", "3"])
54
+ result = idx.insert(loc, val)
55
+ expected = Index(["1", "2", val, "3"])
56
+ tm.assert_index_equal(result, expected)
57
+ assert type(expected[2]) is type(val)
58
+
59
+ def test_insert_none_into_string_numpy(self):
60
+ # GH#55365
61
+ pytest.importorskip("pyarrow")
62
+ index = Index(["a", "b", "c"], dtype="string[pyarrow_numpy]")
63
+ result = index.insert(-1, None)
64
+ expected = Index(["a", "b", None, "c"], dtype="string[pyarrow_numpy]")
65
+ tm.assert_index_equal(result, expected)
66
+
67
+ @pytest.mark.parametrize(
68
+ "pos,expected",
69
+ [
70
+ (0, Index(["b", "c", "d"], name="index")),
71
+ (-1, Index(["a", "b", "c"], name="index")),
72
+ ],
73
+ )
74
+ def test_delete(self, pos, expected):
75
+ index = Index(["a", "b", "c", "d"], name="index")
76
+ result = index.delete(pos)
77
+ tm.assert_index_equal(result, expected)
78
+ assert result.name == expected.name
79
+
80
+ def test_delete_raises(self):
81
+ index = Index(["a", "b", "c", "d"], name="index")
82
+ msg = "index 5 is out of bounds for axis 0 with size 4"
83
+ with pytest.raises(IndexError, match=msg):
84
+ index.delete(5)
85
+
86
+ def test_append_multiple(self):
87
+ index = Index(["a", "b", "c", "d", "e", "f"])
88
+
89
+ foos = [index[:2], index[2:4], index[4:]]
90
+ result = foos[0].append(foos[1:])
91
+ tm.assert_index_equal(result, index)
92
+
93
+ # empty
94
+ result = index.append([])
95
+ tm.assert_index_equal(result, index)
lib/python3.10/site-packages/pandas/tests/indexes/base_class/test_setops.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ import pandas as pd
7
+ from pandas import (
8
+ Index,
9
+ Series,
10
+ )
11
+ import pandas._testing as tm
12
+ from pandas.core.algorithms import safe_sort
13
+
14
+
15
+ def equal_contents(arr1, arr2) -> bool:
16
+ """
17
+ Checks if the set of unique elements of arr1 and arr2 are equivalent.
18
+ """
19
+ return frozenset(arr1) == frozenset(arr2)
20
+
21
+
22
+ class TestIndexSetOps:
23
+ @pytest.mark.parametrize(
24
+ "method", ["union", "intersection", "difference", "symmetric_difference"]
25
+ )
26
+ def test_setops_sort_validation(self, method):
27
+ idx1 = Index(["a", "b"])
28
+ idx2 = Index(["b", "c"])
29
+
30
+ with pytest.raises(ValueError, match="The 'sort' keyword only takes"):
31
+ getattr(idx1, method)(idx2, sort=2)
32
+
33
+ # sort=True is supported as of GH#??
34
+ getattr(idx1, method)(idx2, sort=True)
35
+
36
+ def test_setops_preserve_object_dtype(self):
37
+ idx = Index([1, 2, 3], dtype=object)
38
+ result = idx.intersection(idx[1:])
39
+ expected = idx[1:]
40
+ tm.assert_index_equal(result, expected)
41
+
42
+ # if other is not monotonic increasing, intersection goes through
43
+ # a different route
44
+ result = idx.intersection(idx[1:][::-1])
45
+ tm.assert_index_equal(result, expected)
46
+
47
+ result = idx._union(idx[1:], sort=None)
48
+ expected = idx
49
+ tm.assert_numpy_array_equal(result, expected.values)
50
+
51
+ result = idx.union(idx[1:], sort=None)
52
+ tm.assert_index_equal(result, expected)
53
+
54
+ # if other is not monotonic increasing, _union goes through
55
+ # a different route
56
+ result = idx._union(idx[1:][::-1], sort=None)
57
+ tm.assert_numpy_array_equal(result, expected.values)
58
+
59
+ result = idx.union(idx[1:][::-1], sort=None)
60
+ tm.assert_index_equal(result, expected)
61
+
62
+ def test_union_base(self):
63
+ index = Index([0, "a", 1, "b", 2, "c"])
64
+ first = index[3:]
65
+ second = index[:5]
66
+
67
+ result = first.union(second)
68
+
69
+ expected = Index([0, 1, 2, "a", "b", "c"])
70
+ tm.assert_index_equal(result, expected)
71
+
72
+ @pytest.mark.parametrize("klass", [np.array, Series, list])
73
+ def test_union_different_type_base(self, klass):
74
+ # GH 10149
75
+ index = Index([0, "a", 1, "b", 2, "c"])
76
+ first = index[3:]
77
+ second = index[:5]
78
+
79
+ result = first.union(klass(second.values))
80
+
81
+ assert equal_contents(result, index)
82
+
83
+ def test_union_sort_other_incomparable(self):
84
+ # https://github.com/pandas-dev/pandas/issues/24959
85
+ idx = Index([1, pd.Timestamp("2000")])
86
+ # default (sort=None)
87
+ with tm.assert_produces_warning(RuntimeWarning):
88
+ result = idx.union(idx[:1])
89
+
90
+ tm.assert_index_equal(result, idx)
91
+
92
+ # sort=None
93
+ with tm.assert_produces_warning(RuntimeWarning):
94
+ result = idx.union(idx[:1], sort=None)
95
+ tm.assert_index_equal(result, idx)
96
+
97
+ # sort=False
98
+ result = idx.union(idx[:1], sort=False)
99
+ tm.assert_index_equal(result, idx)
100
+
101
+ def test_union_sort_other_incomparable_true(self):
102
+ idx = Index([1, pd.Timestamp("2000")])
103
+ with pytest.raises(TypeError, match=".*"):
104
+ idx.union(idx[:1], sort=True)
105
+
106
+ def test_intersection_equal_sort_true(self):
107
+ idx = Index(["c", "a", "b"])
108
+ sorted_ = Index(["a", "b", "c"])
109
+ tm.assert_index_equal(idx.intersection(idx, sort=True), sorted_)
110
+
111
+ def test_intersection_base(self, sort):
112
+ # (same results for py2 and py3 but sortedness not tested elsewhere)
113
+ index = Index([0, "a", 1, "b", 2, "c"])
114
+ first = index[:5]
115
+ second = index[:3]
116
+
117
+ expected = Index([0, 1, "a"]) if sort is None else Index([0, "a", 1])
118
+ result = first.intersection(second, sort=sort)
119
+ tm.assert_index_equal(result, expected)
120
+
121
+ @pytest.mark.parametrize("klass", [np.array, Series, list])
122
+ def test_intersection_different_type_base(self, klass, sort):
123
+ # GH 10149
124
+ index = Index([0, "a", 1, "b", 2, "c"])
125
+ first = index[:5]
126
+ second = index[:3]
127
+
128
+ result = first.intersection(klass(second.values), sort=sort)
129
+ assert equal_contents(result, second)
130
+
131
+ def test_intersection_nosort(self):
132
+ result = Index(["c", "b", "a"]).intersection(["b", "a"])
133
+ expected = Index(["b", "a"])
134
+ tm.assert_index_equal(result, expected)
135
+
136
+ def test_intersection_equal_sort(self):
137
+ idx = Index(["c", "a", "b"])
138
+ tm.assert_index_equal(idx.intersection(idx, sort=False), idx)
139
+ tm.assert_index_equal(idx.intersection(idx, sort=None), idx)
140
+
141
+ def test_intersection_str_dates(self, sort):
142
+ dt_dates = [datetime(2012, 2, 9), datetime(2012, 2, 22)]
143
+
144
+ i1 = Index(dt_dates, dtype=object)
145
+ i2 = Index(["aa"], dtype=object)
146
+ result = i2.intersection(i1, sort=sort)
147
+
148
+ assert len(result) == 0
149
+
150
+ @pytest.mark.parametrize(
151
+ "index2,expected_arr",
152
+ [(Index(["B", "D"]), ["B"]), (Index(["B", "D", "A"]), ["A", "B"])],
153
+ )
154
+ def test_intersection_non_monotonic_non_unique(self, index2, expected_arr, sort):
155
+ # non-monotonic non-unique
156
+ index1 = Index(["A", "B", "A", "C"])
157
+ expected = Index(expected_arr)
158
+ result = index1.intersection(index2, sort=sort)
159
+ if sort is None:
160
+ expected = expected.sort_values()
161
+ tm.assert_index_equal(result, expected)
162
+
163
+ def test_difference_base(self, sort):
164
+ # (same results for py2 and py3 but sortedness not tested elsewhere)
165
+ index = Index([0, "a", 1, "b", 2, "c"])
166
+ first = index[:4]
167
+ second = index[3:]
168
+
169
+ result = first.difference(second, sort)
170
+ expected = Index([0, "a", 1])
171
+ if sort is None:
172
+ expected = Index(safe_sort(expected))
173
+ tm.assert_index_equal(result, expected)
174
+
175
+ def test_symmetric_difference(self):
176
+ # (same results for py2 and py3 but sortedness not tested elsewhere)
177
+ index = Index([0, "a", 1, "b", 2, "c"])
178
+ first = index[:4]
179
+ second = index[3:]
180
+
181
+ result = first.symmetric_difference(second)
182
+ expected = Index([0, 1, 2, "a", "c"])
183
+ tm.assert_index_equal(result, expected)
184
+
185
+ @pytest.mark.parametrize(
186
+ "method,expected,sort",
187
+ [
188
+ (
189
+ "intersection",
190
+ np.array(
191
+ [(1, "A"), (2, "A"), (1, "B"), (2, "B")],
192
+ dtype=[("num", int), ("let", "S1")],
193
+ ),
194
+ False,
195
+ ),
196
+ (
197
+ "intersection",
198
+ np.array(
199
+ [(1, "A"), (1, "B"), (2, "A"), (2, "B")],
200
+ dtype=[("num", int), ("let", "S1")],
201
+ ),
202
+ None,
203
+ ),
204
+ (
205
+ "union",
206
+ np.array(
207
+ [(1, "A"), (1, "B"), (1, "C"), (2, "A"), (2, "B"), (2, "C")],
208
+ dtype=[("num", int), ("let", "S1")],
209
+ ),
210
+ None,
211
+ ),
212
+ ],
213
+ )
214
+ def test_tuple_union_bug(self, method, expected, sort):
215
+ index1 = Index(
216
+ np.array(
217
+ [(1, "A"), (2, "A"), (1, "B"), (2, "B")],
218
+ dtype=[("num", int), ("let", "S1")],
219
+ )
220
+ )
221
+ index2 = Index(
222
+ np.array(
223
+ [(1, "A"), (2, "A"), (1, "B"), (2, "B"), (1, "C"), (2, "C")],
224
+ dtype=[("num", int), ("let", "S1")],
225
+ )
226
+ )
227
+
228
+ result = getattr(index1, method)(index2, sort=sort)
229
+ assert result.ndim == 1
230
+
231
+ expected = Index(expected)
232
+ tm.assert_index_equal(result, expected)
233
+
234
+ @pytest.mark.parametrize("first_list", [["b", "a"], []])
235
+ @pytest.mark.parametrize("second_list", [["a", "b"], []])
236
+ @pytest.mark.parametrize(
237
+ "first_name, second_name, expected_name",
238
+ [("A", "B", None), (None, "B", None), ("A", None, None)],
239
+ )
240
+ def test_union_name_preservation(
241
+ self, first_list, second_list, first_name, second_name, expected_name, sort
242
+ ):
243
+ first = Index(first_list, name=first_name)
244
+ second = Index(second_list, name=second_name)
245
+ union = first.union(second, sort=sort)
246
+
247
+ vals = set(first_list).union(second_list)
248
+
249
+ if sort is None and len(first_list) > 0 and len(second_list) > 0:
250
+ expected = Index(sorted(vals), name=expected_name)
251
+ tm.assert_index_equal(union, expected)
252
+ else:
253
+ expected = Index(vals, name=expected_name)
254
+ tm.assert_index_equal(union.sort_values(), expected.sort_values())
255
+
256
+ @pytest.mark.parametrize(
257
+ "diff_type, expected",
258
+ [["difference", [1, "B"]], ["symmetric_difference", [1, 2, "B", "C"]]],
259
+ )
260
+ def test_difference_object_type(self, diff_type, expected):
261
+ # GH 13432
262
+ idx1 = Index([0, 1, "A", "B"])
263
+ idx2 = Index([0, 2, "A", "C"])
264
+ result = getattr(idx1, diff_type)(idx2)
265
+ expected = Index(expected)
266
+ tm.assert_index_equal(result, expected)
lib/python3.10/site-packages/pandas/tests/indexes/base_class/test_where.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from pandas import Index
4
+ import pandas._testing as tm
5
+
6
+
7
+ class TestWhere:
8
+ def test_where_intlike_str_doesnt_cast_ints(self):
9
+ idx = Index(range(3))
10
+ mask = np.array([True, False, True])
11
+ res = idx.where(mask, "2")
12
+ expected = Index([0, "2", 2])
13
+ tm.assert_index_equal(res, expected)
lib/python3.10/site-packages/pandas/tests/indexes/categorical/__init__.py ADDED
File without changes
lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_append.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from pandas import (
4
+ CategoricalIndex,
5
+ Index,
6
+ )
7
+ import pandas._testing as tm
8
+
9
+
10
+ class TestAppend:
11
+ @pytest.fixture
12
+ def ci(self):
13
+ categories = list("cab")
14
+ return CategoricalIndex(list("aabbca"), categories=categories, ordered=False)
15
+
16
+ def test_append(self, ci):
17
+ # append cats with the same categories
18
+ result = ci[:3].append(ci[3:])
19
+ tm.assert_index_equal(result, ci, exact=True)
20
+
21
+ foos = [ci[:1], ci[1:3], ci[3:]]
22
+ result = foos[0].append(foos[1:])
23
+ tm.assert_index_equal(result, ci, exact=True)
24
+
25
+ def test_append_empty(self, ci):
26
+ # empty
27
+ result = ci.append([])
28
+ tm.assert_index_equal(result, ci, exact=True)
29
+
30
+ def test_append_mismatched_categories(self, ci):
31
+ # appending with different categories or reordered is not ok
32
+ msg = "all inputs must be Index"
33
+ with pytest.raises(TypeError, match=msg):
34
+ ci.append(ci.values.set_categories(list("abcd")))
35
+ with pytest.raises(TypeError, match=msg):
36
+ ci.append(ci.values.reorder_categories(list("abc")))
37
+
38
+ def test_append_category_objects(self, ci):
39
+ # with objects
40
+ result = ci.append(Index(["c", "a"]))
41
+ expected = CategoricalIndex(list("aabbcaca"), categories=ci.categories)
42
+ tm.assert_index_equal(result, expected, exact=True)
43
+
44
+ def test_append_non_categories(self, ci):
45
+ # invalid objects -> cast to object via concat_compat
46
+ result = ci.append(Index(["a", "d"]))
47
+ expected = Index(["a", "a", "b", "b", "c", "a", "a", "d"])
48
+ tm.assert_index_equal(result, expected, exact=True)
49
+
50
+ def test_append_object(self, ci):
51
+ # GH#14298 - if base object is not categorical -> coerce to object
52
+ result = Index(["c", "a"]).append(ci)
53
+ expected = Index(list("caaabbca"))
54
+ tm.assert_index_equal(result, expected, exact=True)
55
+
56
+ def test_append_to_another(self):
57
+ # hits Index._concat
58
+ fst = Index(["a", "b"])
59
+ snd = CategoricalIndex(["d", "e"])
60
+ result = fst.append(snd)
61
+ expected = Index(["a", "b", "d", "e"])
62
+ tm.assert_index_equal(result, expected)
lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_astype.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import date
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ from pandas import (
7
+ Categorical,
8
+ CategoricalDtype,
9
+ CategoricalIndex,
10
+ Index,
11
+ IntervalIndex,
12
+ )
13
+ import pandas._testing as tm
14
+
15
+
16
+ class TestAstype:
17
+ def test_astype(self):
18
+ ci = CategoricalIndex(list("aabbca"), categories=list("cab"), ordered=False)
19
+
20
+ result = ci.astype(object)
21
+ tm.assert_index_equal(result, Index(np.array(ci), dtype=object))
22
+
23
+ # this IS equal, but not the same class
24
+ assert result.equals(ci)
25
+ assert isinstance(result, Index)
26
+ assert not isinstance(result, CategoricalIndex)
27
+
28
+ # interval
29
+ ii = IntervalIndex.from_arrays(left=[-0.001, 2.0], right=[2, 4], closed="right")
30
+
31
+ ci = CategoricalIndex(
32
+ Categorical.from_codes([0, 1, -1], categories=ii, ordered=True)
33
+ )
34
+
35
+ result = ci.astype("interval")
36
+ expected = ii.take([0, 1, -1], allow_fill=True, fill_value=np.nan)
37
+ tm.assert_index_equal(result, expected)
38
+
39
+ result = IntervalIndex(result.values)
40
+ tm.assert_index_equal(result, expected)
41
+
42
+ @pytest.mark.parametrize("name", [None, "foo"])
43
+ @pytest.mark.parametrize("dtype_ordered", [True, False])
44
+ @pytest.mark.parametrize("index_ordered", [True, False])
45
+ def test_astype_category(self, name, dtype_ordered, index_ordered):
46
+ # GH#18630
47
+ index = CategoricalIndex(
48
+ list("aabbca"), categories=list("cab"), ordered=index_ordered
49
+ )
50
+ if name:
51
+ index = index.rename(name)
52
+
53
+ # standard categories
54
+ dtype = CategoricalDtype(ordered=dtype_ordered)
55
+ result = index.astype(dtype)
56
+ expected = CategoricalIndex(
57
+ index.tolist(),
58
+ name=name,
59
+ categories=index.categories,
60
+ ordered=dtype_ordered,
61
+ )
62
+ tm.assert_index_equal(result, expected)
63
+
64
+ # non-standard categories
65
+ dtype = CategoricalDtype(index.unique().tolist()[:-1], dtype_ordered)
66
+ result = index.astype(dtype)
67
+ expected = CategoricalIndex(index.tolist(), name=name, dtype=dtype)
68
+ tm.assert_index_equal(result, expected)
69
+
70
+ if dtype_ordered is False:
71
+ # dtype='category' can't specify ordered, so only test once
72
+ result = index.astype("category")
73
+ expected = index
74
+ tm.assert_index_equal(result, expected)
75
+
76
+ @pytest.mark.parametrize("box", [True, False])
77
+ def test_categorical_date_roundtrip(self, box):
78
+ # astype to categorical and back should preserve date objects
79
+ v = date.today()
80
+
81
+ obj = Index([v, v])
82
+ assert obj.dtype == object
83
+ if box:
84
+ obj = obj.array
85
+
86
+ cat = obj.astype("category")
87
+
88
+ rtrip = cat.astype(object)
89
+ assert rtrip.dtype == object
90
+ assert type(rtrip[0]) is date
lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_category.py ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas._config import using_pyarrow_string_dtype
5
+
6
+ from pandas._libs import index as libindex
7
+ from pandas._libs.arrays import NDArrayBacked
8
+
9
+ import pandas as pd
10
+ from pandas import (
11
+ Categorical,
12
+ CategoricalDtype,
13
+ )
14
+ import pandas._testing as tm
15
+ from pandas.core.indexes.api import (
16
+ CategoricalIndex,
17
+ Index,
18
+ )
19
+
20
+
21
+ class TestCategoricalIndex:
22
+ @pytest.fixture
23
+ def simple_index(self) -> CategoricalIndex:
24
+ return CategoricalIndex(list("aabbca"), categories=list("cab"), ordered=False)
25
+
26
+ def test_can_hold_identifiers(self):
27
+ idx = CategoricalIndex(list("aabbca"), categories=None, ordered=False)
28
+ key = idx[0]
29
+ assert idx._can_hold_identifiers_and_holds_name(key) is True
30
+
31
+ def test_insert(self, simple_index):
32
+ ci = simple_index
33
+ categories = ci.categories
34
+
35
+ # test 0th element
36
+ result = ci.insert(0, "a")
37
+ expected = CategoricalIndex(list("aaabbca"), categories=categories)
38
+ tm.assert_index_equal(result, expected, exact=True)
39
+
40
+ # test Nth element that follows Python list behavior
41
+ result = ci.insert(-1, "a")
42
+ expected = CategoricalIndex(list("aabbcaa"), categories=categories)
43
+ tm.assert_index_equal(result, expected, exact=True)
44
+
45
+ # test empty
46
+ result = CategoricalIndex([], categories=categories).insert(0, "a")
47
+ expected = CategoricalIndex(["a"], categories=categories)
48
+ tm.assert_index_equal(result, expected, exact=True)
49
+
50
+ # invalid -> cast to object
51
+ expected = ci.astype(object).insert(0, "d")
52
+ result = ci.insert(0, "d").astype(object)
53
+ tm.assert_index_equal(result, expected, exact=True)
54
+
55
+ # GH 18295 (test missing)
56
+ expected = CategoricalIndex(["a", np.nan, "a", "b", "c", "b"])
57
+ for na in (np.nan, pd.NaT, None):
58
+ result = CategoricalIndex(list("aabcb")).insert(1, na)
59
+ tm.assert_index_equal(result, expected)
60
+
61
+ def test_insert_na_mismatched_dtype(self):
62
+ ci = CategoricalIndex([0, 1, 1])
63
+ result = ci.insert(0, pd.NaT)
64
+ expected = Index([pd.NaT, 0, 1, 1], dtype=object)
65
+ tm.assert_index_equal(result, expected)
66
+
67
+ def test_delete(self, simple_index):
68
+ ci = simple_index
69
+ categories = ci.categories
70
+
71
+ result = ci.delete(0)
72
+ expected = CategoricalIndex(list("abbca"), categories=categories)
73
+ tm.assert_index_equal(result, expected, exact=True)
74
+
75
+ result = ci.delete(-1)
76
+ expected = CategoricalIndex(list("aabbc"), categories=categories)
77
+ tm.assert_index_equal(result, expected, exact=True)
78
+
79
+ with tm.external_error_raised((IndexError, ValueError)):
80
+ # Either depending on NumPy version
81
+ ci.delete(10)
82
+
83
+ @pytest.mark.parametrize(
84
+ "data, non_lexsorted_data",
85
+ [[[1, 2, 3], [9, 0, 1, 2, 3]], [list("abc"), list("fabcd")]],
86
+ )
87
+ def test_is_monotonic(self, data, non_lexsorted_data):
88
+ c = CategoricalIndex(data)
89
+ assert c.is_monotonic_increasing is True
90
+ assert c.is_monotonic_decreasing is False
91
+
92
+ c = CategoricalIndex(data, ordered=True)
93
+ assert c.is_monotonic_increasing is True
94
+ assert c.is_monotonic_decreasing is False
95
+
96
+ c = CategoricalIndex(data, categories=reversed(data))
97
+ assert c.is_monotonic_increasing is False
98
+ assert c.is_monotonic_decreasing is True
99
+
100
+ c = CategoricalIndex(data, categories=reversed(data), ordered=True)
101
+ assert c.is_monotonic_increasing is False
102
+ assert c.is_monotonic_decreasing is True
103
+
104
+ # test when data is neither monotonic increasing nor decreasing
105
+ reordered_data = [data[0], data[2], data[1]]
106
+ c = CategoricalIndex(reordered_data, categories=reversed(data))
107
+ assert c.is_monotonic_increasing is False
108
+ assert c.is_monotonic_decreasing is False
109
+
110
+ # non lexsorted categories
111
+ categories = non_lexsorted_data
112
+
113
+ c = CategoricalIndex(categories[:2], categories=categories)
114
+ assert c.is_monotonic_increasing is True
115
+ assert c.is_monotonic_decreasing is False
116
+
117
+ c = CategoricalIndex(categories[1:3], categories=categories)
118
+ assert c.is_monotonic_increasing is True
119
+ assert c.is_monotonic_decreasing is False
120
+
121
+ def test_has_duplicates(self):
122
+ idx = CategoricalIndex([0, 0, 0], name="foo")
123
+ assert idx.is_unique is False
124
+ assert idx.has_duplicates is True
125
+
126
+ idx = CategoricalIndex([0, 1], categories=[2, 3], name="foo")
127
+ assert idx.is_unique is False
128
+ assert idx.has_duplicates is True
129
+
130
+ idx = CategoricalIndex([0, 1, 2, 3], categories=[1, 2, 3], name="foo")
131
+ assert idx.is_unique is True
132
+ assert idx.has_duplicates is False
133
+
134
+ @pytest.mark.parametrize(
135
+ "data, categories, expected",
136
+ [
137
+ (
138
+ [1, 1, 1],
139
+ [1, 2, 3],
140
+ {
141
+ "first": np.array([False, True, True]),
142
+ "last": np.array([True, True, False]),
143
+ False: np.array([True, True, True]),
144
+ },
145
+ ),
146
+ (
147
+ [1, 1, 1],
148
+ list("abc"),
149
+ {
150
+ "first": np.array([False, True, True]),
151
+ "last": np.array([True, True, False]),
152
+ False: np.array([True, True, True]),
153
+ },
154
+ ),
155
+ (
156
+ [2, "a", "b"],
157
+ list("abc"),
158
+ {
159
+ "first": np.zeros(shape=(3), dtype=np.bool_),
160
+ "last": np.zeros(shape=(3), dtype=np.bool_),
161
+ False: np.zeros(shape=(3), dtype=np.bool_),
162
+ },
163
+ ),
164
+ (
165
+ list("abb"),
166
+ list("abc"),
167
+ {
168
+ "first": np.array([False, False, True]),
169
+ "last": np.array([False, True, False]),
170
+ False: np.array([False, True, True]),
171
+ },
172
+ ),
173
+ ],
174
+ )
175
+ def test_drop_duplicates(self, data, categories, expected):
176
+ idx = CategoricalIndex(data, categories=categories, name="foo")
177
+ for keep, e in expected.items():
178
+ tm.assert_numpy_array_equal(idx.duplicated(keep=keep), e)
179
+ e = idx[~e]
180
+ result = idx.drop_duplicates(keep=keep)
181
+ tm.assert_index_equal(result, e)
182
+
183
+ @pytest.mark.parametrize(
184
+ "data, categories, expected_data",
185
+ [
186
+ ([1, 1, 1], [1, 2, 3], [1]),
187
+ ([1, 1, 1], list("abc"), [np.nan]),
188
+ ([1, 2, "a"], [1, 2, 3], [1, 2, np.nan]),
189
+ ([2, "a", "b"], list("abc"), [np.nan, "a", "b"]),
190
+ ],
191
+ )
192
+ def test_unique(self, data, categories, expected_data, ordered):
193
+ dtype = CategoricalDtype(categories, ordered=ordered)
194
+
195
+ idx = CategoricalIndex(data, dtype=dtype)
196
+ expected = CategoricalIndex(expected_data, dtype=dtype)
197
+ tm.assert_index_equal(idx.unique(), expected)
198
+
199
+ @pytest.mark.xfail(using_pyarrow_string_dtype(), reason="repr doesn't roundtrip")
200
+ def test_repr_roundtrip(self):
201
+ ci = CategoricalIndex(["a", "b"], categories=["a", "b"], ordered=True)
202
+ str(ci)
203
+ tm.assert_index_equal(eval(repr(ci)), ci, exact=True)
204
+
205
+ # formatting
206
+ str(ci)
207
+
208
+ # long format
209
+ # this is not reprable
210
+ ci = CategoricalIndex(np.random.default_rng(2).integers(0, 5, size=100))
211
+ str(ci)
212
+
213
+ def test_isin(self):
214
+ ci = CategoricalIndex(list("aabca") + [np.nan], categories=["c", "a", "b"])
215
+ tm.assert_numpy_array_equal(
216
+ ci.isin(["c"]), np.array([False, False, False, True, False, False])
217
+ )
218
+ tm.assert_numpy_array_equal(
219
+ ci.isin(["c", "a", "b"]), np.array([True] * 5 + [False])
220
+ )
221
+ tm.assert_numpy_array_equal(
222
+ ci.isin(["c", "a", "b", np.nan]), np.array([True] * 6)
223
+ )
224
+
225
+ # mismatched categorical -> coerced to ndarray so doesn't matter
226
+ result = ci.isin(ci.set_categories(list("abcdefghi")))
227
+ expected = np.array([True] * 6)
228
+ tm.assert_numpy_array_equal(result, expected)
229
+
230
+ result = ci.isin(ci.set_categories(list("defghi")))
231
+ expected = np.array([False] * 5 + [True])
232
+ tm.assert_numpy_array_equal(result, expected)
233
+
234
+ def test_isin_overlapping_intervals(self):
235
+ # GH 34974
236
+ idx = pd.IntervalIndex([pd.Interval(0, 2), pd.Interval(0, 1)])
237
+ result = CategoricalIndex(idx).isin(idx)
238
+ expected = np.array([True, True])
239
+ tm.assert_numpy_array_equal(result, expected)
240
+
241
+ def test_identical(self):
242
+ ci1 = CategoricalIndex(["a", "b"], categories=["a", "b"], ordered=True)
243
+ ci2 = CategoricalIndex(["a", "b"], categories=["a", "b", "c"], ordered=True)
244
+ assert ci1.identical(ci1)
245
+ assert ci1.identical(ci1.copy())
246
+ assert not ci1.identical(ci2)
247
+
248
+ def test_ensure_copied_data(self):
249
+ # gh-12309: Check the "copy" argument of each
250
+ # Index.__new__ is honored.
251
+ #
252
+ # Must be tested separately from other indexes because
253
+ # self.values is not an ndarray.
254
+ index = CategoricalIndex(list("ab") * 5)
255
+
256
+ result = CategoricalIndex(index.values, copy=True)
257
+ tm.assert_index_equal(index, result)
258
+ assert not np.shares_memory(result._data._codes, index._data._codes)
259
+
260
+ result = CategoricalIndex(index.values, copy=False)
261
+ assert result._data._codes is index._data._codes
262
+
263
+
264
+ class TestCategoricalIndex2:
265
+ def test_view_i8(self):
266
+ # GH#25464
267
+ ci = CategoricalIndex(list("ab") * 50)
268
+ msg = "When changing to a larger dtype, its size must be a divisor"
269
+ with pytest.raises(ValueError, match=msg):
270
+ ci.view("i8")
271
+ with pytest.raises(ValueError, match=msg):
272
+ ci._data.view("i8")
273
+
274
+ ci = ci[:-4] # length divisible by 8
275
+
276
+ res = ci.view("i8")
277
+ expected = ci._data.codes.view("i8")
278
+ tm.assert_numpy_array_equal(res, expected)
279
+
280
+ cat = ci._data
281
+ tm.assert_numpy_array_equal(cat.view("i8"), expected)
282
+
283
+ @pytest.mark.parametrize(
284
+ "dtype, engine_type",
285
+ [
286
+ (np.int8, libindex.Int8Engine),
287
+ (np.int16, libindex.Int16Engine),
288
+ (np.int32, libindex.Int32Engine),
289
+ (np.int64, libindex.Int64Engine),
290
+ ],
291
+ )
292
+ def test_engine_type(self, dtype, engine_type):
293
+ if dtype != np.int64:
294
+ # num. of uniques required to push CategoricalIndex.codes to a
295
+ # dtype (128 categories required for .codes dtype to be int16 etc.)
296
+ num_uniques = {np.int8: 1, np.int16: 128, np.int32: 32768}[dtype]
297
+ ci = CategoricalIndex(range(num_uniques))
298
+ else:
299
+ # having 2**32 - 2**31 categories would be very memory-intensive,
300
+ # so we cheat a bit with the dtype
301
+ ci = CategoricalIndex(range(32768)) # == 2**16 - 2**(16 - 1)
302
+ arr = ci.values._ndarray.astype("int64")
303
+ NDArrayBacked.__init__(ci._data, arr, ci.dtype)
304
+ assert np.issubdtype(ci.codes.dtype, dtype)
305
+ assert isinstance(ci._engine, engine_type)
306
+
307
+ @pytest.mark.parametrize(
308
+ "func,op_name",
309
+ [
310
+ (lambda idx: idx - idx, "__sub__"),
311
+ (lambda idx: idx + idx, "__add__"),
312
+ (lambda idx: idx - ["a", "b"], "__sub__"),
313
+ (lambda idx: idx + ["a", "b"], "__add__"),
314
+ (lambda idx: ["a", "b"] - idx, "__rsub__"),
315
+ (lambda idx: ["a", "b"] + idx, "__radd__"),
316
+ ],
317
+ )
318
+ def test_disallow_addsub_ops(self, func, op_name):
319
+ # GH 10039
320
+ # set ops (+/-) raise TypeError
321
+ idx = Index(Categorical(["a", "b"]))
322
+ cat_or_list = "'(Categorical|list)' and '(Categorical|list)'"
323
+ msg = "|".join(
324
+ [
325
+ f"cannot perform {op_name} with this index type: CategoricalIndex",
326
+ "can only concatenate list",
327
+ rf"unsupported operand type\(s\) for [\+-]: {cat_or_list}",
328
+ ]
329
+ )
330
+ with pytest.raises(TypeError, match=msg):
331
+ func(idx)
332
+
333
+ def test_method_delegation(self):
334
+ ci = CategoricalIndex(list("aabbca"), categories=list("cabdef"))
335
+ result = ci.set_categories(list("cab"))
336
+ tm.assert_index_equal(
337
+ result, CategoricalIndex(list("aabbca"), categories=list("cab"))
338
+ )
339
+
340
+ ci = CategoricalIndex(list("aabbca"), categories=list("cab"))
341
+ result = ci.rename_categories(list("efg"))
342
+ tm.assert_index_equal(
343
+ result, CategoricalIndex(list("ffggef"), categories=list("efg"))
344
+ )
345
+
346
+ # GH18862 (let rename_categories take callables)
347
+ result = ci.rename_categories(lambda x: x.upper())
348
+ tm.assert_index_equal(
349
+ result, CategoricalIndex(list("AABBCA"), categories=list("CAB"))
350
+ )
351
+
352
+ ci = CategoricalIndex(list("aabbca"), categories=list("cab"))
353
+ result = ci.add_categories(["d"])
354
+ tm.assert_index_equal(
355
+ result, CategoricalIndex(list("aabbca"), categories=list("cabd"))
356
+ )
357
+
358
+ ci = CategoricalIndex(list("aabbca"), categories=list("cab"))
359
+ result = ci.remove_categories(["c"])
360
+ tm.assert_index_equal(
361
+ result,
362
+ CategoricalIndex(list("aabb") + [np.nan] + ["a"], categories=list("ab")),
363
+ )
364
+
365
+ ci = CategoricalIndex(list("aabbca"), categories=list("cabdef"))
366
+ result = ci.as_unordered()
367
+ tm.assert_index_equal(result, ci)
368
+
369
+ ci = CategoricalIndex(list("aabbca"), categories=list("cabdef"))
370
+ result = ci.as_ordered()
371
+ tm.assert_index_equal(
372
+ result,
373
+ CategoricalIndex(list("aabbca"), categories=list("cabdef"), ordered=True),
374
+ )
375
+
376
+ # invalid
377
+ msg = "cannot use inplace with CategoricalIndex"
378
+ with pytest.raises(ValueError, match=msg):
379
+ ci.set_categories(list("cab"), inplace=True)
380
+
381
+ def test_remove_maintains_order(self):
382
+ ci = CategoricalIndex(list("abcdda"), categories=list("abcd"))
383
+ result = ci.reorder_categories(["d", "c", "b", "a"], ordered=True)
384
+ tm.assert_index_equal(
385
+ result,
386
+ CategoricalIndex(list("abcdda"), categories=list("dcba"), ordered=True),
387
+ )
388
+ result = result.remove_categories(["c"])
389
+ tm.assert_index_equal(
390
+ result,
391
+ CategoricalIndex(
392
+ ["a", "b", np.nan, "d", "d", "a"], categories=list("dba"), ordered=True
393
+ ),
394
+ )
lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_constructors.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas import (
5
+ Categorical,
6
+ CategoricalDtype,
7
+ CategoricalIndex,
8
+ Index,
9
+ )
10
+ import pandas._testing as tm
11
+
12
+
13
+ class TestCategoricalIndexConstructors:
14
+ def test_construction_disallows_scalar(self):
15
+ msg = "must be called with a collection of some kind"
16
+ with pytest.raises(TypeError, match=msg):
17
+ CategoricalIndex(data=1, categories=list("abcd"), ordered=False)
18
+ with pytest.raises(TypeError, match=msg):
19
+ CategoricalIndex(categories=list("abcd"), ordered=False)
20
+
21
+ def test_construction(self):
22
+ ci = CategoricalIndex(list("aabbca"), categories=list("abcd"), ordered=False)
23
+ categories = ci.categories
24
+
25
+ result = Index(ci)
26
+ tm.assert_index_equal(result, ci, exact=True)
27
+ assert not result.ordered
28
+
29
+ result = Index(ci.values)
30
+ tm.assert_index_equal(result, ci, exact=True)
31
+ assert not result.ordered
32
+
33
+ # empty
34
+ result = CategoricalIndex([], categories=categories)
35
+ tm.assert_index_equal(result.categories, Index(categories))
36
+ tm.assert_numpy_array_equal(result.codes, np.array([], dtype="int8"))
37
+ assert not result.ordered
38
+
39
+ # passing categories
40
+ result = CategoricalIndex(list("aabbca"), categories=categories)
41
+ tm.assert_index_equal(result.categories, Index(categories))
42
+ tm.assert_numpy_array_equal(
43
+ result.codes, np.array([0, 0, 1, 1, 2, 0], dtype="int8")
44
+ )
45
+
46
+ c = Categorical(list("aabbca"))
47
+ result = CategoricalIndex(c)
48
+ tm.assert_index_equal(result.categories, Index(list("abc")))
49
+ tm.assert_numpy_array_equal(
50
+ result.codes, np.array([0, 0, 1, 1, 2, 0], dtype="int8")
51
+ )
52
+ assert not result.ordered
53
+
54
+ result = CategoricalIndex(c, categories=categories)
55
+ tm.assert_index_equal(result.categories, Index(categories))
56
+ tm.assert_numpy_array_equal(
57
+ result.codes, np.array([0, 0, 1, 1, 2, 0], dtype="int8")
58
+ )
59
+ assert not result.ordered
60
+
61
+ ci = CategoricalIndex(c, categories=list("abcd"))
62
+ result = CategoricalIndex(ci)
63
+ tm.assert_index_equal(result.categories, Index(categories))
64
+ tm.assert_numpy_array_equal(
65
+ result.codes, np.array([0, 0, 1, 1, 2, 0], dtype="int8")
66
+ )
67
+ assert not result.ordered
68
+
69
+ result = CategoricalIndex(ci, categories=list("ab"))
70
+ tm.assert_index_equal(result.categories, Index(list("ab")))
71
+ tm.assert_numpy_array_equal(
72
+ result.codes, np.array([0, 0, 1, 1, -1, 0], dtype="int8")
73
+ )
74
+ assert not result.ordered
75
+
76
+ result = CategoricalIndex(ci, categories=list("ab"), ordered=True)
77
+ tm.assert_index_equal(result.categories, Index(list("ab")))
78
+ tm.assert_numpy_array_equal(
79
+ result.codes, np.array([0, 0, 1, 1, -1, 0], dtype="int8")
80
+ )
81
+ assert result.ordered
82
+
83
+ result = CategoricalIndex(ci, categories=list("ab"), ordered=True)
84
+ expected = CategoricalIndex(
85
+ ci, categories=list("ab"), ordered=True, dtype="category"
86
+ )
87
+ tm.assert_index_equal(result, expected, exact=True)
88
+
89
+ # turn me to an Index
90
+ result = Index(np.array(ci))
91
+ assert isinstance(result, Index)
92
+ assert not isinstance(result, CategoricalIndex)
93
+
94
+ def test_construction_with_dtype(self):
95
+ # specify dtype
96
+ ci = CategoricalIndex(list("aabbca"), categories=list("abc"), ordered=False)
97
+
98
+ result = Index(np.array(ci), dtype="category")
99
+ tm.assert_index_equal(result, ci, exact=True)
100
+
101
+ result = Index(np.array(ci).tolist(), dtype="category")
102
+ tm.assert_index_equal(result, ci, exact=True)
103
+
104
+ # these are generally only equal when the categories are reordered
105
+ ci = CategoricalIndex(list("aabbca"), categories=list("cab"), ordered=False)
106
+
107
+ result = Index(np.array(ci), dtype="category").reorder_categories(ci.categories)
108
+ tm.assert_index_equal(result, ci, exact=True)
109
+
110
+ # make sure indexes are handled
111
+ idx = Index(range(3))
112
+ expected = CategoricalIndex([0, 1, 2], categories=idx, ordered=True)
113
+ result = CategoricalIndex(idx, categories=idx, ordered=True)
114
+ tm.assert_index_equal(result, expected, exact=True)
115
+
116
+ def test_construction_empty_with_bool_categories(self):
117
+ # see GH#22702
118
+ cat = CategoricalIndex([], categories=[True, False])
119
+ categories = sorted(cat.categories.tolist())
120
+ assert categories == [False, True]
121
+
122
+ def test_construction_with_categorical_dtype(self):
123
+ # construction with CategoricalDtype
124
+ # GH#18109
125
+ data, cats, ordered = "a a b b".split(), "c b a".split(), True
126
+ dtype = CategoricalDtype(categories=cats, ordered=ordered)
127
+
128
+ result = CategoricalIndex(data, dtype=dtype)
129
+ expected = CategoricalIndex(data, categories=cats, ordered=ordered)
130
+ tm.assert_index_equal(result, expected, exact=True)
131
+
132
+ # GH#19032
133
+ result = Index(data, dtype=dtype)
134
+ tm.assert_index_equal(result, expected, exact=True)
135
+
136
+ # error when combining categories/ordered and dtype kwargs
137
+ msg = "Cannot specify `categories` or `ordered` together with `dtype`."
138
+ with pytest.raises(ValueError, match=msg):
139
+ CategoricalIndex(data, categories=cats, dtype=dtype)
140
+
141
+ with pytest.raises(ValueError, match=msg):
142
+ CategoricalIndex(data, ordered=ordered, dtype=dtype)
lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_equals.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas import (
5
+ Categorical,
6
+ CategoricalIndex,
7
+ Index,
8
+ MultiIndex,
9
+ )
10
+
11
+
12
+ class TestEquals:
13
+ def test_equals_categorical(self):
14
+ ci1 = CategoricalIndex(["a", "b"], categories=["a", "b"], ordered=True)
15
+ ci2 = CategoricalIndex(["a", "b"], categories=["a", "b", "c"], ordered=True)
16
+
17
+ assert ci1.equals(ci1)
18
+ assert not ci1.equals(ci2)
19
+ assert ci1.equals(ci1.astype(object))
20
+ assert ci1.astype(object).equals(ci1)
21
+
22
+ assert (ci1 == ci1).all()
23
+ assert not (ci1 != ci1).all()
24
+ assert not (ci1 > ci1).all()
25
+ assert not (ci1 < ci1).all()
26
+ assert (ci1 <= ci1).all()
27
+ assert (ci1 >= ci1).all()
28
+
29
+ assert not (ci1 == 1).all()
30
+ assert (ci1 == Index(["a", "b"])).all()
31
+ assert (ci1 == ci1.values).all()
32
+
33
+ # invalid comparisons
34
+ with pytest.raises(ValueError, match="Lengths must match"):
35
+ ci1 == Index(["a", "b", "c"])
36
+
37
+ msg = "Categoricals can only be compared if 'categories' are the same"
38
+ with pytest.raises(TypeError, match=msg):
39
+ ci1 == ci2
40
+ with pytest.raises(TypeError, match=msg):
41
+ ci1 == Categorical(ci1.values, ordered=False)
42
+ with pytest.raises(TypeError, match=msg):
43
+ ci1 == Categorical(ci1.values, categories=list("abc"))
44
+
45
+ # tests
46
+ # make sure that we are testing for category inclusion properly
47
+ ci = CategoricalIndex(list("aabca"), categories=["c", "a", "b"])
48
+ assert not ci.equals(list("aabca"))
49
+ # Same categories, but different order
50
+ # Unordered
51
+ assert ci.equals(CategoricalIndex(list("aabca")))
52
+ # Ordered
53
+ assert not ci.equals(CategoricalIndex(list("aabca"), ordered=True))
54
+ assert ci.equals(ci.copy())
55
+
56
+ ci = CategoricalIndex(list("aabca") + [np.nan], categories=["c", "a", "b"])
57
+ assert not ci.equals(list("aabca"))
58
+ assert not ci.equals(CategoricalIndex(list("aabca")))
59
+ assert ci.equals(ci.copy())
60
+
61
+ ci = CategoricalIndex(list("aabca") + [np.nan], categories=["c", "a", "b"])
62
+ assert not ci.equals(list("aabca") + [np.nan])
63
+ assert ci.equals(CategoricalIndex(list("aabca") + [np.nan]))
64
+ assert not ci.equals(CategoricalIndex(list("aabca") + [np.nan], ordered=True))
65
+ assert ci.equals(ci.copy())
66
+
67
+ def test_equals_categorical_unordered(self):
68
+ # https://github.com/pandas-dev/pandas/issues/16603
69
+ a = CategoricalIndex(["A"], categories=["A", "B"])
70
+ b = CategoricalIndex(["A"], categories=["B", "A"])
71
+ c = CategoricalIndex(["C"], categories=["B", "A"])
72
+ assert a.equals(b)
73
+ assert not a.equals(c)
74
+ assert not b.equals(c)
75
+
76
+ def test_equals_non_category(self):
77
+ # GH#37667 Case where other contains a value not among ci's
78
+ # categories ("D") and also contains np.nan
79
+ ci = CategoricalIndex(["A", "B", np.nan, np.nan])
80
+ other = Index(["A", "B", "D", np.nan])
81
+
82
+ assert not ci.equals(other)
83
+
84
+ def test_equals_multiindex(self):
85
+ # dont raise NotImplementedError when calling is_dtype_compat
86
+
87
+ mi = MultiIndex.from_arrays([["A", "B", "C", "D"], range(4)])
88
+ ci = mi.to_flat_index().astype("category")
89
+
90
+ assert not ci.equals(mi)
91
+
92
+ def test_equals_string_dtype(self, any_string_dtype):
93
+ # GH#55364
94
+ idx = CategoricalIndex(list("abc"), name="B")
95
+ other = Index(["a", "b", "c"], name="B", dtype=any_string_dtype)
96
+ assert idx.equals(other)
lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_fillna.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas import CategoricalIndex
5
+ import pandas._testing as tm
6
+
7
+
8
+ class TestFillNA:
9
+ def test_fillna_categorical(self):
10
+ # GH#11343
11
+ idx = CategoricalIndex([1.0, np.nan, 3.0, 1.0], name="x")
12
+ # fill by value in categories
13
+ exp = CategoricalIndex([1.0, 1.0, 3.0, 1.0], name="x")
14
+ tm.assert_index_equal(idx.fillna(1.0), exp)
15
+
16
+ cat = idx._data
17
+
18
+ # fill by value not in categories raises TypeError on EA, casts on CI
19
+ msg = "Cannot setitem on a Categorical with a new category"
20
+ with pytest.raises(TypeError, match=msg):
21
+ cat.fillna(2.0)
22
+
23
+ result = idx.fillna(2.0)
24
+ expected = idx.astype(object).fillna(2.0)
25
+ tm.assert_index_equal(result, expected)
26
+
27
+ def test_fillna_copies_with_no_nas(self):
28
+ # Nothing to fill, should still get a copy for the Categorical method,
29
+ # but OK to get a view on CategoricalIndex method
30
+ ci = CategoricalIndex([0, 1, 1])
31
+ result = ci.fillna(0)
32
+ assert result is not ci
33
+ assert tm.shares_memory(result, ci)
34
+
35
+ # But at the EA level we always get a copy.
36
+ cat = ci._data
37
+ result = cat.fillna(0)
38
+ assert result._ndarray is not cat._ndarray
39
+ assert result._ndarray.base is None
40
+ assert not tm.shares_memory(result, cat)
41
+
42
+ def test_fillna_validates_with_no_nas(self):
43
+ # We validate the fill value even if fillna is a no-op
44
+ ci = CategoricalIndex([2, 3, 3])
45
+ cat = ci._data
46
+
47
+ msg = "Cannot setitem on a Categorical with a new category"
48
+ res = ci.fillna(False)
49
+ # nothing to fill, so we dont cast
50
+ tm.assert_index_equal(res, ci)
51
+
52
+ # Same check directly on the Categorical
53
+ with pytest.raises(TypeError, match=msg):
54
+ cat.fillna(False)
lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_formats.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests for CategoricalIndex.__repr__ and related methods.
3
+ """
4
+ import pytest
5
+
6
+ from pandas._config import using_pyarrow_string_dtype
7
+ import pandas._config.config as cf
8
+
9
+ from pandas import CategoricalIndex
10
+ import pandas._testing as tm
11
+
12
+
13
+ class TestCategoricalIndexRepr:
14
+ def test_format_different_scalar_lengths(self):
15
+ # GH#35439
16
+ idx = CategoricalIndex(["aaaaaaaaa", "b"])
17
+ expected = ["aaaaaaaaa", "b"]
18
+ msg = r"CategoricalIndex\.format is deprecated"
19
+ with tm.assert_produces_warning(FutureWarning, match=msg):
20
+ assert idx.format() == expected
21
+
22
+ @pytest.mark.xfail(using_pyarrow_string_dtype(), reason="repr different")
23
+ def test_string_categorical_index_repr(self):
24
+ # short
25
+ idx = CategoricalIndex(["a", "bb", "ccc"])
26
+ expected = """CategoricalIndex(['a', 'bb', 'ccc'], categories=['a', 'bb', 'ccc'], ordered=False, dtype='category')""" # noqa: E501
27
+ assert repr(idx) == expected
28
+
29
+ # multiple lines
30
+ idx = CategoricalIndex(["a", "bb", "ccc"] * 10)
31
+ expected = """CategoricalIndex(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a',
32
+ 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb',
33
+ 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc'],
34
+ categories=['a', 'bb', 'ccc'], ordered=False, dtype='category')""" # noqa: E501
35
+
36
+ assert repr(idx) == expected
37
+
38
+ # truncated
39
+ idx = CategoricalIndex(["a", "bb", "ccc"] * 100)
40
+ expected = """CategoricalIndex(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a',
41
+ ...
42
+ 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc'],
43
+ categories=['a', 'bb', 'ccc'], ordered=False, dtype='category', length=300)""" # noqa: E501
44
+
45
+ assert repr(idx) == expected
46
+
47
+ # larger categories
48
+ idx = CategoricalIndex(list("abcdefghijklmmo"))
49
+ expected = """CategoricalIndex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
50
+ 'm', 'm', 'o'],
51
+ categories=['a', 'b', 'c', 'd', ..., 'k', 'l', 'm', 'o'], ordered=False, dtype='category')""" # noqa: E501
52
+
53
+ assert repr(idx) == expected
54
+
55
+ # short
56
+ idx = CategoricalIndex(["あ", "いい", "ううう"])
57
+ expected = """CategoricalIndex(['あ', 'いい', 'ううう'], categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')""" # noqa: E501
58
+ assert repr(idx) == expected
59
+
60
+ # multiple lines
61
+ idx = CategoricalIndex(["あ", "いい", "ううう"] * 10)
62
+ expected = """CategoricalIndex(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ',
63
+ 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい',
64
+ 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう'],
65
+ categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')""" # noqa: E501
66
+
67
+ assert repr(idx) == expected
68
+
69
+ # truncated
70
+ idx = CategoricalIndex(["あ", "いい", "ううう"] * 100)
71
+ expected = """CategoricalIndex(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ',
72
+ ...
73
+ 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう'],
74
+ categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category', length=300)""" # noqa: E501
75
+
76
+ assert repr(idx) == expected
77
+
78
+ # larger categories
79
+ idx = CategoricalIndex(list("あいうえおかきくけこさしすせそ"))
80
+ expected = """CategoricalIndex(['あ', 'い', 'う', 'え', 'お', 'か', 'き', 'く', 'け', 'こ', 'さ', 'し',
81
+ 'す', 'せ', 'そ'],
82
+ categories=['あ', 'い', 'う', 'え', ..., 'し', 'す', 'せ', 'そ'], ordered=False, dtype='category')""" # noqa: E501
83
+
84
+ assert repr(idx) == expected
85
+
86
+ # Enable Unicode option -----------------------------------------
87
+ with cf.option_context("display.unicode.east_asian_width", True):
88
+ # short
89
+ idx = CategoricalIndex(["あ", "いい", "ううう"])
90
+ expected = """CategoricalIndex(['あ', 'いい', 'ううう'], categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')""" # noqa: E501
91
+ assert repr(idx) == expected
92
+
93
+ # multiple lines
94
+ idx = CategoricalIndex(["あ", "いい", "ううう"] * 10)
95
+ expected = """CategoricalIndex(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい',
96
+ 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう',
97
+ 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい',
98
+ 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう'],
99
+ categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')""" # noqa: E501
100
+
101
+ assert repr(idx) == expected
102
+
103
+ # truncated
104
+ idx = CategoricalIndex(["あ", "いい", "ううう"] * 100)
105
+ expected = """CategoricalIndex(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい',
106
+ 'ううう', 'あ',
107
+ ...
108
+ 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう',
109
+ 'あ', 'いい', 'ううう'],
110
+ categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category', length=300)""" # noqa: E501
111
+
112
+ assert repr(idx) == expected
113
+
114
+ # larger categories
115
+ idx = CategoricalIndex(list("あいうえおかきくけこさしすせそ"))
116
+ expected = """CategoricalIndex(['あ', 'い', 'う', 'え', 'お', 'か', 'き', 'く', 'け', 'こ',
117
+ 'さ', 'し', 'す', 'せ', 'そ'],
118
+ categories=['あ', 'い', 'う', 'え', ..., 'し', 'す', 'せ', 'そ'], ordered=False, dtype='category')""" # noqa: E501
119
+
120
+ assert repr(idx) == expected
lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_indexing.py ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas.errors import InvalidIndexError
5
+
6
+ import pandas as pd
7
+ from pandas import (
8
+ CategoricalIndex,
9
+ Index,
10
+ IntervalIndex,
11
+ Timestamp,
12
+ )
13
+ import pandas._testing as tm
14
+
15
+
16
+ class TestTake:
17
+ def test_take_fill_value(self):
18
+ # GH 12631
19
+
20
+ # numeric category
21
+ idx = CategoricalIndex([1, 2, 3], name="xxx")
22
+ result = idx.take(np.array([1, 0, -1]))
23
+ expected = CategoricalIndex([2, 1, 3], name="xxx")
24
+ tm.assert_index_equal(result, expected)
25
+ tm.assert_categorical_equal(result.values, expected.values)
26
+
27
+ # fill_value
28
+ result = idx.take(np.array([1, 0, -1]), fill_value=True)
29
+ expected = CategoricalIndex([2, 1, np.nan], categories=[1, 2, 3], name="xxx")
30
+ tm.assert_index_equal(result, expected)
31
+ tm.assert_categorical_equal(result.values, expected.values)
32
+
33
+ # allow_fill=False
34
+ result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True)
35
+ expected = CategoricalIndex([2, 1, 3], name="xxx")
36
+ tm.assert_index_equal(result, expected)
37
+ tm.assert_categorical_equal(result.values, expected.values)
38
+
39
+ # object category
40
+ idx = CategoricalIndex(
41
+ list("CBA"), categories=list("ABC"), ordered=True, name="xxx"
42
+ )
43
+ result = idx.take(np.array([1, 0, -1]))
44
+ expected = CategoricalIndex(
45
+ list("BCA"), categories=list("ABC"), ordered=True, name="xxx"
46
+ )
47
+ tm.assert_index_equal(result, expected)
48
+ tm.assert_categorical_equal(result.values, expected.values)
49
+
50
+ # fill_value
51
+ result = idx.take(np.array([1, 0, -1]), fill_value=True)
52
+ expected = CategoricalIndex(
53
+ ["B", "C", np.nan], categories=list("ABC"), ordered=True, name="xxx"
54
+ )
55
+ tm.assert_index_equal(result, expected)
56
+ tm.assert_categorical_equal(result.values, expected.values)
57
+
58
+ # allow_fill=False
59
+ result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True)
60
+ expected = CategoricalIndex(
61
+ list("BCA"), categories=list("ABC"), ordered=True, name="xxx"
62
+ )
63
+ tm.assert_index_equal(result, expected)
64
+ tm.assert_categorical_equal(result.values, expected.values)
65
+
66
+ msg = (
67
+ "When allow_fill=True and fill_value is not None, "
68
+ "all indices must be >= -1"
69
+ )
70
+ with pytest.raises(ValueError, match=msg):
71
+ idx.take(np.array([1, 0, -2]), fill_value=True)
72
+ with pytest.raises(ValueError, match=msg):
73
+ idx.take(np.array([1, 0, -5]), fill_value=True)
74
+
75
+ msg = "index -5 is out of bounds for (axis 0 with )?size 3"
76
+ with pytest.raises(IndexError, match=msg):
77
+ idx.take(np.array([1, -5]))
78
+
79
+ def test_take_fill_value_datetime(self):
80
+ # datetime category
81
+ idx = pd.DatetimeIndex(["2011-01-01", "2011-02-01", "2011-03-01"], name="xxx")
82
+ idx = CategoricalIndex(idx)
83
+ result = idx.take(np.array([1, 0, -1]))
84
+ expected = pd.DatetimeIndex(
85
+ ["2011-02-01", "2011-01-01", "2011-03-01"], name="xxx"
86
+ )
87
+ expected = CategoricalIndex(expected)
88
+ tm.assert_index_equal(result, expected)
89
+
90
+ # fill_value
91
+ result = idx.take(np.array([1, 0, -1]), fill_value=True)
92
+ expected = pd.DatetimeIndex(["2011-02-01", "2011-01-01", "NaT"], name="xxx")
93
+ exp_cats = pd.DatetimeIndex(["2011-01-01", "2011-02-01", "2011-03-01"])
94
+ expected = CategoricalIndex(expected, categories=exp_cats)
95
+ tm.assert_index_equal(result, expected)
96
+
97
+ # allow_fill=False
98
+ result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True)
99
+ expected = pd.DatetimeIndex(
100
+ ["2011-02-01", "2011-01-01", "2011-03-01"], name="xxx"
101
+ )
102
+ expected = CategoricalIndex(expected)
103
+ tm.assert_index_equal(result, expected)
104
+
105
+ msg = (
106
+ "When allow_fill=True and fill_value is not None, "
107
+ "all indices must be >= -1"
108
+ )
109
+ with pytest.raises(ValueError, match=msg):
110
+ idx.take(np.array([1, 0, -2]), fill_value=True)
111
+ with pytest.raises(ValueError, match=msg):
112
+ idx.take(np.array([1, 0, -5]), fill_value=True)
113
+
114
+ msg = "index -5 is out of bounds for (axis 0 with )?size 3"
115
+ with pytest.raises(IndexError, match=msg):
116
+ idx.take(np.array([1, -5]))
117
+
118
+ def test_take_invalid_kwargs(self):
119
+ idx = CategoricalIndex([1, 2, 3], name="foo")
120
+ indices = [1, 0, -1]
121
+
122
+ msg = r"take\(\) got an unexpected keyword argument 'foo'"
123
+ with pytest.raises(TypeError, match=msg):
124
+ idx.take(indices, foo=2)
125
+
126
+ msg = "the 'out' parameter is not supported"
127
+ with pytest.raises(ValueError, match=msg):
128
+ idx.take(indices, out=indices)
129
+
130
+ msg = "the 'mode' parameter is not supported"
131
+ with pytest.raises(ValueError, match=msg):
132
+ idx.take(indices, mode="clip")
133
+
134
+
135
+ class TestGetLoc:
136
+ def test_get_loc(self):
137
+ # GH 12531
138
+ cidx1 = CategoricalIndex(list("abcde"), categories=list("edabc"))
139
+ idx1 = Index(list("abcde"))
140
+ assert cidx1.get_loc("a") == idx1.get_loc("a")
141
+ assert cidx1.get_loc("e") == idx1.get_loc("e")
142
+
143
+ for i in [cidx1, idx1]:
144
+ with pytest.raises(KeyError, match="'NOT-EXIST'"):
145
+ i.get_loc("NOT-EXIST")
146
+
147
+ # non-unique
148
+ cidx2 = CategoricalIndex(list("aacded"), categories=list("edabc"))
149
+ idx2 = Index(list("aacded"))
150
+
151
+ # results in bool array
152
+ res = cidx2.get_loc("d")
153
+ tm.assert_numpy_array_equal(res, idx2.get_loc("d"))
154
+ tm.assert_numpy_array_equal(
155
+ res, np.array([False, False, False, True, False, True])
156
+ )
157
+ # unique element results in scalar
158
+ res = cidx2.get_loc("e")
159
+ assert res == idx2.get_loc("e")
160
+ assert res == 4
161
+
162
+ for i in [cidx2, idx2]:
163
+ with pytest.raises(KeyError, match="'NOT-EXIST'"):
164
+ i.get_loc("NOT-EXIST")
165
+
166
+ # non-unique, sliceable
167
+ cidx3 = CategoricalIndex(list("aabbb"), categories=list("abc"))
168
+ idx3 = Index(list("aabbb"))
169
+
170
+ # results in slice
171
+ res = cidx3.get_loc("a")
172
+ assert res == idx3.get_loc("a")
173
+ assert res == slice(0, 2, None)
174
+
175
+ res = cidx3.get_loc("b")
176
+ assert res == idx3.get_loc("b")
177
+ assert res == slice(2, 5, None)
178
+
179
+ for i in [cidx3, idx3]:
180
+ with pytest.raises(KeyError, match="'c'"):
181
+ i.get_loc("c")
182
+
183
+ def test_get_loc_unique(self):
184
+ cidx = CategoricalIndex(list("abc"))
185
+ result = cidx.get_loc("b")
186
+ assert result == 1
187
+
188
+ def test_get_loc_monotonic_nonunique(self):
189
+ cidx = CategoricalIndex(list("abbc"))
190
+ result = cidx.get_loc("b")
191
+ expected = slice(1, 3, None)
192
+ assert result == expected
193
+
194
+ def test_get_loc_nonmonotonic_nonunique(self):
195
+ cidx = CategoricalIndex(list("abcb"))
196
+ result = cidx.get_loc("b")
197
+ expected = np.array([False, True, False, True], dtype=bool)
198
+ tm.assert_numpy_array_equal(result, expected)
199
+
200
+ def test_get_loc_nan(self):
201
+ # GH#41933
202
+ ci = CategoricalIndex(["A", "B", np.nan])
203
+ res = ci.get_loc(np.nan)
204
+
205
+ assert res == 2
206
+
207
+
208
+ class TestGetIndexer:
209
+ def test_get_indexer_base(self):
210
+ # Determined by cat ordering.
211
+ idx = CategoricalIndex(list("cab"), categories=list("cab"))
212
+ expected = np.arange(len(idx), dtype=np.intp)
213
+
214
+ actual = idx.get_indexer(idx)
215
+ tm.assert_numpy_array_equal(expected, actual)
216
+
217
+ with pytest.raises(ValueError, match="Invalid fill method"):
218
+ idx.get_indexer(idx, method="invalid")
219
+
220
+ def test_get_indexer_requires_unique(self):
221
+ ci = CategoricalIndex(list("aabbca"), categories=list("cab"), ordered=False)
222
+ oidx = Index(np.array(ci))
223
+
224
+ msg = "Reindexing only valid with uniquely valued Index objects"
225
+
226
+ for n in [1, 2, 5, len(ci)]:
227
+ finder = oidx[np.random.default_rng(2).integers(0, len(ci), size=n)]
228
+
229
+ with pytest.raises(InvalidIndexError, match=msg):
230
+ ci.get_indexer(finder)
231
+
232
+ # see gh-17323
233
+ #
234
+ # Even when indexer is equal to the
235
+ # members in the index, we should
236
+ # respect duplicates instead of taking
237
+ # the fast-track path.
238
+ for finder in [list("aabbca"), list("aababca")]:
239
+ with pytest.raises(InvalidIndexError, match=msg):
240
+ ci.get_indexer(finder)
241
+
242
+ def test_get_indexer_non_unique(self):
243
+ idx1 = CategoricalIndex(list("aabcde"), categories=list("edabc"))
244
+ idx2 = CategoricalIndex(list("abf"))
245
+
246
+ for indexer in [idx2, list("abf"), Index(list("abf"))]:
247
+ msg = "Reindexing only valid with uniquely valued Index objects"
248
+ with pytest.raises(InvalidIndexError, match=msg):
249
+ idx1.get_indexer(indexer)
250
+
251
+ r1, _ = idx1.get_indexer_non_unique(indexer)
252
+ expected = np.array([0, 1, 2, -1], dtype=np.intp)
253
+ tm.assert_almost_equal(r1, expected)
254
+
255
+ def test_get_indexer_method(self):
256
+ idx1 = CategoricalIndex(list("aabcde"), categories=list("edabc"))
257
+ idx2 = CategoricalIndex(list("abf"))
258
+
259
+ msg = "method pad not yet implemented for CategoricalIndex"
260
+ with pytest.raises(NotImplementedError, match=msg):
261
+ idx2.get_indexer(idx1, method="pad")
262
+ msg = "method backfill not yet implemented for CategoricalIndex"
263
+ with pytest.raises(NotImplementedError, match=msg):
264
+ idx2.get_indexer(idx1, method="backfill")
265
+
266
+ msg = "method nearest not yet implemented for CategoricalIndex"
267
+ with pytest.raises(NotImplementedError, match=msg):
268
+ idx2.get_indexer(idx1, method="nearest")
269
+
270
+ def test_get_indexer_array(self):
271
+ arr = np.array(
272
+ [Timestamp("1999-12-31 00:00:00"), Timestamp("2000-12-31 00:00:00")],
273
+ dtype=object,
274
+ )
275
+ cats = [Timestamp("1999-12-31 00:00:00"), Timestamp("2000-12-31 00:00:00")]
276
+ ci = CategoricalIndex(cats, categories=cats, ordered=False, dtype="category")
277
+ result = ci.get_indexer(arr)
278
+ expected = np.array([0, 1], dtype="intp")
279
+ tm.assert_numpy_array_equal(result, expected)
280
+
281
+ def test_get_indexer_same_categories_same_order(self):
282
+ ci = CategoricalIndex(["a", "b"], categories=["a", "b"])
283
+
284
+ result = ci.get_indexer(CategoricalIndex(["b", "b"], categories=["a", "b"]))
285
+ expected = np.array([1, 1], dtype="intp")
286
+ tm.assert_numpy_array_equal(result, expected)
287
+
288
+ def test_get_indexer_same_categories_different_order(self):
289
+ # https://github.com/pandas-dev/pandas/issues/19551
290
+ ci = CategoricalIndex(["a", "b"], categories=["a", "b"])
291
+
292
+ result = ci.get_indexer(CategoricalIndex(["b", "b"], categories=["b", "a"]))
293
+ expected = np.array([1, 1], dtype="intp")
294
+ tm.assert_numpy_array_equal(result, expected)
295
+
296
+ def test_get_indexer_nans_in_index_and_target(self):
297
+ # GH 45361
298
+ ci = CategoricalIndex([1, 2, np.nan, 3])
299
+ other1 = [2, 3, 4, np.nan]
300
+ res1 = ci.get_indexer(other1)
301
+ expected1 = np.array([1, 3, -1, 2], dtype=np.intp)
302
+ tm.assert_numpy_array_equal(res1, expected1)
303
+ other2 = [1, 4, 2, 3]
304
+ res2 = ci.get_indexer(other2)
305
+ expected2 = np.array([0, -1, 1, 3], dtype=np.intp)
306
+ tm.assert_numpy_array_equal(res2, expected2)
307
+
308
+
309
+ class TestWhere:
310
+ def test_where(self, listlike_box):
311
+ klass = listlike_box
312
+
313
+ i = CategoricalIndex(list("aabbca"), categories=list("cab"), ordered=False)
314
+ cond = [True] * len(i)
315
+ expected = i
316
+ result = i.where(klass(cond))
317
+ tm.assert_index_equal(result, expected)
318
+
319
+ cond = [False] + [True] * (len(i) - 1)
320
+ expected = CategoricalIndex([np.nan] + i[1:].tolist(), categories=i.categories)
321
+ result = i.where(klass(cond))
322
+ tm.assert_index_equal(result, expected)
323
+
324
+ def test_where_non_categories(self):
325
+ ci = CategoricalIndex(["a", "b", "c", "d"])
326
+ mask = np.array([True, False, True, False])
327
+
328
+ result = ci.where(mask, 2)
329
+ expected = Index(["a", 2, "c", 2], dtype=object)
330
+ tm.assert_index_equal(result, expected)
331
+
332
+ msg = "Cannot setitem on a Categorical with a new category"
333
+ with pytest.raises(TypeError, match=msg):
334
+ # Test the Categorical method directly
335
+ ci._data._where(mask, 2)
336
+
337
+
338
+ class TestContains:
339
+ def test_contains(self):
340
+ ci = CategoricalIndex(list("aabbca"), categories=list("cabdef"), ordered=False)
341
+
342
+ assert "a" in ci
343
+ assert "z" not in ci
344
+ assert "e" not in ci
345
+ assert np.nan not in ci
346
+
347
+ # assert codes NOT in index
348
+ assert 0 not in ci
349
+ assert 1 not in ci
350
+
351
+ def test_contains_nan(self):
352
+ ci = CategoricalIndex(list("aabbca") + [np.nan], categories=list("cabdef"))
353
+ assert np.nan in ci
354
+
355
+ @pytest.mark.parametrize("unwrap", [True, False])
356
+ def test_contains_na_dtype(self, unwrap):
357
+ dti = pd.date_range("2016-01-01", periods=100).insert(0, pd.NaT)
358
+ pi = dti.to_period("D")
359
+ tdi = dti - dti[-1]
360
+ ci = CategoricalIndex(dti)
361
+
362
+ obj = ci
363
+ if unwrap:
364
+ obj = ci._data
365
+
366
+ assert np.nan in obj
367
+ assert None in obj
368
+ assert pd.NaT in obj
369
+ assert np.datetime64("NaT") in obj
370
+ assert np.timedelta64("NaT") not in obj
371
+
372
+ obj2 = CategoricalIndex(tdi)
373
+ if unwrap:
374
+ obj2 = obj2._data
375
+
376
+ assert np.nan in obj2
377
+ assert None in obj2
378
+ assert pd.NaT in obj2
379
+ assert np.datetime64("NaT") not in obj2
380
+ assert np.timedelta64("NaT") in obj2
381
+
382
+ obj3 = CategoricalIndex(pi)
383
+ if unwrap:
384
+ obj3 = obj3._data
385
+
386
+ assert np.nan in obj3
387
+ assert None in obj3
388
+ assert pd.NaT in obj3
389
+ assert np.datetime64("NaT") not in obj3
390
+ assert np.timedelta64("NaT") not in obj3
391
+
392
+ @pytest.mark.parametrize(
393
+ "item, expected",
394
+ [
395
+ (pd.Interval(0, 1), True),
396
+ (1.5, True),
397
+ (pd.Interval(0.5, 1.5), False),
398
+ ("a", False),
399
+ (Timestamp(1), False),
400
+ (pd.Timedelta(1), False),
401
+ ],
402
+ ids=str,
403
+ )
404
+ def test_contains_interval(self, item, expected):
405
+ # GH 23705
406
+ ci = CategoricalIndex(IntervalIndex.from_breaks(range(3)))
407
+ result = item in ci
408
+ assert result is expected
409
+
410
+ def test_contains_list(self):
411
+ # GH#21729
412
+ idx = CategoricalIndex([1, 2, 3])
413
+
414
+ assert "a" not in idx
415
+
416
+ with pytest.raises(TypeError, match="unhashable type"):
417
+ ["a"] in idx
418
+
419
+ with pytest.raises(TypeError, match="unhashable type"):
420
+ ["a", "b"] in idx
lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_map.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ import pandas as pd
5
+ from pandas import (
6
+ CategoricalIndex,
7
+ Index,
8
+ Series,
9
+ )
10
+ import pandas._testing as tm
11
+
12
+
13
+ @pytest.mark.parametrize(
14
+ "data, categories",
15
+ [
16
+ (list("abcbca"), list("cab")),
17
+ (pd.interval_range(0, 3).repeat(3), pd.interval_range(0, 3)),
18
+ ],
19
+ ids=["string", "interval"],
20
+ )
21
+ def test_map_str(data, categories, ordered):
22
+ # GH 31202 - override base class since we want to maintain categorical/ordered
23
+ index = CategoricalIndex(data, categories=categories, ordered=ordered)
24
+ result = index.map(str)
25
+ expected = CategoricalIndex(
26
+ map(str, data), categories=map(str, categories), ordered=ordered
27
+ )
28
+ tm.assert_index_equal(result, expected)
29
+
30
+
31
+ def test_map():
32
+ ci = CategoricalIndex(list("ABABC"), categories=list("CBA"), ordered=True)
33
+ result = ci.map(lambda x: x.lower())
34
+ exp = CategoricalIndex(list("ababc"), categories=list("cba"), ordered=True)
35
+ tm.assert_index_equal(result, exp)
36
+
37
+ ci = CategoricalIndex(
38
+ list("ABABC"), categories=list("BAC"), ordered=False, name="XXX"
39
+ )
40
+ result = ci.map(lambda x: x.lower())
41
+ exp = CategoricalIndex(
42
+ list("ababc"), categories=list("bac"), ordered=False, name="XXX"
43
+ )
44
+ tm.assert_index_equal(result, exp)
45
+
46
+ # GH 12766: Return an index not an array
47
+ tm.assert_index_equal(
48
+ ci.map(lambda x: 1), Index(np.array([1] * 5, dtype=np.int64), name="XXX")
49
+ )
50
+
51
+ # change categories dtype
52
+ ci = CategoricalIndex(list("ABABC"), categories=list("BAC"), ordered=False)
53
+
54
+ def f(x):
55
+ return {"A": 10, "B": 20, "C": 30}.get(x)
56
+
57
+ result = ci.map(f)
58
+ exp = CategoricalIndex([10, 20, 10, 20, 30], categories=[20, 10, 30], ordered=False)
59
+ tm.assert_index_equal(result, exp)
60
+
61
+ result = ci.map(Series([10, 20, 30], index=["A", "B", "C"]))
62
+ tm.assert_index_equal(result, exp)
63
+
64
+ result = ci.map({"A": 10, "B": 20, "C": 30})
65
+ tm.assert_index_equal(result, exp)
66
+
67
+
68
+ def test_map_with_categorical_series():
69
+ # GH 12756
70
+ a = Index([1, 2, 3, 4])
71
+ b = Series(["even", "odd", "even", "odd"], dtype="category")
72
+ c = Series(["even", "odd", "even", "odd"])
73
+
74
+ exp = CategoricalIndex(["odd", "even", "odd", np.nan])
75
+ tm.assert_index_equal(a.map(b), exp)
76
+ exp = Index(["odd", "even", "odd", np.nan])
77
+ tm.assert_index_equal(a.map(c), exp)
78
+
79
+
80
+ @pytest.mark.parametrize(
81
+ ("data", "f", "expected"),
82
+ (
83
+ ([1, 1, np.nan], pd.isna, CategoricalIndex([False, False, np.nan])),
84
+ ([1, 2, np.nan], pd.isna, Index([False, False, np.nan])),
85
+ ([1, 1, np.nan], {1: False}, CategoricalIndex([False, False, np.nan])),
86
+ ([1, 2, np.nan], {1: False, 2: False}, Index([False, False, np.nan])),
87
+ (
88
+ [1, 1, np.nan],
89
+ Series([False, False]),
90
+ CategoricalIndex([False, False, np.nan]),
91
+ ),
92
+ (
93
+ [1, 2, np.nan],
94
+ Series([False, False, False]),
95
+ Index([False, False, np.nan]),
96
+ ),
97
+ ),
98
+ )
99
+ def test_map_with_nan_ignore(data, f, expected): # GH 24241
100
+ values = CategoricalIndex(data)
101
+ result = values.map(f, na_action="ignore")
102
+ tm.assert_index_equal(result, expected)
103
+
104
+
105
+ @pytest.mark.parametrize(
106
+ ("data", "f", "expected"),
107
+ (
108
+ ([1, 1, np.nan], pd.isna, Index([False, False, True])),
109
+ ([1, 2, np.nan], pd.isna, Index([False, False, True])),
110
+ ([1, 1, np.nan], {1: False}, CategoricalIndex([False, False, np.nan])),
111
+ ([1, 2, np.nan], {1: False, 2: False}, Index([False, False, np.nan])),
112
+ (
113
+ [1, 1, np.nan],
114
+ Series([False, False]),
115
+ CategoricalIndex([False, False, np.nan]),
116
+ ),
117
+ (
118
+ [1, 2, np.nan],
119
+ Series([False, False, False]),
120
+ Index([False, False, np.nan]),
121
+ ),
122
+ ),
123
+ )
124
+ def test_map_with_nan_none(data, f, expected): # GH 24241
125
+ values = CategoricalIndex(data)
126
+ result = values.map(f, na_action=None)
127
+ tm.assert_index_equal(result, expected)
128
+
129
+
130
+ def test_map_with_dict_or_series():
131
+ orig_values = ["a", "B", 1, "a"]
132
+ new_values = ["one", 2, 3.0, "one"]
133
+ cur_index = CategoricalIndex(orig_values, name="XXX")
134
+ expected = CategoricalIndex(new_values, name="XXX", categories=[3.0, 2, "one"])
135
+
136
+ mapper = Series(new_values[:-1], index=orig_values[:-1])
137
+ result = cur_index.map(mapper)
138
+ # Order of categories in result can be different
139
+ tm.assert_index_equal(result, expected)
140
+
141
+ mapper = dict(zip(orig_values[:-1], new_values[:-1]))
142
+ result = cur_index.map(mapper)
143
+ # Order of categories in result can be different
144
+ tm.assert_index_equal(result, expected)
lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_reindex.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas import (
5
+ Categorical,
6
+ CategoricalIndex,
7
+ Index,
8
+ Interval,
9
+ )
10
+ import pandas._testing as tm
11
+
12
+
13
+ class TestReindex:
14
+ def test_reindex_list_non_unique(self):
15
+ # GH#11586
16
+ msg = "cannot reindex on an axis with duplicate labels"
17
+ ci = CategoricalIndex(["a", "b", "c", "a"])
18
+ with pytest.raises(ValueError, match=msg):
19
+ ci.reindex(["a", "c"])
20
+
21
+ def test_reindex_categorical_non_unique(self):
22
+ msg = "cannot reindex on an axis with duplicate labels"
23
+ ci = CategoricalIndex(["a", "b", "c", "a"])
24
+ with pytest.raises(ValueError, match=msg):
25
+ ci.reindex(Categorical(["a", "c"]))
26
+
27
+ def test_reindex_list_non_unique_unused_category(self):
28
+ msg = "cannot reindex on an axis with duplicate labels"
29
+ ci = CategoricalIndex(["a", "b", "c", "a"], categories=["a", "b", "c", "d"])
30
+ with pytest.raises(ValueError, match=msg):
31
+ ci.reindex(["a", "c"])
32
+
33
+ def test_reindex_categorical_non_unique_unused_category(self):
34
+ msg = "cannot reindex on an axis with duplicate labels"
35
+ ci = CategoricalIndex(["a", "b", "c", "a"], categories=["a", "b", "c", "d"])
36
+ with pytest.raises(ValueError, match=msg):
37
+ ci.reindex(Categorical(["a", "c"]))
38
+
39
+ def test_reindex_duplicate_target(self):
40
+ # See GH25459
41
+ cat = CategoricalIndex(["a", "b", "c"], categories=["a", "b", "c", "d"])
42
+ res, indexer = cat.reindex(["a", "c", "c"])
43
+ exp = Index(["a", "c", "c"])
44
+ tm.assert_index_equal(res, exp, exact=True)
45
+ tm.assert_numpy_array_equal(indexer, np.array([0, 2, 2], dtype=np.intp))
46
+
47
+ res, indexer = cat.reindex(
48
+ CategoricalIndex(["a", "c", "c"], categories=["a", "b", "c", "d"])
49
+ )
50
+ exp = CategoricalIndex(["a", "c", "c"], categories=["a", "b", "c", "d"])
51
+ tm.assert_index_equal(res, exp, exact=True)
52
+ tm.assert_numpy_array_equal(indexer, np.array([0, 2, 2], dtype=np.intp))
53
+
54
+ def test_reindex_empty_index(self):
55
+ # See GH16770
56
+ c = CategoricalIndex([])
57
+ res, indexer = c.reindex(["a", "b"])
58
+ tm.assert_index_equal(res, Index(["a", "b"]), exact=True)
59
+ tm.assert_numpy_array_equal(indexer, np.array([-1, -1], dtype=np.intp))
60
+
61
+ def test_reindex_categorical_added_category(self):
62
+ # GH 42424
63
+ ci = CategoricalIndex(
64
+ [Interval(0, 1, closed="right"), Interval(1, 2, closed="right")],
65
+ ordered=True,
66
+ )
67
+ ci_add = CategoricalIndex(
68
+ [
69
+ Interval(0, 1, closed="right"),
70
+ Interval(1, 2, closed="right"),
71
+ Interval(2, 3, closed="right"),
72
+ Interval(3, 4, closed="right"),
73
+ ],
74
+ ordered=True,
75
+ )
76
+ result, _ = ci.reindex(ci_add)
77
+ expected = ci_add
78
+ tm.assert_index_equal(expected, result)
lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_setops.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas import (
5
+ CategoricalIndex,
6
+ Index,
7
+ )
8
+ import pandas._testing as tm
9
+
10
+
11
+ @pytest.mark.parametrize("na_value", [None, np.nan])
12
+ def test_difference_with_na(na_value):
13
+ # GH 57318
14
+ ci = CategoricalIndex(["a", "b", "c", None])
15
+ other = Index(["c", na_value])
16
+ result = ci.difference(other)
17
+ expected = CategoricalIndex(["a", "b"], categories=["a", "b", "c"])
18
+ tm.assert_index_equal(result, expected)
lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__init__.py ADDED
File without changes
lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_drop_duplicates.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas import (
5
+ PeriodIndex,
6
+ Series,
7
+ date_range,
8
+ period_range,
9
+ timedelta_range,
10
+ )
11
+ import pandas._testing as tm
12
+
13
+
14
+ class DropDuplicates:
15
+ def test_drop_duplicates_metadata(self, idx):
16
+ # GH#10115
17
+ result = idx.drop_duplicates()
18
+ tm.assert_index_equal(idx, result)
19
+ assert idx.freq == result.freq
20
+
21
+ idx_dup = idx.append(idx)
22
+ result = idx_dup.drop_duplicates()
23
+
24
+ expected = idx
25
+ if not isinstance(idx, PeriodIndex):
26
+ # freq is reset except for PeriodIndex
27
+ assert idx_dup.freq is None
28
+ assert result.freq is None
29
+ expected = idx._with_freq(None)
30
+ else:
31
+ assert result.freq == expected.freq
32
+
33
+ tm.assert_index_equal(result, expected)
34
+
35
+ @pytest.mark.parametrize(
36
+ "keep, expected, index",
37
+ [
38
+ (
39
+ "first",
40
+ np.concatenate(([False] * 10, [True] * 5)),
41
+ np.arange(0, 10, dtype=np.int64),
42
+ ),
43
+ (
44
+ "last",
45
+ np.concatenate(([True] * 5, [False] * 10)),
46
+ np.arange(5, 15, dtype=np.int64),
47
+ ),
48
+ (
49
+ False,
50
+ np.concatenate(([True] * 5, [False] * 5, [True] * 5)),
51
+ np.arange(5, 10, dtype=np.int64),
52
+ ),
53
+ ],
54
+ )
55
+ def test_drop_duplicates(self, keep, expected, index, idx):
56
+ # to check Index/Series compat
57
+ idx = idx.append(idx[:5])
58
+
59
+ tm.assert_numpy_array_equal(idx.duplicated(keep=keep), expected)
60
+ expected = idx[~expected]
61
+
62
+ result = idx.drop_duplicates(keep=keep)
63
+ tm.assert_index_equal(result, expected)
64
+
65
+ result = Series(idx).drop_duplicates(keep=keep)
66
+ expected = Series(expected, index=index)
67
+ tm.assert_series_equal(result, expected)
68
+
69
+
70
+ class TestDropDuplicatesPeriodIndex(DropDuplicates):
71
+ @pytest.fixture(params=["D", "3D", "h", "2h", "min", "2min", "s", "3s"])
72
+ def freq(self, request):
73
+ return request.param
74
+
75
+ @pytest.fixture
76
+ def idx(self, freq):
77
+ return period_range("2011-01-01", periods=10, freq=freq, name="idx")
78
+
79
+
80
+ class TestDropDuplicatesDatetimeIndex(DropDuplicates):
81
+ @pytest.fixture
82
+ def idx(self, freq_sample):
83
+ return date_range("2011-01-01", freq=freq_sample, periods=10, name="idx")
84
+
85
+
86
+ class TestDropDuplicatesTimedeltaIndex(DropDuplicates):
87
+ @pytest.fixture
88
+ def idx(self, freq_sample):
89
+ return timedelta_range("1 day", periods=10, freq=freq_sample, name="idx")
lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_equals.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests shared for DatetimeIndex/TimedeltaIndex/PeriodIndex
3
+ """
4
+ from datetime import (
5
+ datetime,
6
+ timedelta,
7
+ )
8
+
9
+ import numpy as np
10
+ import pytest
11
+
12
+ import pandas as pd
13
+ from pandas import (
14
+ CategoricalIndex,
15
+ DatetimeIndex,
16
+ Index,
17
+ PeriodIndex,
18
+ TimedeltaIndex,
19
+ date_range,
20
+ period_range,
21
+ timedelta_range,
22
+ )
23
+ import pandas._testing as tm
24
+
25
+
26
+ class EqualsTests:
27
+ def test_not_equals_numeric(self, index):
28
+ assert not index.equals(Index(index.asi8))
29
+ assert not index.equals(Index(index.asi8.astype("u8")))
30
+ assert not index.equals(Index(index.asi8).astype("f8"))
31
+
32
+ def test_equals(self, index):
33
+ assert index.equals(index)
34
+ assert index.equals(index.astype(object))
35
+ assert index.equals(CategoricalIndex(index))
36
+ assert index.equals(CategoricalIndex(index.astype(object)))
37
+
38
+ def test_not_equals_non_arraylike(self, index):
39
+ assert not index.equals(list(index))
40
+
41
+ def test_not_equals_strings(self, index):
42
+ other = Index([str(x) for x in index], dtype=object)
43
+ assert not index.equals(other)
44
+ assert not index.equals(CategoricalIndex(other))
45
+
46
+ def test_not_equals_misc_strs(self, index):
47
+ other = Index(list("abc"))
48
+ assert not index.equals(other)
49
+
50
+
51
+ class TestPeriodIndexEquals(EqualsTests):
52
+ @pytest.fixture
53
+ def index(self):
54
+ return period_range("2013-01-01", periods=5, freq="D")
55
+
56
+ # TODO: de-duplicate with other test_equals2 methods
57
+ @pytest.mark.parametrize("freq", ["D", "M"])
58
+ def test_equals2(self, freq):
59
+ # GH#13107
60
+ idx = PeriodIndex(["2011-01-01", "2011-01-02", "NaT"], freq=freq)
61
+ assert idx.equals(idx)
62
+ assert idx.equals(idx.copy())
63
+ assert idx.equals(idx.astype(object))
64
+ assert idx.astype(object).equals(idx)
65
+ assert idx.astype(object).equals(idx.astype(object))
66
+ assert not idx.equals(list(idx))
67
+ assert not idx.equals(pd.Series(idx))
68
+
69
+ idx2 = PeriodIndex(["2011-01-01", "2011-01-02", "NaT"], freq="h")
70
+ assert not idx.equals(idx2)
71
+ assert not idx.equals(idx2.copy())
72
+ assert not idx.equals(idx2.astype(object))
73
+ assert not idx.astype(object).equals(idx2)
74
+ assert not idx.equals(list(idx2))
75
+ assert not idx.equals(pd.Series(idx2))
76
+
77
+ # same internal, different tz
78
+ idx3 = PeriodIndex._simple_new(
79
+ idx._values._simple_new(idx._values.asi8, dtype=pd.PeriodDtype("h"))
80
+ )
81
+ tm.assert_numpy_array_equal(idx.asi8, idx3.asi8)
82
+ assert not idx.equals(idx3)
83
+ assert not idx.equals(idx3.copy())
84
+ assert not idx.equals(idx3.astype(object))
85
+ assert not idx.astype(object).equals(idx3)
86
+ assert not idx.equals(list(idx3))
87
+ assert not idx.equals(pd.Series(idx3))
88
+
89
+
90
+ class TestDatetimeIndexEquals(EqualsTests):
91
+ @pytest.fixture
92
+ def index(self):
93
+ return date_range("2013-01-01", periods=5)
94
+
95
+ def test_equals2(self):
96
+ # GH#13107
97
+ idx = DatetimeIndex(["2011-01-01", "2011-01-02", "NaT"])
98
+ assert idx.equals(idx)
99
+ assert idx.equals(idx.copy())
100
+ assert idx.equals(idx.astype(object))
101
+ assert idx.astype(object).equals(idx)
102
+ assert idx.astype(object).equals(idx.astype(object))
103
+ assert not idx.equals(list(idx))
104
+ assert not idx.equals(pd.Series(idx))
105
+
106
+ idx2 = DatetimeIndex(["2011-01-01", "2011-01-02", "NaT"], tz="US/Pacific")
107
+ assert not idx.equals(idx2)
108
+ assert not idx.equals(idx2.copy())
109
+ assert not idx.equals(idx2.astype(object))
110
+ assert not idx.astype(object).equals(idx2)
111
+ assert not idx.equals(list(idx2))
112
+ assert not idx.equals(pd.Series(idx2))
113
+
114
+ # same internal, different tz
115
+ idx3 = DatetimeIndex(idx.asi8, tz="US/Pacific")
116
+ tm.assert_numpy_array_equal(idx.asi8, idx3.asi8)
117
+ assert not idx.equals(idx3)
118
+ assert not idx.equals(idx3.copy())
119
+ assert not idx.equals(idx3.astype(object))
120
+ assert not idx.astype(object).equals(idx3)
121
+ assert not idx.equals(list(idx3))
122
+ assert not idx.equals(pd.Series(idx3))
123
+
124
+ # check that we do not raise when comparing with OutOfBounds objects
125
+ oob = Index([datetime(2500, 1, 1)] * 3, dtype=object)
126
+ assert not idx.equals(oob)
127
+ assert not idx2.equals(oob)
128
+ assert not idx3.equals(oob)
129
+
130
+ # check that we do not raise when comparing with OutOfBounds dt64
131
+ oob2 = oob.map(np.datetime64)
132
+ assert not idx.equals(oob2)
133
+ assert not idx2.equals(oob2)
134
+ assert not idx3.equals(oob2)
135
+
136
+ @pytest.mark.parametrize("freq", ["B", "C"])
137
+ def test_not_equals_bday(self, freq):
138
+ rng = date_range("2009-01-01", "2010-01-01", freq=freq)
139
+ assert not rng.equals(list(rng))
140
+
141
+
142
+ class TestTimedeltaIndexEquals(EqualsTests):
143
+ @pytest.fixture
144
+ def index(self):
145
+ return timedelta_range("1 day", periods=10)
146
+
147
+ def test_equals2(self):
148
+ # GH#13107
149
+ idx = TimedeltaIndex(["1 days", "2 days", "NaT"])
150
+ assert idx.equals(idx)
151
+ assert idx.equals(idx.copy())
152
+ assert idx.equals(idx.astype(object))
153
+ assert idx.astype(object).equals(idx)
154
+ assert idx.astype(object).equals(idx.astype(object))
155
+ assert not idx.equals(list(idx))
156
+ assert not idx.equals(pd.Series(idx))
157
+
158
+ idx2 = TimedeltaIndex(["2 days", "1 days", "NaT"])
159
+ assert not idx.equals(idx2)
160
+ assert not idx.equals(idx2.copy())
161
+ assert not idx.equals(idx2.astype(object))
162
+ assert not idx.astype(object).equals(idx2)
163
+ assert not idx.astype(object).equals(idx2.astype(object))
164
+ assert not idx.equals(list(idx2))
165
+ assert not idx.equals(pd.Series(idx2))
166
+
167
+ # Check that we dont raise OverflowError on comparisons outside the
168
+ # implementation range GH#28532
169
+ oob = Index([timedelta(days=10**6)] * 3, dtype=object)
170
+ assert not idx.equals(oob)
171
+ assert not idx2.equals(oob)
172
+
173
+ oob2 = Index([np.timedelta64(x) for x in oob], dtype=object)
174
+ assert (oob == oob2).all()
175
+ assert not idx.equals(oob2)
176
+ assert not idx2.equals(oob2)
177
+
178
+ oob3 = oob.map(np.timedelta64)
179
+ assert (oob3 == oob).all()
180
+ assert not idx.equals(oob3)
181
+ assert not idx2.equals(oob3)
lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_indexing.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ import pandas as pd
5
+ from pandas import (
6
+ DatetimeIndex,
7
+ Index,
8
+ )
9
+ import pandas._testing as tm
10
+
11
+ dtlike_dtypes = [
12
+ np.dtype("timedelta64[ns]"),
13
+ np.dtype("datetime64[ns]"),
14
+ pd.DatetimeTZDtype("ns", "Asia/Tokyo"),
15
+ pd.PeriodDtype("ns"),
16
+ ]
17
+
18
+
19
+ @pytest.mark.parametrize("ldtype", dtlike_dtypes)
20
+ @pytest.mark.parametrize("rdtype", dtlike_dtypes)
21
+ def test_get_indexer_non_unique_wrong_dtype(ldtype, rdtype):
22
+ vals = np.tile(3600 * 10**9 * np.arange(3, dtype=np.int64), 2)
23
+
24
+ def construct(dtype):
25
+ if dtype is dtlike_dtypes[-1]:
26
+ # PeriodArray will try to cast ints to strings
27
+ return DatetimeIndex(vals).astype(dtype)
28
+ return Index(vals, dtype=dtype)
29
+
30
+ left = construct(ldtype)
31
+ right = construct(rdtype)
32
+
33
+ result = left.get_indexer_non_unique(right)
34
+
35
+ if ldtype is rdtype:
36
+ ex1 = np.array([0, 3, 1, 4, 2, 5] * 2, dtype=np.intp)
37
+ ex2 = np.array([], dtype=np.intp)
38
+ tm.assert_numpy_array_equal(result[0], ex1)
39
+ tm.assert_numpy_array_equal(result[1], ex2)
40
+
41
+ else:
42
+ no_matches = np.array([-1] * 6, dtype=np.intp)
43
+ missing = np.arange(6, dtype=np.intp)
44
+ tm.assert_numpy_array_equal(result[0], no_matches)
45
+ tm.assert_numpy_array_equal(result[1], missing)
lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_is_monotonic.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pandas import (
2
+ Index,
3
+ NaT,
4
+ date_range,
5
+ )
6
+
7
+
8
+ def test_is_monotonic_with_nat():
9
+ # GH#31437
10
+ # PeriodIndex.is_monotonic_increasing should behave analogously to DatetimeIndex,
11
+ # in particular never be monotonic when we have NaT
12
+ dti = date_range("2016-01-01", periods=3)
13
+ pi = dti.to_period("D")
14
+ tdi = Index(dti.view("timedelta64[ns]"))
15
+
16
+ for obj in [pi, pi._engine, dti, dti._engine, tdi, tdi._engine]:
17
+ if isinstance(obj, Index):
18
+ # i.e. not Engines
19
+ assert obj.is_monotonic_increasing
20
+ assert obj.is_monotonic_increasing
21
+ assert not obj.is_monotonic_decreasing
22
+ assert obj.is_unique
23
+
24
+ dti1 = dti.insert(0, NaT)
25
+ pi1 = dti1.to_period("D")
26
+ tdi1 = Index(dti1.view("timedelta64[ns]"))
27
+
28
+ for obj in [pi1, pi1._engine, dti1, dti1._engine, tdi1, tdi1._engine]:
29
+ if isinstance(obj, Index):
30
+ # i.e. not Engines
31
+ assert not obj.is_monotonic_increasing
32
+ assert not obj.is_monotonic_increasing
33
+ assert not obj.is_monotonic_decreasing
34
+ assert obj.is_unique
35
+
36
+ dti2 = dti.insert(3, NaT)
37
+ pi2 = dti2.to_period("h")
38
+ tdi2 = Index(dti2.view("timedelta64[ns]"))
39
+
40
+ for obj in [pi2, pi2._engine, dti2, dti2._engine, tdi2, tdi2._engine]:
41
+ if isinstance(obj, Index):
42
+ # i.e. not Engines
43
+ assert not obj.is_monotonic_increasing
44
+ assert not obj.is_monotonic_increasing
45
+ assert not obj.is_monotonic_decreasing
46
+ assert obj.is_unique
lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_nat.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas import (
5
+ DatetimeIndex,
6
+ NaT,
7
+ PeriodIndex,
8
+ TimedeltaIndex,
9
+ )
10
+ import pandas._testing as tm
11
+
12
+
13
+ class NATests:
14
+ def test_nat(self, index_without_na):
15
+ empty_index = index_without_na[:0]
16
+
17
+ index_with_na = index_without_na.copy(deep=True)
18
+ index_with_na._data[1] = NaT
19
+
20
+ assert empty_index._na_value is NaT
21
+ assert index_with_na._na_value is NaT
22
+ assert index_without_na._na_value is NaT
23
+
24
+ idx = index_without_na
25
+ assert idx._can_hold_na
26
+
27
+ tm.assert_numpy_array_equal(idx._isnan, np.array([False, False]))
28
+ assert idx.hasnans is False
29
+
30
+ idx = index_with_na
31
+ assert idx._can_hold_na
32
+
33
+ tm.assert_numpy_array_equal(idx._isnan, np.array([False, True]))
34
+ assert idx.hasnans is True
35
+
36
+
37
+ class TestDatetimeIndexNA(NATests):
38
+ @pytest.fixture
39
+ def index_without_na(self, tz_naive_fixture):
40
+ tz = tz_naive_fixture
41
+ return DatetimeIndex(["2011-01-01", "2011-01-02"], tz=tz)
42
+
43
+
44
+ class TestTimedeltaIndexNA(NATests):
45
+ @pytest.fixture
46
+ def index_without_na(self):
47
+ return TimedeltaIndex(["1 days", "2 days"])
48
+
49
+
50
+ class TestPeriodIndexNA(NATests):
51
+ @pytest.fixture
52
+ def index_without_na(self):
53
+ return PeriodIndex(["2011-01-01", "2011-01-02"], freq="D")
lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_sort_values.py ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas import (
5
+ DatetimeIndex,
6
+ Index,
7
+ NaT,
8
+ PeriodIndex,
9
+ TimedeltaIndex,
10
+ timedelta_range,
11
+ )
12
+ import pandas._testing as tm
13
+
14
+
15
+ def check_freq_ascending(ordered, orig, ascending):
16
+ """
17
+ Check the expected freq on a PeriodIndex/DatetimeIndex/TimedeltaIndex
18
+ when the original index is generated (or generate-able) with
19
+ period_range/date_range/timedelta_range.
20
+ """
21
+ if isinstance(ordered, PeriodIndex):
22
+ assert ordered.freq == orig.freq
23
+ elif isinstance(ordered, (DatetimeIndex, TimedeltaIndex)):
24
+ if ascending:
25
+ assert ordered.freq.n == orig.freq.n
26
+ else:
27
+ assert ordered.freq.n == -1 * orig.freq.n
28
+
29
+
30
+ def check_freq_nonmonotonic(ordered, orig):
31
+ """
32
+ Check the expected freq on a PeriodIndex/DatetimeIndex/TimedeltaIndex
33
+ when the original index is _not_ generated (or generate-able) with
34
+ period_range/date_range//timedelta_range.
35
+ """
36
+ if isinstance(ordered, PeriodIndex):
37
+ assert ordered.freq == orig.freq
38
+ elif isinstance(ordered, (DatetimeIndex, TimedeltaIndex)):
39
+ assert ordered.freq is None
40
+
41
+
42
+ class TestSortValues:
43
+ @pytest.fixture(params=[DatetimeIndex, TimedeltaIndex, PeriodIndex])
44
+ def non_monotonic_idx(self, request):
45
+ if request.param is DatetimeIndex:
46
+ return DatetimeIndex(["2000-01-04", "2000-01-01", "2000-01-02"])
47
+ elif request.param is PeriodIndex:
48
+ dti = DatetimeIndex(["2000-01-04", "2000-01-01", "2000-01-02"])
49
+ return dti.to_period("D")
50
+ else:
51
+ return TimedeltaIndex(
52
+ ["1 day 00:00:05", "1 day 00:00:01", "1 day 00:00:02"]
53
+ )
54
+
55
+ def test_argmin_argmax(self, non_monotonic_idx):
56
+ assert non_monotonic_idx.argmin() == 1
57
+ assert non_monotonic_idx.argmax() == 0
58
+
59
+ def test_sort_values(self, non_monotonic_idx):
60
+ idx = non_monotonic_idx
61
+ ordered = idx.sort_values()
62
+ assert ordered.is_monotonic_increasing
63
+ ordered = idx.sort_values(ascending=False)
64
+ assert ordered[::-1].is_monotonic_increasing
65
+
66
+ ordered, dexer = idx.sort_values(return_indexer=True)
67
+ assert ordered.is_monotonic_increasing
68
+ tm.assert_numpy_array_equal(dexer, np.array([1, 2, 0], dtype=np.intp))
69
+
70
+ ordered, dexer = idx.sort_values(return_indexer=True, ascending=False)
71
+ assert ordered[::-1].is_monotonic_increasing
72
+ tm.assert_numpy_array_equal(dexer, np.array([0, 2, 1], dtype=np.intp))
73
+
74
+ def check_sort_values_with_freq(self, idx):
75
+ ordered = idx.sort_values()
76
+ tm.assert_index_equal(ordered, idx)
77
+ check_freq_ascending(ordered, idx, True)
78
+
79
+ ordered = idx.sort_values(ascending=False)
80
+ expected = idx[::-1]
81
+ tm.assert_index_equal(ordered, expected)
82
+ check_freq_ascending(ordered, idx, False)
83
+
84
+ ordered, indexer = idx.sort_values(return_indexer=True)
85
+ tm.assert_index_equal(ordered, idx)
86
+ tm.assert_numpy_array_equal(indexer, np.array([0, 1, 2], dtype=np.intp))
87
+ check_freq_ascending(ordered, idx, True)
88
+
89
+ ordered, indexer = idx.sort_values(return_indexer=True, ascending=False)
90
+ expected = idx[::-1]
91
+ tm.assert_index_equal(ordered, expected)
92
+ tm.assert_numpy_array_equal(indexer, np.array([2, 1, 0], dtype=np.intp))
93
+ check_freq_ascending(ordered, idx, False)
94
+
95
+ @pytest.mark.parametrize("freq", ["D", "h"])
96
+ def test_sort_values_with_freq_timedeltaindex(self, freq):
97
+ # GH#10295
98
+ idx = timedelta_range(start=f"1{freq}", periods=3, freq=freq).rename("idx")
99
+
100
+ self.check_sort_values_with_freq(idx)
101
+
102
+ @pytest.mark.parametrize(
103
+ "idx",
104
+ [
105
+ DatetimeIndex(
106
+ ["2011-01-01", "2011-01-02", "2011-01-03"], freq="D", name="idx"
107
+ ),
108
+ DatetimeIndex(
109
+ ["2011-01-01 09:00", "2011-01-01 10:00", "2011-01-01 11:00"],
110
+ freq="h",
111
+ name="tzidx",
112
+ tz="Asia/Tokyo",
113
+ ),
114
+ ],
115
+ )
116
+ def test_sort_values_with_freq_datetimeindex(self, idx):
117
+ self.check_sort_values_with_freq(idx)
118
+
119
+ @pytest.mark.parametrize("freq", ["D", "2D", "4D"])
120
+ def test_sort_values_with_freq_periodindex(self, freq):
121
+ # here with_freq refers to being period_range-like
122
+ idx = PeriodIndex(
123
+ ["2011-01-01", "2011-01-02", "2011-01-03"], freq=freq, name="idx"
124
+ )
125
+ self.check_sort_values_with_freq(idx)
126
+
127
+ @pytest.mark.parametrize(
128
+ "idx",
129
+ [
130
+ PeriodIndex(["2011", "2012", "2013"], name="pidx", freq="Y"),
131
+ Index([2011, 2012, 2013], name="idx"), # for compatibility check
132
+ ],
133
+ )
134
+ def test_sort_values_with_freq_periodindex2(self, idx):
135
+ # here with_freq indicates this is period_range-like
136
+ self.check_sort_values_with_freq(idx)
137
+
138
+ def check_sort_values_without_freq(self, idx, expected):
139
+ ordered = idx.sort_values(na_position="first")
140
+ tm.assert_index_equal(ordered, expected)
141
+ check_freq_nonmonotonic(ordered, idx)
142
+
143
+ if not idx.isna().any():
144
+ ordered = idx.sort_values()
145
+ tm.assert_index_equal(ordered, expected)
146
+ check_freq_nonmonotonic(ordered, idx)
147
+
148
+ ordered = idx.sort_values(ascending=False)
149
+ tm.assert_index_equal(ordered, expected[::-1])
150
+ check_freq_nonmonotonic(ordered, idx)
151
+
152
+ ordered, indexer = idx.sort_values(return_indexer=True, na_position="first")
153
+ tm.assert_index_equal(ordered, expected)
154
+
155
+ exp = np.array([0, 4, 3, 1, 2], dtype=np.intp)
156
+ tm.assert_numpy_array_equal(indexer, exp)
157
+ check_freq_nonmonotonic(ordered, idx)
158
+
159
+ if not idx.isna().any():
160
+ ordered, indexer = idx.sort_values(return_indexer=True)
161
+ tm.assert_index_equal(ordered, expected)
162
+
163
+ exp = np.array([0, 4, 3, 1, 2], dtype=np.intp)
164
+ tm.assert_numpy_array_equal(indexer, exp)
165
+ check_freq_nonmonotonic(ordered, idx)
166
+
167
+ ordered, indexer = idx.sort_values(return_indexer=True, ascending=False)
168
+ tm.assert_index_equal(ordered, expected[::-1])
169
+
170
+ exp = np.array([2, 1, 3, 0, 4], dtype=np.intp)
171
+ tm.assert_numpy_array_equal(indexer, exp)
172
+ check_freq_nonmonotonic(ordered, idx)
173
+
174
+ def test_sort_values_without_freq_timedeltaindex(self):
175
+ # GH#10295
176
+
177
+ idx = TimedeltaIndex(
178
+ ["1 hour", "3 hour", "5 hour", "2 hour ", "1 hour"], name="idx1"
179
+ )
180
+ expected = TimedeltaIndex(
181
+ ["1 hour", "1 hour", "2 hour", "3 hour", "5 hour"], name="idx1"
182
+ )
183
+ self.check_sort_values_without_freq(idx, expected)
184
+
185
+ @pytest.mark.parametrize(
186
+ "index_dates,expected_dates",
187
+ [
188
+ (
189
+ ["2011-01-01", "2011-01-03", "2011-01-05", "2011-01-02", "2011-01-01"],
190
+ ["2011-01-01", "2011-01-01", "2011-01-02", "2011-01-03", "2011-01-05"],
191
+ ),
192
+ (
193
+ ["2011-01-01", "2011-01-03", "2011-01-05", "2011-01-02", "2011-01-01"],
194
+ ["2011-01-01", "2011-01-01", "2011-01-02", "2011-01-03", "2011-01-05"],
195
+ ),
196
+ (
197
+ [NaT, "2011-01-03", "2011-01-05", "2011-01-02", NaT],
198
+ [NaT, NaT, "2011-01-02", "2011-01-03", "2011-01-05"],
199
+ ),
200
+ ],
201
+ )
202
+ def test_sort_values_without_freq_datetimeindex(
203
+ self, index_dates, expected_dates, tz_naive_fixture
204
+ ):
205
+ tz = tz_naive_fixture
206
+
207
+ # without freq
208
+ idx = DatetimeIndex(index_dates, tz=tz, name="idx")
209
+ expected = DatetimeIndex(expected_dates, tz=tz, name="idx")
210
+
211
+ self.check_sort_values_without_freq(idx, expected)
212
+
213
+ @pytest.mark.parametrize(
214
+ "idx,expected",
215
+ [
216
+ (
217
+ PeriodIndex(
218
+ [
219
+ "2011-01-01",
220
+ "2011-01-03",
221
+ "2011-01-05",
222
+ "2011-01-02",
223
+ "2011-01-01",
224
+ ],
225
+ freq="D",
226
+ name="idx1",
227
+ ),
228
+ PeriodIndex(
229
+ [
230
+ "2011-01-01",
231
+ "2011-01-01",
232
+ "2011-01-02",
233
+ "2011-01-03",
234
+ "2011-01-05",
235
+ ],
236
+ freq="D",
237
+ name="idx1",
238
+ ),
239
+ ),
240
+ (
241
+ PeriodIndex(
242
+ [
243
+ "2011-01-01",
244
+ "2011-01-03",
245
+ "2011-01-05",
246
+ "2011-01-02",
247
+ "2011-01-01",
248
+ ],
249
+ freq="D",
250
+ name="idx2",
251
+ ),
252
+ PeriodIndex(
253
+ [
254
+ "2011-01-01",
255
+ "2011-01-01",
256
+ "2011-01-02",
257
+ "2011-01-03",
258
+ "2011-01-05",
259
+ ],
260
+ freq="D",
261
+ name="idx2",
262
+ ),
263
+ ),
264
+ (
265
+ PeriodIndex(
266
+ [NaT, "2011-01-03", "2011-01-05", "2011-01-02", NaT],
267
+ freq="D",
268
+ name="idx3",
269
+ ),
270
+ PeriodIndex(
271
+ [NaT, NaT, "2011-01-02", "2011-01-03", "2011-01-05"],
272
+ freq="D",
273
+ name="idx3",
274
+ ),
275
+ ),
276
+ (
277
+ PeriodIndex(
278
+ ["2011", "2013", "2015", "2012", "2011"], name="pidx", freq="Y"
279
+ ),
280
+ PeriodIndex(
281
+ ["2011", "2011", "2012", "2013", "2015"], name="pidx", freq="Y"
282
+ ),
283
+ ),
284
+ (
285
+ # For compatibility check
286
+ Index([2011, 2013, 2015, 2012, 2011], name="idx"),
287
+ Index([2011, 2011, 2012, 2013, 2015], name="idx"),
288
+ ),
289
+ ],
290
+ )
291
+ def test_sort_values_without_freq_periodindex(self, idx, expected):
292
+ # here without_freq means not generateable by period_range
293
+ self.check_sort_values_without_freq(idx, expected)
294
+
295
+ def test_sort_values_without_freq_periodindex_nat(self):
296
+ # doesn't quite fit into check_sort_values_without_freq
297
+ idx = PeriodIndex(["2011", "2013", "NaT", "2011"], name="pidx", freq="D")
298
+ expected = PeriodIndex(["NaT", "2011", "2011", "2013"], name="pidx", freq="D")
299
+
300
+ ordered = idx.sort_values(na_position="first")
301
+ tm.assert_index_equal(ordered, expected)
302
+ check_freq_nonmonotonic(ordered, idx)
303
+
304
+ ordered = idx.sort_values(ascending=False)
305
+ tm.assert_index_equal(ordered, expected[::-1])
306
+ check_freq_nonmonotonic(ordered, idx)
307
+
308
+
309
+ def test_order_stability_compat():
310
+ # GH#35922. sort_values is stable both for normal and datetime-like Index
311
+ pidx = PeriodIndex(["2011", "2013", "2015", "2012", "2011"], name="pidx", freq="Y")
312
+ iidx = Index([2011, 2013, 2015, 2012, 2011], name="idx")
313
+ ordered1, indexer1 = pidx.sort_values(return_indexer=True, ascending=False)
314
+ ordered2, indexer2 = iidx.sort_values(return_indexer=True, ascending=False)
315
+ tm.assert_numpy_array_equal(indexer1, indexer2)
lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_value_counts.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from pandas import (
4
+ DatetimeIndex,
5
+ NaT,
6
+ PeriodIndex,
7
+ Series,
8
+ TimedeltaIndex,
9
+ date_range,
10
+ period_range,
11
+ timedelta_range,
12
+ )
13
+ import pandas._testing as tm
14
+
15
+
16
+ class TestValueCounts:
17
+ # GH#7735
18
+
19
+ def test_value_counts_unique_datetimeindex(self, tz_naive_fixture):
20
+ tz = tz_naive_fixture
21
+ orig = date_range("2011-01-01 09:00", freq="h", periods=10, tz=tz)
22
+ self._check_value_counts_with_repeats(orig)
23
+
24
+ def test_value_counts_unique_timedeltaindex(self):
25
+ orig = timedelta_range("1 days 09:00:00", freq="h", periods=10)
26
+ self._check_value_counts_with_repeats(orig)
27
+
28
+ def test_value_counts_unique_periodindex(self):
29
+ orig = period_range("2011-01-01 09:00", freq="h", periods=10)
30
+ self._check_value_counts_with_repeats(orig)
31
+
32
+ def _check_value_counts_with_repeats(self, orig):
33
+ # create repeated values, 'n'th element is repeated by n+1 times
34
+ idx = type(orig)(
35
+ np.repeat(orig._values, range(1, len(orig) + 1)), dtype=orig.dtype
36
+ )
37
+
38
+ exp_idx = orig[::-1]
39
+ if not isinstance(exp_idx, PeriodIndex):
40
+ exp_idx = exp_idx._with_freq(None)
41
+ expected = Series(range(10, 0, -1), index=exp_idx, dtype="int64", name="count")
42
+
43
+ for obj in [idx, Series(idx)]:
44
+ tm.assert_series_equal(obj.value_counts(), expected)
45
+
46
+ tm.assert_index_equal(idx.unique(), orig)
47
+
48
+ def test_value_counts_unique_datetimeindex2(self, tz_naive_fixture):
49
+ tz = tz_naive_fixture
50
+ idx = DatetimeIndex(
51
+ [
52
+ "2013-01-01 09:00",
53
+ "2013-01-01 09:00",
54
+ "2013-01-01 09:00",
55
+ "2013-01-01 08:00",
56
+ "2013-01-01 08:00",
57
+ NaT,
58
+ ],
59
+ tz=tz,
60
+ )
61
+ self._check_value_counts_dropna(idx)
62
+
63
+ def test_value_counts_unique_timedeltaindex2(self):
64
+ idx = TimedeltaIndex(
65
+ [
66
+ "1 days 09:00:00",
67
+ "1 days 09:00:00",
68
+ "1 days 09:00:00",
69
+ "1 days 08:00:00",
70
+ "1 days 08:00:00",
71
+ NaT,
72
+ ]
73
+ )
74
+ self._check_value_counts_dropna(idx)
75
+
76
+ def test_value_counts_unique_periodindex2(self):
77
+ idx = PeriodIndex(
78
+ [
79
+ "2013-01-01 09:00",
80
+ "2013-01-01 09:00",
81
+ "2013-01-01 09:00",
82
+ "2013-01-01 08:00",
83
+ "2013-01-01 08:00",
84
+ NaT,
85
+ ],
86
+ freq="h",
87
+ )
88
+ self._check_value_counts_dropna(idx)
89
+
90
+ def _check_value_counts_dropna(self, idx):
91
+ exp_idx = idx[[2, 3]]
92
+ expected = Series([3, 2], index=exp_idx, name="count")
93
+
94
+ for obj in [idx, Series(idx)]:
95
+ tm.assert_series_equal(obj.value_counts(), expected)
96
+
97
+ exp_idx = idx[[2, 3, -1]]
98
+ expected = Series([3, 2, 1], index=exp_idx, name="count")
99
+
100
+ for obj in [idx, Series(idx)]:
101
+ tm.assert_series_equal(obj.value_counts(dropna=False), expected)
102
+
103
+ tm.assert_index_equal(idx.unique(), exp_idx)
lib/python3.10/site-packages/pandas/tests/indexes/datetimes/methods/test_asof.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import timedelta
2
+
3
+ from pandas import (
4
+ Index,
5
+ Timestamp,
6
+ date_range,
7
+ isna,
8
+ )
9
+
10
+
11
+ class TestAsOf:
12
+ def test_asof_partial(self):
13
+ index = date_range("2010-01-01", periods=2, freq="ME")
14
+ expected = Timestamp("2010-02-28")
15
+ result = index.asof("2010-02")
16
+ assert result == expected
17
+ assert not isinstance(result, Index)
18
+
19
+ def test_asof(self):
20
+ index = date_range("2020-01-01", periods=10)
21
+
22
+ dt = index[0]
23
+ assert index.asof(dt) == dt
24
+ assert isna(index.asof(dt - timedelta(1)))
25
+
26
+ dt = index[-1]
27
+ assert index.asof(dt + timedelta(1)) == dt
28
+
29
+ dt = index[0].to_pydatetime()
30
+ assert isinstance(index.asof(dt), Timestamp)
lib/python3.10/site-packages/pandas/tests/indexes/datetimes/methods/test_astype.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+
3
+ import dateutil
4
+ import numpy as np
5
+ import pytest
6
+ import pytz
7
+
8
+ import pandas as pd
9
+ from pandas import (
10
+ DatetimeIndex,
11
+ Index,
12
+ NaT,
13
+ PeriodIndex,
14
+ Timestamp,
15
+ date_range,
16
+ )
17
+ import pandas._testing as tm
18
+
19
+
20
+ class TestDatetimeIndex:
21
+ @pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"])
22
+ def test_dti_astype_asobject_around_dst_transition(self, tzstr):
23
+ # GH#1345
24
+
25
+ # dates around a dst transition
26
+ rng = date_range("2/13/2010", "5/6/2010", tz=tzstr)
27
+
28
+ objs = rng.astype(object)
29
+ for i, x in enumerate(objs):
30
+ exval = rng[i]
31
+ assert x == exval
32
+ assert x.tzinfo == exval.tzinfo
33
+
34
+ objs = rng.astype(object)
35
+ for i, x in enumerate(objs):
36
+ exval = rng[i]
37
+ assert x == exval
38
+ assert x.tzinfo == exval.tzinfo
39
+
40
+ def test_astype(self):
41
+ # GH 13149, GH 13209
42
+ idx = DatetimeIndex(
43
+ ["2016-05-16", "NaT", NaT, np.nan], dtype="M8[ns]", name="idx"
44
+ )
45
+
46
+ result = idx.astype(object)
47
+ expected = Index(
48
+ [Timestamp("2016-05-16")] + [NaT] * 3, dtype=object, name="idx"
49
+ )
50
+ tm.assert_index_equal(result, expected)
51
+
52
+ result = idx.astype(np.int64)
53
+ expected = Index(
54
+ [1463356800000000000] + [-9223372036854775808] * 3,
55
+ dtype=np.int64,
56
+ name="idx",
57
+ )
58
+ tm.assert_index_equal(result, expected)
59
+
60
+ def test_astype2(self):
61
+ rng = date_range("1/1/2000", periods=10, name="idx")
62
+ result = rng.astype("i8")
63
+ tm.assert_index_equal(result, Index(rng.asi8, name="idx"))
64
+ tm.assert_numpy_array_equal(result.values, rng.asi8)
65
+
66
+ def test_astype_uint(self):
67
+ arr = date_range("2000", periods=2, name="idx")
68
+
69
+ with pytest.raises(TypeError, match=r"Do obj.astype\('int64'\)"):
70
+ arr.astype("uint64")
71
+ with pytest.raises(TypeError, match=r"Do obj.astype\('int64'\)"):
72
+ arr.astype("uint32")
73
+
74
+ def test_astype_with_tz(self):
75
+ # with tz
76
+ rng = date_range("1/1/2000", periods=10, tz="US/Eastern")
77
+ msg = "Cannot use .astype to convert from timezone-aware"
78
+ with pytest.raises(TypeError, match=msg):
79
+ # deprecated
80
+ rng.astype("datetime64[ns]")
81
+ with pytest.raises(TypeError, match=msg):
82
+ # check DatetimeArray while we're here deprecated
83
+ rng._data.astype("datetime64[ns]")
84
+
85
+ def test_astype_tzaware_to_tzaware(self):
86
+ # GH 18951: tz-aware to tz-aware
87
+ idx = date_range("20170101", periods=4, tz="US/Pacific")
88
+ result = idx.astype("datetime64[ns, US/Eastern]")
89
+ expected = date_range("20170101 03:00:00", periods=4, tz="US/Eastern")
90
+ tm.assert_index_equal(result, expected)
91
+ assert result.freq == expected.freq
92
+
93
+ def test_astype_tznaive_to_tzaware(self):
94
+ # GH 18951: tz-naive to tz-aware
95
+ idx = date_range("20170101", periods=4)
96
+ idx = idx._with_freq(None) # tz_localize does not preserve freq
97
+ msg = "Cannot use .astype to convert from timezone-naive"
98
+ with pytest.raises(TypeError, match=msg):
99
+ # dt64->dt64tz deprecated
100
+ idx.astype("datetime64[ns, US/Eastern]")
101
+ with pytest.raises(TypeError, match=msg):
102
+ # dt64->dt64tz deprecated
103
+ idx._data.astype("datetime64[ns, US/Eastern]")
104
+
105
+ def test_astype_str_nat(self):
106
+ # GH 13149, GH 13209
107
+ # verify that we are returning NaT as a string (and not unicode)
108
+
109
+ idx = DatetimeIndex(["2016-05-16", "NaT", NaT, np.nan])
110
+ result = idx.astype(str)
111
+ expected = Index(["2016-05-16", "NaT", "NaT", "NaT"], dtype=object)
112
+ tm.assert_index_equal(result, expected)
113
+
114
+ def test_astype_str(self):
115
+ # test astype string - #10442
116
+ dti = date_range("2012-01-01", periods=4, name="test_name")
117
+ result = dti.astype(str)
118
+ expected = Index(
119
+ ["2012-01-01", "2012-01-02", "2012-01-03", "2012-01-04"],
120
+ name="test_name",
121
+ dtype=object,
122
+ )
123
+ tm.assert_index_equal(result, expected)
124
+
125
+ def test_astype_str_tz_and_name(self):
126
+ # test astype string with tz and name
127
+ dti = date_range("2012-01-01", periods=3, name="test_name", tz="US/Eastern")
128
+ result = dti.astype(str)
129
+ expected = Index(
130
+ [
131
+ "2012-01-01 00:00:00-05:00",
132
+ "2012-01-02 00:00:00-05:00",
133
+ "2012-01-03 00:00:00-05:00",
134
+ ],
135
+ name="test_name",
136
+ dtype=object,
137
+ )
138
+ tm.assert_index_equal(result, expected)
139
+
140
+ def test_astype_str_freq_and_name(self):
141
+ # test astype string with freqH and name
142
+ dti = date_range("1/1/2011", periods=3, freq="h", name="test_name")
143
+ result = dti.astype(str)
144
+ expected = Index(
145
+ ["2011-01-01 00:00:00", "2011-01-01 01:00:00", "2011-01-01 02:00:00"],
146
+ name="test_name",
147
+ dtype=object,
148
+ )
149
+ tm.assert_index_equal(result, expected)
150
+
151
+ def test_astype_str_freq_and_tz(self):
152
+ # test astype string with freqH and timezone
153
+ dti = date_range(
154
+ "3/6/2012 00:00", periods=2, freq="h", tz="Europe/London", name="test_name"
155
+ )
156
+ result = dti.astype(str)
157
+ expected = Index(
158
+ ["2012-03-06 00:00:00+00:00", "2012-03-06 01:00:00+00:00"],
159
+ dtype=object,
160
+ name="test_name",
161
+ )
162
+ tm.assert_index_equal(result, expected)
163
+
164
+ def test_astype_datetime64(self):
165
+ # GH 13149, GH 13209
166
+ idx = DatetimeIndex(
167
+ ["2016-05-16", "NaT", NaT, np.nan], dtype="M8[ns]", name="idx"
168
+ )
169
+
170
+ result = idx.astype("datetime64[ns]")
171
+ tm.assert_index_equal(result, idx)
172
+ assert result is not idx
173
+
174
+ result = idx.astype("datetime64[ns]", copy=False)
175
+ tm.assert_index_equal(result, idx)
176
+ assert result is idx
177
+
178
+ idx_tz = DatetimeIndex(["2016-05-16", "NaT", NaT, np.nan], tz="EST", name="idx")
179
+ msg = "Cannot use .astype to convert from timezone-aware"
180
+ with pytest.raises(TypeError, match=msg):
181
+ # dt64tz->dt64 deprecated
182
+ result = idx_tz.astype("datetime64[ns]")
183
+
184
+ def test_astype_object(self):
185
+ rng = date_range("1/1/2000", periods=20)
186
+
187
+ casted = rng.astype("O")
188
+ exp_values = list(rng)
189
+
190
+ tm.assert_index_equal(casted, Index(exp_values, dtype=np.object_))
191
+ assert casted.tolist() == exp_values
192
+
193
+ @pytest.mark.parametrize("tz", [None, "Asia/Tokyo"])
194
+ def test_astype_object_tz(self, tz):
195
+ idx = date_range(start="2013-01-01", periods=4, freq="ME", name="idx", tz=tz)
196
+ expected_list = [
197
+ Timestamp("2013-01-31", tz=tz),
198
+ Timestamp("2013-02-28", tz=tz),
199
+ Timestamp("2013-03-31", tz=tz),
200
+ Timestamp("2013-04-30", tz=tz),
201
+ ]
202
+ expected = Index(expected_list, dtype=object, name="idx")
203
+ result = idx.astype(object)
204
+ tm.assert_index_equal(result, expected)
205
+ assert idx.tolist() == expected_list
206
+
207
+ def test_astype_object_with_nat(self):
208
+ idx = DatetimeIndex(
209
+ [datetime(2013, 1, 1), datetime(2013, 1, 2), NaT, datetime(2013, 1, 4)],
210
+ name="idx",
211
+ )
212
+ expected_list = [
213
+ Timestamp("2013-01-01"),
214
+ Timestamp("2013-01-02"),
215
+ NaT,
216
+ Timestamp("2013-01-04"),
217
+ ]
218
+ expected = Index(expected_list, dtype=object, name="idx")
219
+ result = idx.astype(object)
220
+ tm.assert_index_equal(result, expected)
221
+ assert idx.tolist() == expected_list
222
+
223
+ @pytest.mark.parametrize(
224
+ "dtype",
225
+ [float, "timedelta64", "timedelta64[ns]", "datetime64", "datetime64[D]"],
226
+ )
227
+ def test_astype_raises(self, dtype):
228
+ # GH 13149, GH 13209
229
+ idx = DatetimeIndex(["2016-05-16", "NaT", NaT, np.nan])
230
+ msg = "Cannot cast DatetimeIndex to dtype"
231
+ if dtype == "datetime64":
232
+ msg = "Casting to unit-less dtype 'datetime64' is not supported"
233
+ with pytest.raises(TypeError, match=msg):
234
+ idx.astype(dtype)
235
+
236
+ def test_index_convert_to_datetime_array(self):
237
+ def _check_rng(rng):
238
+ converted = rng.to_pydatetime()
239
+ assert isinstance(converted, np.ndarray)
240
+ for x, stamp in zip(converted, rng):
241
+ assert isinstance(x, datetime)
242
+ assert x == stamp.to_pydatetime()
243
+ assert x.tzinfo == stamp.tzinfo
244
+
245
+ rng = date_range("20090415", "20090519")
246
+ rng_eastern = date_range("20090415", "20090519", tz="US/Eastern")
247
+ rng_utc = date_range("20090415", "20090519", tz="utc")
248
+
249
+ _check_rng(rng)
250
+ _check_rng(rng_eastern)
251
+ _check_rng(rng_utc)
252
+
253
+ def test_index_convert_to_datetime_array_explicit_pytz(self):
254
+ def _check_rng(rng):
255
+ converted = rng.to_pydatetime()
256
+ assert isinstance(converted, np.ndarray)
257
+ for x, stamp in zip(converted, rng):
258
+ assert isinstance(x, datetime)
259
+ assert x == stamp.to_pydatetime()
260
+ assert x.tzinfo == stamp.tzinfo
261
+
262
+ rng = date_range("20090415", "20090519")
263
+ rng_eastern = date_range("20090415", "20090519", tz=pytz.timezone("US/Eastern"))
264
+ rng_utc = date_range("20090415", "20090519", tz=pytz.utc)
265
+
266
+ _check_rng(rng)
267
+ _check_rng(rng_eastern)
268
+ _check_rng(rng_utc)
269
+
270
+ def test_index_convert_to_datetime_array_dateutil(self):
271
+ def _check_rng(rng):
272
+ converted = rng.to_pydatetime()
273
+ assert isinstance(converted, np.ndarray)
274
+ for x, stamp in zip(converted, rng):
275
+ assert isinstance(x, datetime)
276
+ assert x == stamp.to_pydatetime()
277
+ assert x.tzinfo == stamp.tzinfo
278
+
279
+ rng = date_range("20090415", "20090519")
280
+ rng_eastern = date_range("20090415", "20090519", tz="dateutil/US/Eastern")
281
+ rng_utc = date_range("20090415", "20090519", tz=dateutil.tz.tzutc())
282
+
283
+ _check_rng(rng)
284
+ _check_rng(rng_eastern)
285
+ _check_rng(rng_utc)
286
+
287
+ @pytest.mark.parametrize(
288
+ "tz, dtype",
289
+ [["US/Pacific", "datetime64[ns, US/Pacific]"], [None, "datetime64[ns]"]],
290
+ )
291
+ def test_integer_index_astype_datetime(self, tz, dtype):
292
+ # GH 20997, 20964, 24559
293
+ val = [Timestamp("2018-01-01", tz=tz).as_unit("ns")._value]
294
+ result = Index(val, name="idx").astype(dtype)
295
+ expected = DatetimeIndex(["2018-01-01"], tz=tz, name="idx").as_unit("ns")
296
+ tm.assert_index_equal(result, expected)
297
+
298
+ def test_dti_astype_period(self):
299
+ idx = DatetimeIndex([NaT, "2011-01-01", "2011-02-01"], name="idx")
300
+
301
+ res = idx.astype("period[M]")
302
+ exp = PeriodIndex(["NaT", "2011-01", "2011-02"], freq="M", name="idx")
303
+ tm.assert_index_equal(res, exp)
304
+
305
+ res = idx.astype("period[3M]")
306
+ exp = PeriodIndex(["NaT", "2011-01", "2011-02"], freq="3M", name="idx")
307
+ tm.assert_index_equal(res, exp)
308
+
309
+
310
+ class TestAstype:
311
+ @pytest.mark.parametrize("tz", [None, "US/Central"])
312
+ def test_astype_category(self, tz):
313
+ obj = date_range("2000", periods=2, tz=tz, name="idx")
314
+ result = obj.astype("category")
315
+ dti = DatetimeIndex(["2000-01-01", "2000-01-02"], tz=tz).as_unit("ns")
316
+ expected = pd.CategoricalIndex(
317
+ dti,
318
+ name="idx",
319
+ )
320
+ tm.assert_index_equal(result, expected)
321
+
322
+ result = obj._data.astype("category")
323
+ expected = expected.values
324
+ tm.assert_categorical_equal(result, expected)
325
+
326
+ @pytest.mark.parametrize("tz", [None, "US/Central"])
327
+ def test_astype_array_fallback(self, tz):
328
+ obj = date_range("2000", periods=2, tz=tz, name="idx")
329
+ result = obj.astype(bool)
330
+ expected = Index(np.array([True, True]), name="idx")
331
+ tm.assert_index_equal(result, expected)
332
+
333
+ result = obj._data.astype(bool)
334
+ expected = np.array([True, True])
335
+ tm.assert_numpy_array_equal(result, expected)
lib/python3.10/site-packages/pandas/tests/indexes/datetimes/methods/test_factorize.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas import (
5
+ DatetimeIndex,
6
+ Index,
7
+ date_range,
8
+ factorize,
9
+ )
10
+ import pandas._testing as tm
11
+
12
+
13
+ class TestDatetimeIndexFactorize:
14
+ def test_factorize(self):
15
+ idx1 = DatetimeIndex(
16
+ ["2014-01", "2014-01", "2014-02", "2014-02", "2014-03", "2014-03"]
17
+ )
18
+
19
+ exp_arr = np.array([0, 0, 1, 1, 2, 2], dtype=np.intp)
20
+ exp_idx = DatetimeIndex(["2014-01", "2014-02", "2014-03"])
21
+
22
+ arr, idx = idx1.factorize()
23
+ tm.assert_numpy_array_equal(arr, exp_arr)
24
+ tm.assert_index_equal(idx, exp_idx)
25
+ assert idx.freq == exp_idx.freq
26
+
27
+ arr, idx = idx1.factorize(sort=True)
28
+ tm.assert_numpy_array_equal(arr, exp_arr)
29
+ tm.assert_index_equal(idx, exp_idx)
30
+ assert idx.freq == exp_idx.freq
31
+
32
+ # tz must be preserved
33
+ idx1 = idx1.tz_localize("Asia/Tokyo")
34
+ exp_idx = exp_idx.tz_localize("Asia/Tokyo")
35
+
36
+ arr, idx = idx1.factorize()
37
+ tm.assert_numpy_array_equal(arr, exp_arr)
38
+ tm.assert_index_equal(idx, exp_idx)
39
+ assert idx.freq == exp_idx.freq
40
+
41
+ idx2 = DatetimeIndex(
42
+ ["2014-03", "2014-03", "2014-02", "2014-01", "2014-03", "2014-01"]
43
+ )
44
+
45
+ exp_arr = np.array([2, 2, 1, 0, 2, 0], dtype=np.intp)
46
+ exp_idx = DatetimeIndex(["2014-01", "2014-02", "2014-03"])
47
+ arr, idx = idx2.factorize(sort=True)
48
+ tm.assert_numpy_array_equal(arr, exp_arr)
49
+ tm.assert_index_equal(idx, exp_idx)
50
+ assert idx.freq == exp_idx.freq
51
+
52
+ exp_arr = np.array([0, 0, 1, 2, 0, 2], dtype=np.intp)
53
+ exp_idx = DatetimeIndex(["2014-03", "2014-02", "2014-01"])
54
+ arr, idx = idx2.factorize()
55
+ tm.assert_numpy_array_equal(arr, exp_arr)
56
+ tm.assert_index_equal(idx, exp_idx)
57
+ assert idx.freq == exp_idx.freq
58
+
59
+ def test_factorize_preserves_freq(self):
60
+ # GH#38120 freq should be preserved
61
+ idx3 = date_range("2000-01", periods=4, freq="ME", tz="Asia/Tokyo")
62
+ exp_arr = np.array([0, 1, 2, 3], dtype=np.intp)
63
+
64
+ arr, idx = idx3.factorize()
65
+ tm.assert_numpy_array_equal(arr, exp_arr)
66
+ tm.assert_index_equal(idx, idx3)
67
+ assert idx.freq == idx3.freq
68
+
69
+ arr, idx = factorize(idx3)
70
+ tm.assert_numpy_array_equal(arr, exp_arr)
71
+ tm.assert_index_equal(idx, idx3)
72
+ assert idx.freq == idx3.freq
73
+
74
+ def test_factorize_tz(self, tz_naive_fixture, index_or_series):
75
+ tz = tz_naive_fixture
76
+ # GH#13750
77
+ base = date_range("2016-11-05", freq="h", periods=100, tz=tz)
78
+ idx = base.repeat(5)
79
+
80
+ exp_arr = np.arange(100, dtype=np.intp).repeat(5)
81
+
82
+ obj = index_or_series(idx)
83
+
84
+ arr, res = obj.factorize()
85
+ tm.assert_numpy_array_equal(arr, exp_arr)
86
+ expected = base._with_freq(None)
87
+ tm.assert_index_equal(res, expected)
88
+ assert res.freq == expected.freq
89
+
90
+ def test_factorize_dst(self, index_or_series):
91
+ # GH#13750
92
+ idx = date_range("2016-11-06", freq="h", periods=12, tz="US/Eastern")
93
+ obj = index_or_series(idx)
94
+
95
+ arr, res = obj.factorize()
96
+ tm.assert_numpy_array_equal(arr, np.arange(12, dtype=np.intp))
97
+ tm.assert_index_equal(res, idx)
98
+ if index_or_series is Index:
99
+ assert res.freq == idx.freq
100
+
101
+ idx = date_range("2016-06-13", freq="h", periods=12, tz="US/Eastern")
102
+ obj = index_or_series(idx)
103
+
104
+ arr, res = obj.factorize()
105
+ tm.assert_numpy_array_equal(arr, np.arange(12, dtype=np.intp))
106
+ tm.assert_index_equal(res, idx)
107
+ if index_or_series is Index:
108
+ assert res.freq == idx.freq
109
+
110
+ @pytest.mark.parametrize("sort", [True, False])
111
+ def test_factorize_no_freq_non_nano(self, tz_naive_fixture, sort):
112
+ # GH#51978 case that does not go through the fastpath based on
113
+ # non-None freq
114
+ tz = tz_naive_fixture
115
+ idx = date_range("2016-11-06", freq="h", periods=5, tz=tz)[[0, 4, 1, 3, 2]]
116
+ exp_codes, exp_uniques = idx.factorize(sort=sort)
117
+
118
+ res_codes, res_uniques = idx.as_unit("s").factorize(sort=sort)
119
+
120
+ tm.assert_numpy_array_equal(res_codes, exp_codes)
121
+ tm.assert_index_equal(res_uniques, exp_uniques.as_unit("s"))
122
+
123
+ res_codes, res_uniques = idx.as_unit("s").to_series().factorize(sort=sort)
124
+ tm.assert_numpy_array_equal(res_codes, exp_codes)
125
+ tm.assert_index_equal(res_uniques, exp_uniques.as_unit("s"))
lib/python3.10/site-packages/pandas/tests/indexes/datetimes/methods/test_insert.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+
3
+ import numpy as np
4
+ import pytest
5
+ import pytz
6
+
7
+ from pandas import (
8
+ NA,
9
+ DatetimeIndex,
10
+ Index,
11
+ NaT,
12
+ Timestamp,
13
+ date_range,
14
+ )
15
+ import pandas._testing as tm
16
+
17
+
18
+ class TestInsert:
19
+ @pytest.mark.parametrize("null", [None, np.nan, np.datetime64("NaT"), NaT, NA])
20
+ @pytest.mark.parametrize("tz", [None, "UTC", "US/Eastern"])
21
+ def test_insert_nat(self, tz, null):
22
+ # GH#16537, GH#18295 (test missing)
23
+
24
+ idx = DatetimeIndex(["2017-01-01"], tz=tz)
25
+ expected = DatetimeIndex(["NaT", "2017-01-01"], tz=tz)
26
+ if tz is not None and isinstance(null, np.datetime64):
27
+ expected = Index([null, idx[0]], dtype=object)
28
+
29
+ res = idx.insert(0, null)
30
+ tm.assert_index_equal(res, expected)
31
+
32
+ @pytest.mark.parametrize("tz", [None, "UTC", "US/Eastern"])
33
+ def test_insert_invalid_na(self, tz):
34
+ idx = DatetimeIndex(["2017-01-01"], tz=tz)
35
+
36
+ item = np.timedelta64("NaT")
37
+ result = idx.insert(0, item)
38
+ expected = Index([item] + list(idx), dtype=object)
39
+ tm.assert_index_equal(result, expected)
40
+
41
+ def test_insert_empty_preserves_freq(self, tz_naive_fixture):
42
+ # GH#33573
43
+ tz = tz_naive_fixture
44
+ dti = DatetimeIndex([], tz=tz, freq="D")
45
+ item = Timestamp("2017-04-05").tz_localize(tz)
46
+
47
+ result = dti.insert(0, item)
48
+ assert result.freq == dti.freq
49
+
50
+ # But not when we insert an item that doesn't conform to freq
51
+ dti = DatetimeIndex([], tz=tz, freq="W-THU")
52
+ result = dti.insert(0, item)
53
+ assert result.freq is None
54
+
55
+ def test_insert(self, unit):
56
+ idx = DatetimeIndex(
57
+ ["2000-01-04", "2000-01-01", "2000-01-02"], name="idx"
58
+ ).as_unit(unit)
59
+
60
+ result = idx.insert(2, datetime(2000, 1, 5))
61
+ exp = DatetimeIndex(
62
+ ["2000-01-04", "2000-01-01", "2000-01-05", "2000-01-02"], name="idx"
63
+ ).as_unit(unit)
64
+ tm.assert_index_equal(result, exp)
65
+
66
+ # insertion of non-datetime should coerce to object index
67
+ result = idx.insert(1, "inserted")
68
+ expected = Index(
69
+ [
70
+ datetime(2000, 1, 4),
71
+ "inserted",
72
+ datetime(2000, 1, 1),
73
+ datetime(2000, 1, 2),
74
+ ],
75
+ name="idx",
76
+ )
77
+ assert not isinstance(result, DatetimeIndex)
78
+ tm.assert_index_equal(result, expected)
79
+ assert result.name == expected.name
80
+
81
+ def test_insert2(self, unit):
82
+ idx = date_range("1/1/2000", periods=3, freq="ME", name="idx", unit=unit)
83
+
84
+ # preserve freq
85
+ expected_0 = DatetimeIndex(
86
+ ["1999-12-31", "2000-01-31", "2000-02-29", "2000-03-31"],
87
+ name="idx",
88
+ freq="ME",
89
+ ).as_unit(unit)
90
+ expected_3 = DatetimeIndex(
91
+ ["2000-01-31", "2000-02-29", "2000-03-31", "2000-04-30"],
92
+ name="idx",
93
+ freq="ME",
94
+ ).as_unit(unit)
95
+
96
+ # reset freq to None
97
+ expected_1_nofreq = DatetimeIndex(
98
+ ["2000-01-31", "2000-01-31", "2000-02-29", "2000-03-31"],
99
+ name="idx",
100
+ freq=None,
101
+ ).as_unit(unit)
102
+ expected_3_nofreq = DatetimeIndex(
103
+ ["2000-01-31", "2000-02-29", "2000-03-31", "2000-01-02"],
104
+ name="idx",
105
+ freq=None,
106
+ ).as_unit(unit)
107
+
108
+ cases = [
109
+ (0, datetime(1999, 12, 31), expected_0),
110
+ (-3, datetime(1999, 12, 31), expected_0),
111
+ (3, datetime(2000, 4, 30), expected_3),
112
+ (1, datetime(2000, 1, 31), expected_1_nofreq),
113
+ (3, datetime(2000, 1, 2), expected_3_nofreq),
114
+ ]
115
+
116
+ for n, d, expected in cases:
117
+ result = idx.insert(n, d)
118
+ tm.assert_index_equal(result, expected)
119
+ assert result.name == expected.name
120
+ assert result.freq == expected.freq
121
+
122
+ def test_insert3(self, unit):
123
+ idx = date_range("1/1/2000", periods=3, freq="ME", name="idx", unit=unit)
124
+
125
+ # reset freq to None
126
+ result = idx.insert(3, datetime(2000, 1, 2))
127
+ expected = DatetimeIndex(
128
+ ["2000-01-31", "2000-02-29", "2000-03-31", "2000-01-02"],
129
+ name="idx",
130
+ freq=None,
131
+ ).as_unit(unit)
132
+ tm.assert_index_equal(result, expected)
133
+ assert result.name == expected.name
134
+ assert result.freq is None
135
+
136
+ def test_insert4(self, unit):
137
+ for tz in ["US/Pacific", "Asia/Singapore"]:
138
+ idx = date_range(
139
+ "1/1/2000 09:00", periods=6, freq="h", tz=tz, name="idx", unit=unit
140
+ )
141
+ # preserve freq
142
+ expected = date_range(
143
+ "1/1/2000 09:00", periods=7, freq="h", tz=tz, name="idx", unit=unit
144
+ )
145
+ for d in [
146
+ Timestamp("2000-01-01 15:00", tz=tz),
147
+ pytz.timezone(tz).localize(datetime(2000, 1, 1, 15)),
148
+ ]:
149
+ result = idx.insert(6, d)
150
+ tm.assert_index_equal(result, expected)
151
+ assert result.name == expected.name
152
+ assert result.freq == expected.freq
153
+ assert result.tz == expected.tz
154
+
155
+ expected = DatetimeIndex(
156
+ [
157
+ "2000-01-01 09:00",
158
+ "2000-01-01 10:00",
159
+ "2000-01-01 11:00",
160
+ "2000-01-01 12:00",
161
+ "2000-01-01 13:00",
162
+ "2000-01-01 14:00",
163
+ "2000-01-01 10:00",
164
+ ],
165
+ name="idx",
166
+ tz=tz,
167
+ freq=None,
168
+ ).as_unit(unit)
169
+ # reset freq to None
170
+ for d in [
171
+ Timestamp("2000-01-01 10:00", tz=tz),
172
+ pytz.timezone(tz).localize(datetime(2000, 1, 1, 10)),
173
+ ]:
174
+ result = idx.insert(6, d)
175
+ tm.assert_index_equal(result, expected)
176
+ assert result.name == expected.name
177
+ assert result.tz == expected.tz
178
+ assert result.freq is None
179
+
180
+ # TODO: also changes DataFrame.__setitem__ with expansion
181
+ def test_insert_mismatched_tzawareness(self):
182
+ # see GH#7299
183
+ idx = date_range("1/1/2000", periods=3, freq="D", tz="Asia/Tokyo", name="idx")
184
+
185
+ # mismatched tz-awareness
186
+ item = Timestamp("2000-01-04")
187
+ result = idx.insert(3, item)
188
+ expected = Index(
189
+ list(idx[:3]) + [item] + list(idx[3:]), dtype=object, name="idx"
190
+ )
191
+ tm.assert_index_equal(result, expected)
192
+
193
+ # mismatched tz-awareness
194
+ item = datetime(2000, 1, 4)
195
+ result = idx.insert(3, item)
196
+ expected = Index(
197
+ list(idx[:3]) + [item] + list(idx[3:]), dtype=object, name="idx"
198
+ )
199
+ tm.assert_index_equal(result, expected)
200
+
201
+ # TODO: also changes DataFrame.__setitem__ with expansion
202
+ def test_insert_mismatched_tz(self):
203
+ # see GH#7299
204
+ # pre-2.0 with mismatched tzs we would cast to object
205
+ idx = date_range("1/1/2000", periods=3, freq="D", tz="Asia/Tokyo", name="idx")
206
+
207
+ # mismatched tz -> cast to object (could reasonably cast to same tz or UTC)
208
+ item = Timestamp("2000-01-04", tz="US/Eastern")
209
+ result = idx.insert(3, item)
210
+ expected = Index(
211
+ list(idx[:3]) + [item.tz_convert(idx.tz)] + list(idx[3:]),
212
+ name="idx",
213
+ )
214
+ assert expected.dtype == idx.dtype
215
+ tm.assert_index_equal(result, expected)
216
+
217
+ item = datetime(2000, 1, 4, tzinfo=pytz.timezone("US/Eastern"))
218
+ result = idx.insert(3, item)
219
+ expected = Index(
220
+ list(idx[:3]) + [item.astimezone(idx.tzinfo)] + list(idx[3:]),
221
+ name="idx",
222
+ )
223
+ assert expected.dtype == idx.dtype
224
+ tm.assert_index_equal(result, expected)
225
+
226
+ @pytest.mark.parametrize(
227
+ "item", [0, np.int64(0), np.float64(0), np.array(0), np.timedelta64(456)]
228
+ )
229
+ def test_insert_mismatched_types_raises(self, tz_aware_fixture, item):
230
+ # GH#33703 dont cast these to dt64
231
+ tz = tz_aware_fixture
232
+ dti = date_range("2019-11-04", periods=9, freq="-1D", name=9, tz=tz)
233
+
234
+ result = dti.insert(1, item)
235
+
236
+ if isinstance(item, np.ndarray):
237
+ assert item.item() == 0
238
+ expected = Index([dti[0], 0] + list(dti[1:]), dtype=object, name=9)
239
+ else:
240
+ expected = Index([dti[0], item] + list(dti[1:]), dtype=object, name=9)
241
+
242
+ tm.assert_index_equal(result, expected)
243
+
244
+ def test_insert_castable_str(self, tz_aware_fixture):
245
+ # GH#33703
246
+ tz = tz_aware_fixture
247
+ dti = date_range("2019-11-04", periods=3, freq="-1D", name=9, tz=tz)
248
+
249
+ value = "2019-11-05"
250
+ result = dti.insert(0, value)
251
+
252
+ ts = Timestamp(value).tz_localize(tz)
253
+ expected = DatetimeIndex([ts] + list(dti), dtype=dti.dtype, name=9)
254
+ tm.assert_index_equal(result, expected)
255
+
256
+ def test_insert_non_castable_str(self, tz_aware_fixture):
257
+ # GH#33703
258
+ tz = tz_aware_fixture
259
+ dti = date_range("2019-11-04", periods=3, freq="-1D", name=9, tz=tz)
260
+
261
+ value = "foo"
262
+ result = dti.insert(0, value)
263
+
264
+ expected = Index(["foo"] + list(dti), dtype=object, name=9)
265
+ tm.assert_index_equal(result, expected)
lib/python3.10/site-packages/pandas/tests/indexes/datetimes/methods/test_map.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from pandas import (
4
+ DatetimeIndex,
5
+ Index,
6
+ MultiIndex,
7
+ Period,
8
+ date_range,
9
+ )
10
+ import pandas._testing as tm
11
+
12
+
13
+ class TestMap:
14
+ def test_map(self):
15
+ rng = date_range("1/1/2000", periods=10)
16
+
17
+ f = lambda x: x.strftime("%Y%m%d")
18
+ result = rng.map(f)
19
+ exp = Index([f(x) for x in rng])
20
+ tm.assert_index_equal(result, exp)
21
+
22
+ def test_map_fallthrough(self, capsys):
23
+ # GH#22067, check we don't get warnings about silently ignored errors
24
+ dti = date_range("2017-01-01", "2018-01-01", freq="B")
25
+
26
+ dti.map(lambda x: Period(year=x.year, month=x.month, freq="M"))
27
+
28
+ captured = capsys.readouterr()
29
+ assert captured.err == ""
30
+
31
+ def test_map_bug_1677(self):
32
+ index = DatetimeIndex(["2012-04-25 09:30:00.393000"])
33
+ f = index.asof
34
+
35
+ result = index.map(f)
36
+ expected = Index([f(index[0])])
37
+ tm.assert_index_equal(result, expected)
38
+
39
+ @pytest.mark.parametrize("name", [None, "name"])
40
+ def test_index_map(self, name):
41
+ # see GH#20990
42
+ count = 6
43
+ index = date_range("2018-01-01", periods=count, freq="ME", name=name).map(
44
+ lambda x: (x.year, x.month)
45
+ )
46
+ exp_index = MultiIndex.from_product(((2018,), range(1, 7)), names=[name, name])
47
+ tm.assert_index_equal(index, exp_index)
lib/python3.10/site-packages/pandas/tests/indexes/datetimes/methods/test_normalize.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dateutil.tz import tzlocal
2
+ import numpy as np
3
+ import pytest
4
+
5
+ import pandas.util._test_decorators as td
6
+
7
+ from pandas import (
8
+ DatetimeIndex,
9
+ NaT,
10
+ Timestamp,
11
+ date_range,
12
+ )
13
+ import pandas._testing as tm
14
+
15
+
16
+ class TestNormalize:
17
+ def test_normalize(self):
18
+ rng = date_range("1/1/2000 9:30", periods=10, freq="D")
19
+
20
+ result = rng.normalize()
21
+ expected = date_range("1/1/2000", periods=10, freq="D")
22
+ tm.assert_index_equal(result, expected)
23
+
24
+ arr_ns = np.array([1380585623454345752, 1380585612343234312]).astype(
25
+ "datetime64[ns]"
26
+ )
27
+ rng_ns = DatetimeIndex(arr_ns)
28
+ rng_ns_normalized = rng_ns.normalize()
29
+
30
+ arr_ns = np.array([1380585600000000000, 1380585600000000000]).astype(
31
+ "datetime64[ns]"
32
+ )
33
+ expected = DatetimeIndex(arr_ns)
34
+ tm.assert_index_equal(rng_ns_normalized, expected)
35
+
36
+ assert result.is_normalized
37
+ assert not rng.is_normalized
38
+
39
+ def test_normalize_nat(self):
40
+ dti = DatetimeIndex([NaT, Timestamp("2018-01-01 01:00:00")])
41
+ result = dti.normalize()
42
+ expected = DatetimeIndex([NaT, Timestamp("2018-01-01")])
43
+ tm.assert_index_equal(result, expected)
44
+
45
+ def test_normalize_tz(self):
46
+ rng = date_range("1/1/2000 9:30", periods=10, freq="D", tz="US/Eastern")
47
+
48
+ result = rng.normalize() # does not preserve freq
49
+ expected = date_range("1/1/2000", periods=10, freq="D", tz="US/Eastern")
50
+ tm.assert_index_equal(result, expected._with_freq(None))
51
+
52
+ assert result.is_normalized
53
+ assert not rng.is_normalized
54
+
55
+ rng = date_range("1/1/2000 9:30", periods=10, freq="D", tz="UTC")
56
+
57
+ result = rng.normalize()
58
+ expected = date_range("1/1/2000", periods=10, freq="D", tz="UTC")
59
+ tm.assert_index_equal(result, expected)
60
+
61
+ assert result.is_normalized
62
+ assert not rng.is_normalized
63
+
64
+ rng = date_range("1/1/2000 9:30", periods=10, freq="D", tz=tzlocal())
65
+ result = rng.normalize() # does not preserve freq
66
+ expected = date_range("1/1/2000", periods=10, freq="D", tz=tzlocal())
67
+ tm.assert_index_equal(result, expected._with_freq(None))
68
+
69
+ assert result.is_normalized
70
+ assert not rng.is_normalized
71
+
72
+ @td.skip_if_windows
73
+ @pytest.mark.parametrize(
74
+ "timezone",
75
+ [
76
+ "US/Pacific",
77
+ "US/Eastern",
78
+ "UTC",
79
+ "Asia/Kolkata",
80
+ "Asia/Shanghai",
81
+ "Australia/Canberra",
82
+ ],
83
+ )
84
+ def test_normalize_tz_local(self, timezone):
85
+ # GH#13459
86
+ with tm.set_timezone(timezone):
87
+ rng = date_range("1/1/2000 9:30", periods=10, freq="D", tz=tzlocal())
88
+
89
+ result = rng.normalize()
90
+ expected = date_range("1/1/2000", periods=10, freq="D", tz=tzlocal())
91
+ expected = expected._with_freq(None)
92
+ tm.assert_index_equal(result, expected)
93
+
94
+ assert result.is_normalized
95
+ assert not rng.is_normalized
lib/python3.10/site-packages/pandas/tests/indexes/datetimes/methods/test_resolution.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dateutil.tz import tzlocal
2
+ import pytest
3
+
4
+ from pandas.compat import IS64
5
+
6
+ from pandas import date_range
7
+
8
+
9
+ @pytest.mark.parametrize(
10
+ "freq,expected",
11
+ [
12
+ ("YE", "day"),
13
+ ("QE", "day"),
14
+ ("ME", "day"),
15
+ ("D", "day"),
16
+ ("h", "hour"),
17
+ ("min", "minute"),
18
+ ("s", "second"),
19
+ ("ms", "millisecond"),
20
+ ("us", "microsecond"),
21
+ ],
22
+ )
23
+ def test_dti_resolution(request, tz_naive_fixture, freq, expected):
24
+ tz = tz_naive_fixture
25
+ if freq == "YE" and not IS64 and isinstance(tz, tzlocal):
26
+ request.applymarker(
27
+ pytest.mark.xfail(reason="OverflowError inside tzlocal past 2038")
28
+ )
29
+
30
+ idx = date_range(start="2013-04-01", periods=30, freq=freq, tz=tz)
31
+ assert idx.resolution == expected
lib/python3.10/site-packages/pandas/tests/indexes/datetimes/methods/test_snap.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from pandas import (
4
+ DatetimeIndex,
5
+ date_range,
6
+ )
7
+ import pandas._testing as tm
8
+
9
+
10
+ @pytest.mark.parametrize("tz", [None, "Asia/Shanghai", "Europe/Berlin"])
11
+ @pytest.mark.parametrize("name", [None, "my_dti"])
12
+ @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
13
+ def test_dti_snap(name, tz, unit):
14
+ dti = DatetimeIndex(
15
+ [
16
+ "1/1/2002",
17
+ "1/2/2002",
18
+ "1/3/2002",
19
+ "1/4/2002",
20
+ "1/5/2002",
21
+ "1/6/2002",
22
+ "1/7/2002",
23
+ ],
24
+ name=name,
25
+ tz=tz,
26
+ freq="D",
27
+ )
28
+ dti = dti.as_unit(unit)
29
+
30
+ result = dti.snap(freq="W-MON")
31
+ expected = date_range("12/31/2001", "1/7/2002", name=name, tz=tz, freq="w-mon")
32
+ expected = expected.repeat([3, 4])
33
+ expected = expected.as_unit(unit)
34
+ tm.assert_index_equal(result, expected)
35
+ assert result.tz == expected.tz
36
+ assert result.freq is None
37
+ assert expected.freq is None
38
+
39
+ result = dti.snap(freq="B")
40
+
41
+ expected = date_range("1/1/2002", "1/7/2002", name=name, tz=tz, freq="b")
42
+ expected = expected.repeat([1, 1, 1, 2, 2])
43
+ expected = expected.as_unit(unit)
44
+ tm.assert_index_equal(result, expected)
45
+ assert result.tz == expected.tz
46
+ assert result.freq is None
47
+ assert expected.freq is None
lib/python3.10/site-packages/pandas/tests/indexes/datetimes/methods/test_to_frame.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pandas import (
2
+ DataFrame,
3
+ Index,
4
+ date_range,
5
+ )
6
+ import pandas._testing as tm
7
+
8
+
9
+ class TestToFrame:
10
+ def test_to_frame_datetime_tz(self):
11
+ # GH#25809
12
+ idx = date_range(start="2019-01-01", end="2019-01-30", freq="D", tz="UTC")
13
+ result = idx.to_frame()
14
+ expected = DataFrame(idx, index=idx)
15
+ tm.assert_frame_equal(result, expected)
16
+
17
+ def test_to_frame_respects_none_name(self):
18
+ # GH#44212 if we explicitly pass name=None, then that should be respected,
19
+ # not changed to 0
20
+ # GH-45448 this is first deprecated to only change in the future
21
+ idx = date_range(start="2019-01-01", end="2019-01-30", freq="D", tz="UTC")
22
+ result = idx.to_frame(name=None)
23
+ exp_idx = Index([None], dtype=object)
24
+ tm.assert_index_equal(exp_idx, result.columns)
25
+
26
+ result = idx.rename("foo").to_frame(name=None)
27
+ exp_idx = Index([None], dtype=object)
28
+ tm.assert_index_equal(exp_idx, result.columns)
lib/python3.10/site-packages/pandas/tests/indexes/datetimes/methods/test_to_period.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dateutil.tz
2
+ from dateutil.tz import tzlocal
3
+ import pytest
4
+ import pytz
5
+
6
+ from pandas._libs.tslibs.ccalendar import MONTHS
7
+ from pandas._libs.tslibs.offsets import MonthEnd
8
+ from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG
9
+
10
+ from pandas import (
11
+ DatetimeIndex,
12
+ Period,
13
+ PeriodIndex,
14
+ Timestamp,
15
+ date_range,
16
+ period_range,
17
+ )
18
+ import pandas._testing as tm
19
+
20
+
21
+ class TestToPeriod:
22
+ def test_dti_to_period(self):
23
+ dti = date_range(start="1/1/2005", end="12/1/2005", freq="ME")
24
+ pi1 = dti.to_period()
25
+ pi2 = dti.to_period(freq="D")
26
+ pi3 = dti.to_period(freq="3D")
27
+
28
+ assert pi1[0] == Period("Jan 2005", freq="M")
29
+ assert pi2[0] == Period("1/31/2005", freq="D")
30
+ assert pi3[0] == Period("1/31/2005", freq="3D")
31
+
32
+ assert pi1[-1] == Period("Nov 2005", freq="M")
33
+ assert pi2[-1] == Period("11/30/2005", freq="D")
34
+ assert pi3[-1], Period("11/30/2005", freq="3D")
35
+
36
+ tm.assert_index_equal(pi1, period_range("1/1/2005", "11/1/2005", freq="M"))
37
+ tm.assert_index_equal(
38
+ pi2, period_range("1/1/2005", "11/1/2005", freq="M").asfreq("D")
39
+ )
40
+ tm.assert_index_equal(
41
+ pi3, period_range("1/1/2005", "11/1/2005", freq="M").asfreq("3D")
42
+ )
43
+
44
+ @pytest.mark.parametrize("month", MONTHS)
45
+ def test_to_period_quarterly(self, month):
46
+ # make sure we can make the round trip
47
+ freq = f"Q-{month}"
48
+ rng = period_range("1989Q3", "1991Q3", freq=freq)
49
+ stamps = rng.to_timestamp()
50
+ result = stamps.to_period(freq)
51
+ tm.assert_index_equal(rng, result)
52
+
53
+ @pytest.mark.parametrize("off", ["BQE", "QS", "BQS"])
54
+ def test_to_period_quarterlyish(self, off):
55
+ rng = date_range("01-Jan-2012", periods=8, freq=off)
56
+ prng = rng.to_period()
57
+ assert prng.freq == "QE-DEC"
58
+
59
+ @pytest.mark.parametrize("off", ["BYE", "YS", "BYS"])
60
+ def test_to_period_annualish(self, off):
61
+ rng = date_range("01-Jan-2012", periods=8, freq=off)
62
+ prng = rng.to_period()
63
+ assert prng.freq == "YE-DEC"
64
+
65
+ def test_to_period_monthish(self):
66
+ offsets = ["MS", "BME"]
67
+ for off in offsets:
68
+ rng = date_range("01-Jan-2012", periods=8, freq=off)
69
+ prng = rng.to_period()
70
+ assert prng.freqstr == "M"
71
+
72
+ rng = date_range("01-Jan-2012", periods=8, freq="ME")
73
+ prng = rng.to_period()
74
+ assert prng.freqstr == "M"
75
+
76
+ with pytest.raises(ValueError, match=INVALID_FREQ_ERR_MSG):
77
+ date_range("01-Jan-2012", periods=8, freq="EOM")
78
+
79
+ @pytest.mark.parametrize(
80
+ "freq_offset, freq_period",
81
+ [
82
+ ("2ME", "2M"),
83
+ (MonthEnd(2), MonthEnd(2)),
84
+ ],
85
+ )
86
+ def test_dti_to_period_2monthish(self, freq_offset, freq_period):
87
+ dti = date_range("2020-01-01", periods=3, freq=freq_offset)
88
+ pi = dti.to_period()
89
+
90
+ tm.assert_index_equal(pi, period_range("2020-01", "2020-05", freq=freq_period))
91
+
92
+ @pytest.mark.parametrize(
93
+ "freq, freq_depr",
94
+ [
95
+ ("2ME", "2M"),
96
+ ("2QE", "2Q"),
97
+ ("2QE-SEP", "2Q-SEP"),
98
+ ("1YE", "1Y"),
99
+ ("2YE-MAR", "2Y-MAR"),
100
+ ("1YE", "1A"),
101
+ ("2YE-MAR", "2A-MAR"),
102
+ ],
103
+ )
104
+ def test_to_period_frequency_M_Q_Y_A_deprecated(self, freq, freq_depr):
105
+ # GH#9586
106
+ msg = f"'{freq_depr[1:]}' is deprecated and will be removed "
107
+ f"in a future version, please use '{freq[1:]}' instead."
108
+
109
+ rng = date_range("01-Jan-2012", periods=8, freq=freq)
110
+ prng = rng.to_period()
111
+ with tm.assert_produces_warning(FutureWarning, match=msg):
112
+ assert prng.freq == freq_depr
113
+
114
+ def test_to_period_infer(self):
115
+ # https://github.com/pandas-dev/pandas/issues/33358
116
+ rng = date_range(
117
+ start="2019-12-22 06:40:00+00:00",
118
+ end="2019-12-22 08:45:00+00:00",
119
+ freq="5min",
120
+ )
121
+
122
+ with tm.assert_produces_warning(UserWarning):
123
+ pi1 = rng.to_period("5min")
124
+
125
+ with tm.assert_produces_warning(UserWarning):
126
+ pi2 = rng.to_period()
127
+
128
+ tm.assert_index_equal(pi1, pi2)
129
+
130
+ @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
131
+ def test_period_dt64_round_trip(self):
132
+ dti = date_range("1/1/2000", "1/7/2002", freq="B")
133
+ pi = dti.to_period()
134
+ tm.assert_index_equal(pi.to_timestamp(), dti)
135
+
136
+ dti = date_range("1/1/2000", "1/7/2002", freq="B")
137
+ pi = dti.to_period(freq="h")
138
+ tm.assert_index_equal(pi.to_timestamp(), dti)
139
+
140
+ def test_to_period_millisecond(self):
141
+ index = DatetimeIndex(
142
+ [
143
+ Timestamp("2007-01-01 10:11:12.123456Z"),
144
+ Timestamp("2007-01-01 10:11:13.789123Z"),
145
+ ]
146
+ )
147
+
148
+ with tm.assert_produces_warning(UserWarning):
149
+ # warning that timezone info will be lost
150
+ period = index.to_period(freq="ms")
151
+ assert 2 == len(period)
152
+ assert period[0] == Period("2007-01-01 10:11:12.123Z", "ms")
153
+ assert period[1] == Period("2007-01-01 10:11:13.789Z", "ms")
154
+
155
+ def test_to_period_microsecond(self):
156
+ index = DatetimeIndex(
157
+ [
158
+ Timestamp("2007-01-01 10:11:12.123456Z"),
159
+ Timestamp("2007-01-01 10:11:13.789123Z"),
160
+ ]
161
+ )
162
+
163
+ with tm.assert_produces_warning(UserWarning):
164
+ # warning that timezone info will be lost
165
+ period = index.to_period(freq="us")
166
+ assert 2 == len(period)
167
+ assert period[0] == Period("2007-01-01 10:11:12.123456Z", "us")
168
+ assert period[1] == Period("2007-01-01 10:11:13.789123Z", "us")
169
+
170
+ @pytest.mark.parametrize(
171
+ "tz",
172
+ ["US/Eastern", pytz.utc, tzlocal(), "dateutil/US/Eastern", dateutil.tz.tzutc()],
173
+ )
174
+ def test_to_period_tz(self, tz):
175
+ ts = date_range("1/1/2000", "2/1/2000", tz=tz)
176
+
177
+ with tm.assert_produces_warning(UserWarning):
178
+ # GH#21333 warning that timezone info will be lost
179
+ # filter warning about freq deprecation
180
+
181
+ result = ts.to_period()[0]
182
+ expected = ts[0].to_period(ts.freq)
183
+
184
+ assert result == expected
185
+
186
+ expected = date_range("1/1/2000", "2/1/2000").to_period()
187
+
188
+ with tm.assert_produces_warning(UserWarning):
189
+ # GH#21333 warning that timezone info will be lost
190
+ result = ts.to_period(ts.freq)
191
+
192
+ tm.assert_index_equal(result, expected)
193
+
194
+ @pytest.mark.parametrize("tz", ["Etc/GMT-1", "Etc/GMT+1"])
195
+ def test_to_period_tz_utc_offset_consistency(self, tz):
196
+ # GH#22905
197
+ ts = date_range("1/1/2000", "2/1/2000", tz="Etc/GMT-1")
198
+ with tm.assert_produces_warning(UserWarning):
199
+ result = ts.to_period()[0]
200
+ expected = ts[0].to_period(ts.freq)
201
+ assert result == expected
202
+
203
+ def test_to_period_nofreq(self):
204
+ idx = DatetimeIndex(["2000-01-01", "2000-01-02", "2000-01-04"])
205
+ msg = "You must pass a freq argument as current index has none."
206
+ with pytest.raises(ValueError, match=msg):
207
+ idx.to_period()
208
+
209
+ idx = DatetimeIndex(["2000-01-01", "2000-01-02", "2000-01-03"], freq="infer")
210
+ assert idx.freqstr == "D"
211
+ expected = PeriodIndex(["2000-01-01", "2000-01-02", "2000-01-03"], freq="D")
212
+ tm.assert_index_equal(idx.to_period(), expected)
213
+
214
+ # GH#7606
215
+ idx = DatetimeIndex(["2000-01-01", "2000-01-02", "2000-01-03"])
216
+ assert idx.freqstr is None
217
+ tm.assert_index_equal(idx.to_period(), expected)
218
+
219
+ @pytest.mark.parametrize("freq", ["2BMS", "1SME-15"])
220
+ def test_to_period_offsets_not_supported(self, freq):
221
+ # GH#56243
222
+ msg = f"{freq[1:]} is not supported as period frequency"
223
+ ts = date_range("1/1/2012", periods=4, freq=freq)
224
+ with pytest.raises(ValueError, match=msg):
225
+ ts.to_period()
lib/python3.10/site-packages/pandas/tests/indexes/datetimes/methods/test_tz_convert.py ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+
3
+ import dateutil.tz
4
+ from dateutil.tz import gettz
5
+ import numpy as np
6
+ import pytest
7
+ import pytz
8
+
9
+ from pandas._libs.tslibs import timezones
10
+
11
+ from pandas import (
12
+ DatetimeIndex,
13
+ Index,
14
+ NaT,
15
+ Timestamp,
16
+ date_range,
17
+ offsets,
18
+ )
19
+ import pandas._testing as tm
20
+
21
+
22
+ class TestTZConvert:
23
+ def test_tz_convert_nat(self):
24
+ # GH#5546
25
+ dates = [NaT]
26
+ idx = DatetimeIndex(dates)
27
+ idx = idx.tz_localize("US/Pacific")
28
+ tm.assert_index_equal(idx, DatetimeIndex(dates, tz="US/Pacific"))
29
+ idx = idx.tz_convert("US/Eastern")
30
+ tm.assert_index_equal(idx, DatetimeIndex(dates, tz="US/Eastern"))
31
+ idx = idx.tz_convert("UTC")
32
+ tm.assert_index_equal(idx, DatetimeIndex(dates, tz="UTC"))
33
+
34
+ dates = ["2010-12-01 00:00", "2010-12-02 00:00", NaT]
35
+ idx = DatetimeIndex(dates)
36
+ idx = idx.tz_localize("US/Pacific")
37
+ tm.assert_index_equal(idx, DatetimeIndex(dates, tz="US/Pacific"))
38
+ idx = idx.tz_convert("US/Eastern")
39
+ expected = ["2010-12-01 03:00", "2010-12-02 03:00", NaT]
40
+ tm.assert_index_equal(idx, DatetimeIndex(expected, tz="US/Eastern"))
41
+
42
+ idx = idx + offsets.Hour(5)
43
+ expected = ["2010-12-01 08:00", "2010-12-02 08:00", NaT]
44
+ tm.assert_index_equal(idx, DatetimeIndex(expected, tz="US/Eastern"))
45
+ idx = idx.tz_convert("US/Pacific")
46
+ expected = ["2010-12-01 05:00", "2010-12-02 05:00", NaT]
47
+ tm.assert_index_equal(idx, DatetimeIndex(expected, tz="US/Pacific"))
48
+
49
+ idx = idx + np.timedelta64(3, "h")
50
+ expected = ["2010-12-01 08:00", "2010-12-02 08:00", NaT]
51
+ tm.assert_index_equal(idx, DatetimeIndex(expected, tz="US/Pacific"))
52
+
53
+ idx = idx.tz_convert("US/Eastern")
54
+ expected = ["2010-12-01 11:00", "2010-12-02 11:00", NaT]
55
+ tm.assert_index_equal(idx, DatetimeIndex(expected, tz="US/Eastern"))
56
+
57
+ @pytest.mark.parametrize("prefix", ["", "dateutil/"])
58
+ def test_dti_tz_convert_compat_timestamp(self, prefix):
59
+ strdates = ["1/1/2012", "3/1/2012", "4/1/2012"]
60
+ idx = DatetimeIndex(strdates, tz=prefix + "US/Eastern")
61
+
62
+ conv = idx[0].tz_convert(prefix + "US/Pacific")
63
+ expected = idx.tz_convert(prefix + "US/Pacific")[0]
64
+
65
+ assert conv == expected
66
+
67
+ def test_dti_tz_convert_hour_overflow_dst(self):
68
+ # Regression test for GH#13306
69
+
70
+ # sorted case US/Eastern -> UTC
71
+ ts = ["2008-05-12 09:50:00", "2008-12-12 09:50:35", "2009-05-12 09:50:32"]
72
+ tt = DatetimeIndex(ts).tz_localize("US/Eastern")
73
+ ut = tt.tz_convert("UTC")
74
+ expected = Index([13, 14, 13], dtype=np.int32)
75
+ tm.assert_index_equal(ut.hour, expected)
76
+
77
+ # sorted case UTC -> US/Eastern
78
+ ts = ["2008-05-12 13:50:00", "2008-12-12 14:50:35", "2009-05-12 13:50:32"]
79
+ tt = DatetimeIndex(ts).tz_localize("UTC")
80
+ ut = tt.tz_convert("US/Eastern")
81
+ expected = Index([9, 9, 9], dtype=np.int32)
82
+ tm.assert_index_equal(ut.hour, expected)
83
+
84
+ # unsorted case US/Eastern -> UTC
85
+ ts = ["2008-05-12 09:50:00", "2008-12-12 09:50:35", "2008-05-12 09:50:32"]
86
+ tt = DatetimeIndex(ts).tz_localize("US/Eastern")
87
+ ut = tt.tz_convert("UTC")
88
+ expected = Index([13, 14, 13], dtype=np.int32)
89
+ tm.assert_index_equal(ut.hour, expected)
90
+
91
+ # unsorted case UTC -> US/Eastern
92
+ ts = ["2008-05-12 13:50:00", "2008-12-12 14:50:35", "2008-05-12 13:50:32"]
93
+ tt = DatetimeIndex(ts).tz_localize("UTC")
94
+ ut = tt.tz_convert("US/Eastern")
95
+ expected = Index([9, 9, 9], dtype=np.int32)
96
+ tm.assert_index_equal(ut.hour, expected)
97
+
98
+ @pytest.mark.parametrize("tz", ["US/Eastern", "dateutil/US/Eastern"])
99
+ def test_dti_tz_convert_hour_overflow_dst_timestamps(self, tz):
100
+ # Regression test for GH#13306
101
+
102
+ # sorted case US/Eastern -> UTC
103
+ ts = [
104
+ Timestamp("2008-05-12 09:50:00", tz=tz),
105
+ Timestamp("2008-12-12 09:50:35", tz=tz),
106
+ Timestamp("2009-05-12 09:50:32", tz=tz),
107
+ ]
108
+ tt = DatetimeIndex(ts)
109
+ ut = tt.tz_convert("UTC")
110
+ expected = Index([13, 14, 13], dtype=np.int32)
111
+ tm.assert_index_equal(ut.hour, expected)
112
+
113
+ # sorted case UTC -> US/Eastern
114
+ ts = [
115
+ Timestamp("2008-05-12 13:50:00", tz="UTC"),
116
+ Timestamp("2008-12-12 14:50:35", tz="UTC"),
117
+ Timestamp("2009-05-12 13:50:32", tz="UTC"),
118
+ ]
119
+ tt = DatetimeIndex(ts)
120
+ ut = tt.tz_convert("US/Eastern")
121
+ expected = Index([9, 9, 9], dtype=np.int32)
122
+ tm.assert_index_equal(ut.hour, expected)
123
+
124
+ # unsorted case US/Eastern -> UTC
125
+ ts = [
126
+ Timestamp("2008-05-12 09:50:00", tz=tz),
127
+ Timestamp("2008-12-12 09:50:35", tz=tz),
128
+ Timestamp("2008-05-12 09:50:32", tz=tz),
129
+ ]
130
+ tt = DatetimeIndex(ts)
131
+ ut = tt.tz_convert("UTC")
132
+ expected = Index([13, 14, 13], dtype=np.int32)
133
+ tm.assert_index_equal(ut.hour, expected)
134
+
135
+ # unsorted case UTC -> US/Eastern
136
+ ts = [
137
+ Timestamp("2008-05-12 13:50:00", tz="UTC"),
138
+ Timestamp("2008-12-12 14:50:35", tz="UTC"),
139
+ Timestamp("2008-05-12 13:50:32", tz="UTC"),
140
+ ]
141
+ tt = DatetimeIndex(ts)
142
+ ut = tt.tz_convert("US/Eastern")
143
+ expected = Index([9, 9, 9], dtype=np.int32)
144
+ tm.assert_index_equal(ut.hour, expected)
145
+
146
+ @pytest.mark.parametrize("freq, n", [("h", 1), ("min", 60), ("s", 3600)])
147
+ def test_dti_tz_convert_trans_pos_plus_1__bug(self, freq, n):
148
+ # Regression test for tslib.tz_convert(vals, tz1, tz2).
149
+ # See GH#4496 for details.
150
+ idx = date_range(datetime(2011, 3, 26, 23), datetime(2011, 3, 27, 1), freq=freq)
151
+ idx = idx.tz_localize("UTC")
152
+ idx = idx.tz_convert("Europe/Moscow")
153
+
154
+ expected = np.repeat(np.array([3, 4, 5]), np.array([n, n, 1]))
155
+ tm.assert_index_equal(idx.hour, Index(expected, dtype=np.int32))
156
+
157
+ def test_dti_tz_convert_dst(self):
158
+ for freq, n in [("h", 1), ("min", 60), ("s", 3600)]:
159
+ # Start DST
160
+ idx = date_range(
161
+ "2014-03-08 23:00", "2014-03-09 09:00", freq=freq, tz="UTC"
162
+ )
163
+ idx = idx.tz_convert("US/Eastern")
164
+ expected = np.repeat(
165
+ np.array([18, 19, 20, 21, 22, 23, 0, 1, 3, 4, 5]),
166
+ np.array([n, n, n, n, n, n, n, n, n, n, 1]),
167
+ )
168
+ tm.assert_index_equal(idx.hour, Index(expected, dtype=np.int32))
169
+
170
+ idx = date_range(
171
+ "2014-03-08 18:00", "2014-03-09 05:00", freq=freq, tz="US/Eastern"
172
+ )
173
+ idx = idx.tz_convert("UTC")
174
+ expected = np.repeat(
175
+ np.array([23, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
176
+ np.array([n, n, n, n, n, n, n, n, n, n, 1]),
177
+ )
178
+ tm.assert_index_equal(idx.hour, Index(expected, dtype=np.int32))
179
+
180
+ # End DST
181
+ idx = date_range(
182
+ "2014-11-01 23:00", "2014-11-02 09:00", freq=freq, tz="UTC"
183
+ )
184
+ idx = idx.tz_convert("US/Eastern")
185
+ expected = np.repeat(
186
+ np.array([19, 20, 21, 22, 23, 0, 1, 1, 2, 3, 4]),
187
+ np.array([n, n, n, n, n, n, n, n, n, n, 1]),
188
+ )
189
+ tm.assert_index_equal(idx.hour, Index(expected, dtype=np.int32))
190
+
191
+ idx = date_range(
192
+ "2014-11-01 18:00", "2014-11-02 05:00", freq=freq, tz="US/Eastern"
193
+ )
194
+ idx = idx.tz_convert("UTC")
195
+ expected = np.repeat(
196
+ np.array([22, 23, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]),
197
+ np.array([n, n, n, n, n, n, n, n, n, n, n, n, 1]),
198
+ )
199
+ tm.assert_index_equal(idx.hour, Index(expected, dtype=np.int32))
200
+
201
+ # daily
202
+ # Start DST
203
+ idx = date_range("2014-03-08 00:00", "2014-03-09 00:00", freq="D", tz="UTC")
204
+ idx = idx.tz_convert("US/Eastern")
205
+ tm.assert_index_equal(idx.hour, Index([19, 19], dtype=np.int32))
206
+
207
+ idx = date_range(
208
+ "2014-03-08 00:00", "2014-03-09 00:00", freq="D", tz="US/Eastern"
209
+ )
210
+ idx = idx.tz_convert("UTC")
211
+ tm.assert_index_equal(idx.hour, Index([5, 5], dtype=np.int32))
212
+
213
+ # End DST
214
+ idx = date_range("2014-11-01 00:00", "2014-11-02 00:00", freq="D", tz="UTC")
215
+ idx = idx.tz_convert("US/Eastern")
216
+ tm.assert_index_equal(idx.hour, Index([20, 20], dtype=np.int32))
217
+
218
+ idx = date_range(
219
+ "2014-11-01 00:00", "2014-11-02 000:00", freq="D", tz="US/Eastern"
220
+ )
221
+ idx = idx.tz_convert("UTC")
222
+ tm.assert_index_equal(idx.hour, Index([4, 4], dtype=np.int32))
223
+
224
+ def test_tz_convert_roundtrip(self, tz_aware_fixture):
225
+ tz = tz_aware_fixture
226
+ idx1 = date_range(start="2014-01-01", end="2014-12-31", freq="ME", tz="UTC")
227
+ exp1 = date_range(start="2014-01-01", end="2014-12-31", freq="ME")
228
+
229
+ idx2 = date_range(start="2014-01-01", end="2014-12-31", freq="D", tz="UTC")
230
+ exp2 = date_range(start="2014-01-01", end="2014-12-31", freq="D")
231
+
232
+ idx3 = date_range(start="2014-01-01", end="2014-03-01", freq="h", tz="UTC")
233
+ exp3 = date_range(start="2014-01-01", end="2014-03-01", freq="h")
234
+
235
+ idx4 = date_range(start="2014-08-01", end="2014-10-31", freq="min", tz="UTC")
236
+ exp4 = date_range(start="2014-08-01", end="2014-10-31", freq="min")
237
+
238
+ for idx, expected in [(idx1, exp1), (idx2, exp2), (idx3, exp3), (idx4, exp4)]:
239
+ converted = idx.tz_convert(tz)
240
+ reset = converted.tz_convert(None)
241
+ tm.assert_index_equal(reset, expected)
242
+ assert reset.tzinfo is None
243
+ expected = converted.tz_convert("UTC").tz_localize(None)
244
+ expected = expected._with_freq("infer")
245
+ tm.assert_index_equal(reset, expected)
246
+
247
+ def test_dti_tz_convert_tzlocal(self):
248
+ # GH#13583
249
+ # tz_convert doesn't affect to internal
250
+ dti = date_range(start="2001-01-01", end="2001-03-01", tz="UTC")
251
+ dti2 = dti.tz_convert(dateutil.tz.tzlocal())
252
+ tm.assert_numpy_array_equal(dti2.asi8, dti.asi8)
253
+
254
+ dti = date_range(start="2001-01-01", end="2001-03-01", tz=dateutil.tz.tzlocal())
255
+ dti2 = dti.tz_convert(None)
256
+ tm.assert_numpy_array_equal(dti2.asi8, dti.asi8)
257
+
258
+ @pytest.mark.parametrize(
259
+ "tz",
260
+ [
261
+ "US/Eastern",
262
+ "dateutil/US/Eastern",
263
+ pytz.timezone("US/Eastern"),
264
+ gettz("US/Eastern"),
265
+ ],
266
+ )
267
+ def test_dti_tz_convert_utc_to_local_no_modify(self, tz):
268
+ rng = date_range("3/11/2012", "3/12/2012", freq="h", tz="utc")
269
+ rng_eastern = rng.tz_convert(tz)
270
+
271
+ # Values are unmodified
272
+ tm.assert_numpy_array_equal(rng.asi8, rng_eastern.asi8)
273
+
274
+ assert timezones.tz_compare(rng_eastern.tz, timezones.maybe_get_tz(tz))
275
+
276
+ @pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"])
277
+ def test_tz_convert_unsorted(self, tzstr):
278
+ dr = date_range("2012-03-09", freq="h", periods=100, tz="utc")
279
+ dr = dr.tz_convert(tzstr)
280
+
281
+ result = dr[::-1].hour
282
+ exp = dr.hour[::-1]
283
+ tm.assert_almost_equal(result, exp)
lib/python3.10/site-packages/pandas/tests/indexes/interval/__init__.py ADDED
File without changes
lib/python3.10/site-packages/pandas/tests/indexes/interval/test_astype.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ from pandas.core.dtypes.dtypes import (
7
+ CategoricalDtype,
8
+ IntervalDtype,
9
+ )
10
+
11
+ from pandas import (
12
+ CategoricalIndex,
13
+ Index,
14
+ IntervalIndex,
15
+ NaT,
16
+ Timedelta,
17
+ Timestamp,
18
+ interval_range,
19
+ )
20
+ import pandas._testing as tm
21
+
22
+
23
+ class AstypeTests:
24
+ """Tests common to IntervalIndex with any subtype"""
25
+
26
+ def test_astype_idempotent(self, index):
27
+ result = index.astype("interval")
28
+ tm.assert_index_equal(result, index)
29
+
30
+ result = index.astype(index.dtype)
31
+ tm.assert_index_equal(result, index)
32
+
33
+ def test_astype_object(self, index):
34
+ result = index.astype(object)
35
+ expected = Index(index.values, dtype="object")
36
+ tm.assert_index_equal(result, expected)
37
+ assert not result.equals(index)
38
+
39
+ def test_astype_category(self, index):
40
+ result = index.astype("category")
41
+ expected = CategoricalIndex(index.values)
42
+ tm.assert_index_equal(result, expected)
43
+
44
+ result = index.astype(CategoricalDtype())
45
+ tm.assert_index_equal(result, expected)
46
+
47
+ # non-default params
48
+ categories = index.dropna().unique().values[:-1]
49
+ dtype = CategoricalDtype(categories=categories, ordered=True)
50
+ result = index.astype(dtype)
51
+ expected = CategoricalIndex(index.values, categories=categories, ordered=True)
52
+ tm.assert_index_equal(result, expected)
53
+
54
+ @pytest.mark.parametrize(
55
+ "dtype",
56
+ [
57
+ "int64",
58
+ "uint64",
59
+ "float64",
60
+ "complex128",
61
+ "period[M]",
62
+ "timedelta64",
63
+ "timedelta64[ns]",
64
+ "datetime64",
65
+ "datetime64[ns]",
66
+ "datetime64[ns, US/Eastern]",
67
+ ],
68
+ )
69
+ def test_astype_cannot_cast(self, index, dtype):
70
+ msg = "Cannot cast IntervalIndex to dtype"
71
+ with pytest.raises(TypeError, match=msg):
72
+ index.astype(dtype)
73
+
74
+ def test_astype_invalid_dtype(self, index):
75
+ msg = "data type [\"']fake_dtype[\"'] not understood"
76
+ with pytest.raises(TypeError, match=msg):
77
+ index.astype("fake_dtype")
78
+
79
+
80
+ class TestIntSubtype(AstypeTests):
81
+ """Tests specific to IntervalIndex with integer-like subtype"""
82
+
83
+ indexes = [
84
+ IntervalIndex.from_breaks(np.arange(-10, 11, dtype="int64")),
85
+ IntervalIndex.from_breaks(np.arange(100, dtype="uint64"), closed="left"),
86
+ ]
87
+
88
+ @pytest.fixture(params=indexes)
89
+ def index(self, request):
90
+ return request.param
91
+
92
+ @pytest.mark.parametrize(
93
+ "subtype", ["float64", "datetime64[ns]", "timedelta64[ns]"]
94
+ )
95
+ def test_subtype_conversion(self, index, subtype):
96
+ dtype = IntervalDtype(subtype, index.closed)
97
+ result = index.astype(dtype)
98
+ expected = IntervalIndex.from_arrays(
99
+ index.left.astype(subtype), index.right.astype(subtype), closed=index.closed
100
+ )
101
+ tm.assert_index_equal(result, expected)
102
+
103
+ @pytest.mark.parametrize(
104
+ "subtype_start, subtype_end", [("int64", "uint64"), ("uint64", "int64")]
105
+ )
106
+ def test_subtype_integer(self, subtype_start, subtype_end):
107
+ index = IntervalIndex.from_breaks(np.arange(100, dtype=subtype_start))
108
+ dtype = IntervalDtype(subtype_end, index.closed)
109
+ result = index.astype(dtype)
110
+ expected = IntervalIndex.from_arrays(
111
+ index.left.astype(subtype_end),
112
+ index.right.astype(subtype_end),
113
+ closed=index.closed,
114
+ )
115
+ tm.assert_index_equal(result, expected)
116
+
117
+ @pytest.mark.xfail(reason="GH#15832")
118
+ def test_subtype_integer_errors(self):
119
+ # int64 -> uint64 fails with negative values
120
+ index = interval_range(-10, 10)
121
+ dtype = IntervalDtype("uint64", "right")
122
+
123
+ # Until we decide what the exception message _should_ be, we
124
+ # assert something that it should _not_ be.
125
+ # We should _not_ be getting a message suggesting that the -10
126
+ # has been wrapped around to a large-positive integer
127
+ msg = "^(?!(left side of interval must be <= right side))"
128
+ with pytest.raises(ValueError, match=msg):
129
+ index.astype(dtype)
130
+
131
+
132
+ class TestFloatSubtype(AstypeTests):
133
+ """Tests specific to IntervalIndex with float subtype"""
134
+
135
+ indexes = [
136
+ interval_range(-10.0, 10.0, closed="neither"),
137
+ IntervalIndex.from_arrays(
138
+ [-1.5, np.nan, 0.0, 0.0, 1.5], [-0.5, np.nan, 1.0, 1.0, 3.0], closed="both"
139
+ ),
140
+ ]
141
+
142
+ @pytest.fixture(params=indexes)
143
+ def index(self, request):
144
+ return request.param
145
+
146
+ @pytest.mark.parametrize("subtype", ["int64", "uint64"])
147
+ def test_subtype_integer(self, subtype):
148
+ index = interval_range(0.0, 10.0)
149
+ dtype = IntervalDtype(subtype, "right")
150
+ result = index.astype(dtype)
151
+ expected = IntervalIndex.from_arrays(
152
+ index.left.astype(subtype), index.right.astype(subtype), closed=index.closed
153
+ )
154
+ tm.assert_index_equal(result, expected)
155
+
156
+ # raises with NA
157
+ msg = r"Cannot convert non-finite values \(NA or inf\) to integer"
158
+ with pytest.raises(ValueError, match=msg):
159
+ index.insert(0, np.nan).astype(dtype)
160
+
161
+ @pytest.mark.parametrize("subtype", ["int64", "uint64"])
162
+ def test_subtype_integer_with_non_integer_borders(self, subtype):
163
+ index = interval_range(0.0, 3.0, freq=0.25)
164
+ dtype = IntervalDtype(subtype, "right")
165
+ result = index.astype(dtype)
166
+ expected = IntervalIndex.from_arrays(
167
+ index.left.astype(subtype), index.right.astype(subtype), closed=index.closed
168
+ )
169
+ tm.assert_index_equal(result, expected)
170
+
171
+ def test_subtype_integer_errors(self):
172
+ # float64 -> uint64 fails with negative values
173
+ index = interval_range(-10.0, 10.0)
174
+ dtype = IntervalDtype("uint64", "right")
175
+ msg = re.escape(
176
+ "Cannot convert interval[float64, right] to interval[uint64, right]; "
177
+ "subtypes are incompatible"
178
+ )
179
+ with pytest.raises(TypeError, match=msg):
180
+ index.astype(dtype)
181
+
182
+ @pytest.mark.parametrize("subtype", ["datetime64[ns]", "timedelta64[ns]"])
183
+ def test_subtype_datetimelike(self, index, subtype):
184
+ dtype = IntervalDtype(subtype, "right")
185
+ msg = "Cannot convert .* to .*; subtypes are incompatible"
186
+ with pytest.raises(TypeError, match=msg):
187
+ index.astype(dtype)
188
+
189
+
190
+ class TestDatetimelikeSubtype(AstypeTests):
191
+ """Tests specific to IntervalIndex with datetime-like subtype"""
192
+
193
+ indexes = [
194
+ interval_range(Timestamp("2018-01-01"), periods=10, closed="neither"),
195
+ interval_range(Timestamp("2018-01-01"), periods=10).insert(2, NaT),
196
+ interval_range(Timestamp("2018-01-01", tz="US/Eastern"), periods=10),
197
+ interval_range(Timedelta("0 days"), periods=10, closed="both"),
198
+ interval_range(Timedelta("0 days"), periods=10).insert(2, NaT),
199
+ ]
200
+
201
+ @pytest.fixture(params=indexes)
202
+ def index(self, request):
203
+ return request.param
204
+
205
+ @pytest.mark.parametrize("subtype", ["int64", "uint64"])
206
+ def test_subtype_integer(self, index, subtype):
207
+ dtype = IntervalDtype(subtype, "right")
208
+
209
+ if subtype != "int64":
210
+ msg = (
211
+ r"Cannot convert interval\[(timedelta64|datetime64)\[ns.*\], .*\] "
212
+ r"to interval\[uint64, .*\]"
213
+ )
214
+ with pytest.raises(TypeError, match=msg):
215
+ index.astype(dtype)
216
+ return
217
+
218
+ result = index.astype(dtype)
219
+ new_left = index.left.astype(subtype)
220
+ new_right = index.right.astype(subtype)
221
+
222
+ expected = IntervalIndex.from_arrays(new_left, new_right, closed=index.closed)
223
+ tm.assert_index_equal(result, expected)
224
+
225
+ def test_subtype_float(self, index):
226
+ dtype = IntervalDtype("float64", "right")
227
+ msg = "Cannot convert .* to .*; subtypes are incompatible"
228
+ with pytest.raises(TypeError, match=msg):
229
+ index.astype(dtype)
230
+
231
+ def test_subtype_datetimelike(self):
232
+ # datetime -> timedelta raises
233
+ dtype = IntervalDtype("timedelta64[ns]", "right")
234
+ msg = "Cannot convert .* to .*; subtypes are incompatible"
235
+
236
+ index = interval_range(Timestamp("2018-01-01"), periods=10)
237
+ with pytest.raises(TypeError, match=msg):
238
+ index.astype(dtype)
239
+
240
+ index = interval_range(Timestamp("2018-01-01", tz="CET"), periods=10)
241
+ with pytest.raises(TypeError, match=msg):
242
+ index.astype(dtype)
243
+
244
+ # timedelta -> datetime raises
245
+ dtype = IntervalDtype("datetime64[ns]", "right")
246
+ index = interval_range(Timedelta("0 days"), periods=10)
247
+ with pytest.raises(TypeError, match=msg):
248
+ index.astype(dtype)
lib/python3.10/site-packages/pandas/tests/indexes/interval/test_constructors.py ADDED
@@ -0,0 +1,535 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import partial
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ import pandas.util._test_decorators as td
7
+
8
+ from pandas.core.dtypes.common import is_unsigned_integer_dtype
9
+ from pandas.core.dtypes.dtypes import IntervalDtype
10
+
11
+ from pandas import (
12
+ Categorical,
13
+ CategoricalDtype,
14
+ CategoricalIndex,
15
+ Index,
16
+ Interval,
17
+ IntervalIndex,
18
+ date_range,
19
+ notna,
20
+ period_range,
21
+ timedelta_range,
22
+ )
23
+ import pandas._testing as tm
24
+ from pandas.core.arrays import IntervalArray
25
+ import pandas.core.common as com
26
+
27
+
28
+ @pytest.fixture(params=[None, "foo"])
29
+ def name(request):
30
+ return request.param
31
+
32
+
33
+ class ConstructorTests:
34
+ """
35
+ Common tests for all variations of IntervalIndex construction. Input data
36
+ to be supplied in breaks format, then converted by the subclass method
37
+ get_kwargs_from_breaks to the expected format.
38
+ """
39
+
40
+ @pytest.fixture(
41
+ params=[
42
+ ([3, 14, 15, 92, 653], np.int64),
43
+ (np.arange(10, dtype="int64"), np.int64),
44
+ (Index(np.arange(-10, 11, dtype=np.int64)), np.int64),
45
+ (Index(np.arange(10, 31, dtype=np.uint64)), np.uint64),
46
+ (Index(np.arange(20, 30, 0.5), dtype=np.float64), np.float64),
47
+ (date_range("20180101", periods=10), "<M8[ns]"),
48
+ (
49
+ date_range("20180101", periods=10, tz="US/Eastern"),
50
+ "datetime64[ns, US/Eastern]",
51
+ ),
52
+ (timedelta_range("1 day", periods=10), "<m8[ns]"),
53
+ ]
54
+ )
55
+ def breaks_and_expected_subtype(self, request):
56
+ return request.param
57
+
58
+ def test_constructor(self, constructor, breaks_and_expected_subtype, closed, name):
59
+ breaks, expected_subtype = breaks_and_expected_subtype
60
+
61
+ result_kwargs = self.get_kwargs_from_breaks(breaks, closed)
62
+
63
+ result = constructor(closed=closed, name=name, **result_kwargs)
64
+
65
+ assert result.closed == closed
66
+ assert result.name == name
67
+ assert result.dtype.subtype == expected_subtype
68
+ tm.assert_index_equal(result.left, Index(breaks[:-1], dtype=expected_subtype))
69
+ tm.assert_index_equal(result.right, Index(breaks[1:], dtype=expected_subtype))
70
+
71
+ @pytest.mark.parametrize(
72
+ "breaks, subtype",
73
+ [
74
+ (Index([0, 1, 2, 3, 4], dtype=np.int64), "float64"),
75
+ (Index([0, 1, 2, 3, 4], dtype=np.int64), "datetime64[ns]"),
76
+ (Index([0, 1, 2, 3, 4], dtype=np.int64), "timedelta64[ns]"),
77
+ (Index([0, 1, 2, 3, 4], dtype=np.float64), "int64"),
78
+ (date_range("2017-01-01", periods=5), "int64"),
79
+ (timedelta_range("1 day", periods=5), "int64"),
80
+ ],
81
+ )
82
+ def test_constructor_dtype(self, constructor, breaks, subtype):
83
+ # GH 19262: conversion via dtype parameter
84
+ expected_kwargs = self.get_kwargs_from_breaks(breaks.astype(subtype))
85
+ expected = constructor(**expected_kwargs)
86
+
87
+ result_kwargs = self.get_kwargs_from_breaks(breaks)
88
+ iv_dtype = IntervalDtype(subtype, "right")
89
+ for dtype in (iv_dtype, str(iv_dtype)):
90
+ result = constructor(dtype=dtype, **result_kwargs)
91
+ tm.assert_index_equal(result, expected)
92
+
93
+ @pytest.mark.parametrize(
94
+ "breaks",
95
+ [
96
+ Index([0, 1, 2, 3, 4], dtype=np.int64),
97
+ Index([0, 1, 2, 3, 4], dtype=np.uint64),
98
+ Index([0, 1, 2, 3, 4], dtype=np.float64),
99
+ date_range("2017-01-01", periods=5),
100
+ timedelta_range("1 day", periods=5),
101
+ ],
102
+ )
103
+ def test_constructor_pass_closed(self, constructor, breaks):
104
+ # not passing closed to IntervalDtype, but to IntervalArray constructor
105
+ iv_dtype = IntervalDtype(breaks.dtype)
106
+
107
+ result_kwargs = self.get_kwargs_from_breaks(breaks)
108
+
109
+ for dtype in (iv_dtype, str(iv_dtype)):
110
+ with tm.assert_produces_warning(None):
111
+ result = constructor(dtype=dtype, closed="left", **result_kwargs)
112
+ assert result.dtype.closed == "left"
113
+
114
+ @pytest.mark.parametrize("breaks", [[np.nan] * 2, [np.nan] * 4, [np.nan] * 50])
115
+ def test_constructor_nan(self, constructor, breaks, closed):
116
+ # GH 18421
117
+ result_kwargs = self.get_kwargs_from_breaks(breaks)
118
+ result = constructor(closed=closed, **result_kwargs)
119
+
120
+ expected_subtype = np.float64
121
+ expected_values = np.array(breaks[:-1], dtype=object)
122
+
123
+ assert result.closed == closed
124
+ assert result.dtype.subtype == expected_subtype
125
+ tm.assert_numpy_array_equal(np.array(result), expected_values)
126
+
127
+ @pytest.mark.parametrize(
128
+ "breaks",
129
+ [
130
+ [],
131
+ np.array([], dtype="int64"),
132
+ np.array([], dtype="uint64"),
133
+ np.array([], dtype="float64"),
134
+ np.array([], dtype="datetime64[ns]"),
135
+ np.array([], dtype="timedelta64[ns]"),
136
+ ],
137
+ )
138
+ def test_constructor_empty(self, constructor, breaks, closed):
139
+ # GH 18421
140
+ result_kwargs = self.get_kwargs_from_breaks(breaks)
141
+ result = constructor(closed=closed, **result_kwargs)
142
+
143
+ expected_values = np.array([], dtype=object)
144
+ expected_subtype = getattr(breaks, "dtype", np.int64)
145
+
146
+ assert result.empty
147
+ assert result.closed == closed
148
+ assert result.dtype.subtype == expected_subtype
149
+ tm.assert_numpy_array_equal(np.array(result), expected_values)
150
+
151
+ @pytest.mark.parametrize(
152
+ "breaks",
153
+ [
154
+ tuple("0123456789"),
155
+ list("abcdefghij"),
156
+ np.array(list("abcdefghij"), dtype=object),
157
+ np.array(list("abcdefghij"), dtype="<U1"),
158
+ ],
159
+ )
160
+ def test_constructor_string(self, constructor, breaks):
161
+ # GH 19016
162
+ msg = (
163
+ "category, object, and string subtypes are not supported "
164
+ "for IntervalIndex"
165
+ )
166
+ with pytest.raises(TypeError, match=msg):
167
+ constructor(**self.get_kwargs_from_breaks(breaks))
168
+
169
+ @pytest.mark.parametrize("cat_constructor", [Categorical, CategoricalIndex])
170
+ def test_constructor_categorical_valid(self, constructor, cat_constructor):
171
+ # GH 21243/21253
172
+
173
+ breaks = np.arange(10, dtype="int64")
174
+ expected = IntervalIndex.from_breaks(breaks)
175
+
176
+ cat_breaks = cat_constructor(breaks)
177
+ result_kwargs = self.get_kwargs_from_breaks(cat_breaks)
178
+ result = constructor(**result_kwargs)
179
+ tm.assert_index_equal(result, expected)
180
+
181
+ def test_generic_errors(self, constructor):
182
+ # filler input data to be used when supplying invalid kwargs
183
+ filler = self.get_kwargs_from_breaks(range(10))
184
+
185
+ # invalid closed
186
+ msg = "closed must be one of 'right', 'left', 'both', 'neither'"
187
+ with pytest.raises(ValueError, match=msg):
188
+ constructor(closed="invalid", **filler)
189
+
190
+ # unsupported dtype
191
+ msg = "dtype must be an IntervalDtype, got int64"
192
+ with pytest.raises(TypeError, match=msg):
193
+ constructor(dtype="int64", **filler)
194
+
195
+ # invalid dtype
196
+ msg = "data type [\"']invalid[\"'] not understood"
197
+ with pytest.raises(TypeError, match=msg):
198
+ constructor(dtype="invalid", **filler)
199
+
200
+ # no point in nesting periods in an IntervalIndex
201
+ periods = period_range("2000-01-01", periods=10)
202
+ periods_kwargs = self.get_kwargs_from_breaks(periods)
203
+ msg = "Period dtypes are not supported, use a PeriodIndex instead"
204
+ with pytest.raises(ValueError, match=msg):
205
+ constructor(**periods_kwargs)
206
+
207
+ # decreasing values
208
+ decreasing_kwargs = self.get_kwargs_from_breaks(range(10, -1, -1))
209
+ msg = "left side of interval must be <= right side"
210
+ with pytest.raises(ValueError, match=msg):
211
+ constructor(**decreasing_kwargs)
212
+
213
+
214
+ class TestFromArrays(ConstructorTests):
215
+ """Tests specific to IntervalIndex.from_arrays"""
216
+
217
+ @pytest.fixture
218
+ def constructor(self):
219
+ return IntervalIndex.from_arrays
220
+
221
+ def get_kwargs_from_breaks(self, breaks, closed="right"):
222
+ """
223
+ converts intervals in breaks format to a dictionary of kwargs to
224
+ specific to the format expected by IntervalIndex.from_arrays
225
+ """
226
+ return {"left": breaks[:-1], "right": breaks[1:]}
227
+
228
+ def test_constructor_errors(self):
229
+ # GH 19016: categorical data
230
+ data = Categorical(list("01234abcde"), ordered=True)
231
+ msg = (
232
+ "category, object, and string subtypes are not supported "
233
+ "for IntervalIndex"
234
+ )
235
+ with pytest.raises(TypeError, match=msg):
236
+ IntervalIndex.from_arrays(data[:-1], data[1:])
237
+
238
+ # unequal length
239
+ left = [0, 1, 2]
240
+ right = [2, 3]
241
+ msg = "left and right must have the same length"
242
+ with pytest.raises(ValueError, match=msg):
243
+ IntervalIndex.from_arrays(left, right)
244
+
245
+ @pytest.mark.parametrize(
246
+ "left_subtype, right_subtype", [(np.int64, np.float64), (np.float64, np.int64)]
247
+ )
248
+ def test_mixed_float_int(self, left_subtype, right_subtype):
249
+ """mixed int/float left/right results in float for both sides"""
250
+ left = np.arange(9, dtype=left_subtype)
251
+ right = np.arange(1, 10, dtype=right_subtype)
252
+ result = IntervalIndex.from_arrays(left, right)
253
+
254
+ expected_left = Index(left, dtype=np.float64)
255
+ expected_right = Index(right, dtype=np.float64)
256
+ expected_subtype = np.float64
257
+
258
+ tm.assert_index_equal(result.left, expected_left)
259
+ tm.assert_index_equal(result.right, expected_right)
260
+ assert result.dtype.subtype == expected_subtype
261
+
262
+ @pytest.mark.parametrize("interval_cls", [IntervalArray, IntervalIndex])
263
+ def test_from_arrays_mismatched_datetimelike_resos(self, interval_cls):
264
+ # GH#55714
265
+ left = date_range("2016-01-01", periods=3, unit="s")
266
+ right = date_range("2017-01-01", periods=3, unit="ms")
267
+ result = interval_cls.from_arrays(left, right)
268
+ expected = interval_cls.from_arrays(left.as_unit("ms"), right)
269
+ tm.assert_equal(result, expected)
270
+
271
+ # td64
272
+ left2 = left - left[0]
273
+ right2 = right - left[0]
274
+ result2 = interval_cls.from_arrays(left2, right2)
275
+ expected2 = interval_cls.from_arrays(left2.as_unit("ms"), right2)
276
+ tm.assert_equal(result2, expected2)
277
+
278
+ # dt64tz
279
+ left3 = left.tz_localize("UTC")
280
+ right3 = right.tz_localize("UTC")
281
+ result3 = interval_cls.from_arrays(left3, right3)
282
+ expected3 = interval_cls.from_arrays(left3.as_unit("ms"), right3)
283
+ tm.assert_equal(result3, expected3)
284
+
285
+
286
+ class TestFromBreaks(ConstructorTests):
287
+ """Tests specific to IntervalIndex.from_breaks"""
288
+
289
+ @pytest.fixture
290
+ def constructor(self):
291
+ return IntervalIndex.from_breaks
292
+
293
+ def get_kwargs_from_breaks(self, breaks, closed="right"):
294
+ """
295
+ converts intervals in breaks format to a dictionary of kwargs to
296
+ specific to the format expected by IntervalIndex.from_breaks
297
+ """
298
+ return {"breaks": breaks}
299
+
300
+ def test_constructor_errors(self):
301
+ # GH 19016: categorical data
302
+ data = Categorical(list("01234abcde"), ordered=True)
303
+ msg = (
304
+ "category, object, and string subtypes are not supported "
305
+ "for IntervalIndex"
306
+ )
307
+ with pytest.raises(TypeError, match=msg):
308
+ IntervalIndex.from_breaks(data)
309
+
310
+ def test_length_one(self):
311
+ """breaks of length one produce an empty IntervalIndex"""
312
+ breaks = [0]
313
+ result = IntervalIndex.from_breaks(breaks)
314
+ expected = IntervalIndex.from_breaks([])
315
+ tm.assert_index_equal(result, expected)
316
+
317
+ def test_left_right_dont_share_data(self):
318
+ # GH#36310
319
+ breaks = np.arange(5)
320
+ result = IntervalIndex.from_breaks(breaks)._data
321
+ assert result._left.base is None or result._left.base is not result._right.base
322
+
323
+
324
+ class TestFromTuples(ConstructorTests):
325
+ """Tests specific to IntervalIndex.from_tuples"""
326
+
327
+ @pytest.fixture
328
+ def constructor(self):
329
+ return IntervalIndex.from_tuples
330
+
331
+ def get_kwargs_from_breaks(self, breaks, closed="right"):
332
+ """
333
+ converts intervals in breaks format to a dictionary of kwargs to
334
+ specific to the format expected by IntervalIndex.from_tuples
335
+ """
336
+ if is_unsigned_integer_dtype(breaks):
337
+ pytest.skip(f"{breaks.dtype} not relevant IntervalIndex.from_tuples tests")
338
+
339
+ if len(breaks) == 0:
340
+ return {"data": breaks}
341
+
342
+ tuples = list(zip(breaks[:-1], breaks[1:]))
343
+ if isinstance(breaks, (list, tuple)):
344
+ return {"data": tuples}
345
+ elif isinstance(getattr(breaks, "dtype", None), CategoricalDtype):
346
+ return {"data": breaks._constructor(tuples)}
347
+ return {"data": com.asarray_tuplesafe(tuples)}
348
+
349
+ def test_constructor_errors(self):
350
+ # non-tuple
351
+ tuples = [(0, 1), 2, (3, 4)]
352
+ msg = "IntervalIndex.from_tuples received an invalid item, 2"
353
+ with pytest.raises(TypeError, match=msg.format(t=tuples)):
354
+ IntervalIndex.from_tuples(tuples)
355
+
356
+ # too few/many items
357
+ tuples = [(0, 1), (2,), (3, 4)]
358
+ msg = "IntervalIndex.from_tuples requires tuples of length 2, got {t}"
359
+ with pytest.raises(ValueError, match=msg.format(t=tuples)):
360
+ IntervalIndex.from_tuples(tuples)
361
+
362
+ tuples = [(0, 1), (2, 3, 4), (5, 6)]
363
+ with pytest.raises(ValueError, match=msg.format(t=tuples)):
364
+ IntervalIndex.from_tuples(tuples)
365
+
366
+ def test_na_tuples(self):
367
+ # tuple (NA, NA) evaluates the same as NA as an element
368
+ na_tuple = [(0, 1), (np.nan, np.nan), (2, 3)]
369
+ idx_na_tuple = IntervalIndex.from_tuples(na_tuple)
370
+ idx_na_element = IntervalIndex.from_tuples([(0, 1), np.nan, (2, 3)])
371
+ tm.assert_index_equal(idx_na_tuple, idx_na_element)
372
+
373
+
374
+ class TestClassConstructors(ConstructorTests):
375
+ """Tests specific to the IntervalIndex/Index constructors"""
376
+
377
+ @pytest.fixture(
378
+ params=[IntervalIndex, partial(Index, dtype="interval")],
379
+ ids=["IntervalIndex", "Index"],
380
+ )
381
+ def klass(self, request):
382
+ # We use a separate fixture here to include Index.__new__ with dtype kwarg
383
+ return request.param
384
+
385
+ @pytest.fixture
386
+ def constructor(self):
387
+ return IntervalIndex
388
+
389
+ def get_kwargs_from_breaks(self, breaks, closed="right"):
390
+ """
391
+ converts intervals in breaks format to a dictionary of kwargs to
392
+ specific to the format expected by the IntervalIndex/Index constructors
393
+ """
394
+ if is_unsigned_integer_dtype(breaks):
395
+ pytest.skip(f"{breaks.dtype} not relevant for class constructor tests")
396
+
397
+ if len(breaks) == 0:
398
+ return {"data": breaks}
399
+
400
+ ivs = [
401
+ Interval(left, right, closed) if notna(left) else left
402
+ for left, right in zip(breaks[:-1], breaks[1:])
403
+ ]
404
+
405
+ if isinstance(breaks, list):
406
+ return {"data": ivs}
407
+ elif isinstance(getattr(breaks, "dtype", None), CategoricalDtype):
408
+ return {"data": breaks._constructor(ivs)}
409
+ return {"data": np.array(ivs, dtype=object)}
410
+
411
+ def test_generic_errors(self, constructor):
412
+ """
413
+ override the base class implementation since errors are handled
414
+ differently; checks unnecessary since caught at the Interval level
415
+ """
416
+
417
+ def test_constructor_string(self):
418
+ # GH23013
419
+ # When forming the interval from breaks,
420
+ # the interval of strings is already forbidden.
421
+ pass
422
+
423
+ def test_constructor_errors(self, klass):
424
+ # mismatched closed within intervals with no constructor override
425
+ ivs = [Interval(0, 1, closed="right"), Interval(2, 3, closed="left")]
426
+ msg = "intervals must all be closed on the same side"
427
+ with pytest.raises(ValueError, match=msg):
428
+ klass(ivs)
429
+
430
+ # scalar
431
+ msg = (
432
+ r"(IntervalIndex|Index)\(...\) must be called with a collection of "
433
+ "some kind, 5 was passed"
434
+ )
435
+ with pytest.raises(TypeError, match=msg):
436
+ klass(5)
437
+
438
+ # not an interval; dtype depends on 32bit/windows builds
439
+ msg = "type <class 'numpy.int(32|64)'> with value 0 is not an interval"
440
+ with pytest.raises(TypeError, match=msg):
441
+ klass([0, 1])
442
+
443
+ @pytest.mark.parametrize(
444
+ "data, closed",
445
+ [
446
+ ([], "both"),
447
+ ([np.nan, np.nan], "neither"),
448
+ (
449
+ [Interval(0, 3, closed="neither"), Interval(2, 5, closed="neither")],
450
+ "left",
451
+ ),
452
+ (
453
+ [Interval(0, 3, closed="left"), Interval(2, 5, closed="right")],
454
+ "neither",
455
+ ),
456
+ (IntervalIndex.from_breaks(range(5), closed="both"), "right"),
457
+ ],
458
+ )
459
+ def test_override_inferred_closed(self, constructor, data, closed):
460
+ # GH 19370
461
+ if isinstance(data, IntervalIndex):
462
+ tuples = data.to_tuples()
463
+ else:
464
+ tuples = [(iv.left, iv.right) if notna(iv) else iv for iv in data]
465
+ expected = IntervalIndex.from_tuples(tuples, closed=closed)
466
+ result = constructor(data, closed=closed)
467
+ tm.assert_index_equal(result, expected)
468
+
469
+ @pytest.mark.parametrize(
470
+ "values_constructor", [list, np.array, IntervalIndex, IntervalArray]
471
+ )
472
+ def test_index_object_dtype(self, values_constructor):
473
+ # Index(intervals, dtype=object) is an Index (not an IntervalIndex)
474
+ intervals = [Interval(0, 1), Interval(1, 2), Interval(2, 3)]
475
+ values = values_constructor(intervals)
476
+ result = Index(values, dtype=object)
477
+
478
+ assert type(result) is Index
479
+ tm.assert_numpy_array_equal(result.values, np.array(values))
480
+
481
+ def test_index_mixed_closed(self):
482
+ # GH27172
483
+ intervals = [
484
+ Interval(0, 1, closed="left"),
485
+ Interval(1, 2, closed="right"),
486
+ Interval(2, 3, closed="neither"),
487
+ Interval(3, 4, closed="both"),
488
+ ]
489
+ result = Index(intervals)
490
+ expected = Index(intervals, dtype=object)
491
+ tm.assert_index_equal(result, expected)
492
+
493
+
494
+ @pytest.mark.parametrize("timezone", ["UTC", "US/Pacific", "GMT"])
495
+ def test_interval_index_subtype(timezone, inclusive_endpoints_fixture):
496
+ # GH#46999
497
+ dates = date_range("2022", periods=3, tz=timezone)
498
+ dtype = f"interval[datetime64[ns, {timezone}], {inclusive_endpoints_fixture}]"
499
+ result = IntervalIndex.from_arrays(
500
+ ["2022-01-01", "2022-01-02"],
501
+ ["2022-01-02", "2022-01-03"],
502
+ closed=inclusive_endpoints_fixture,
503
+ dtype=dtype,
504
+ )
505
+ expected = IntervalIndex.from_arrays(
506
+ dates[:-1], dates[1:], closed=inclusive_endpoints_fixture
507
+ )
508
+ tm.assert_index_equal(result, expected)
509
+
510
+
511
+ def test_dtype_closed_mismatch():
512
+ # GH#38394 closed specified in both dtype and IntervalIndex constructor
513
+
514
+ dtype = IntervalDtype(np.int64, "left")
515
+
516
+ msg = "closed keyword does not match dtype.closed"
517
+ with pytest.raises(ValueError, match=msg):
518
+ IntervalIndex([], dtype=dtype, closed="neither")
519
+
520
+ with pytest.raises(ValueError, match=msg):
521
+ IntervalArray([], dtype=dtype, closed="neither")
522
+
523
+
524
+ @pytest.mark.parametrize(
525
+ "dtype",
526
+ ["Float64", pytest.param("float64[pyarrow]", marks=td.skip_if_no("pyarrow"))],
527
+ )
528
+ def test_ea_dtype(dtype):
529
+ # GH#56765
530
+ bins = [(0.0, 0.4), (0.4, 0.6)]
531
+ interval_dtype = IntervalDtype(subtype=dtype, closed="left")
532
+ result = IntervalIndex.from_tuples(bins, closed="left", dtype=interval_dtype)
533
+ assert result.dtype == interval_dtype
534
+ expected = IntervalIndex.from_tuples(bins, closed="left").astype(interval_dtype)
535
+ tm.assert_index_equal(result, expected)
lib/python3.10/site-packages/pandas/tests/indexes/interval/test_equals.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from pandas import (
4
+ IntervalIndex,
5
+ date_range,
6
+ )
7
+
8
+
9
+ class TestEquals:
10
+ def test_equals(self, closed):
11
+ expected = IntervalIndex.from_breaks(np.arange(5), closed=closed)
12
+ assert expected.equals(expected)
13
+ assert expected.equals(expected.copy())
14
+
15
+ assert not expected.equals(expected.astype(object))
16
+ assert not expected.equals(np.array(expected))
17
+ assert not expected.equals(list(expected))
18
+
19
+ assert not expected.equals([1, 2])
20
+ assert not expected.equals(np.array([1, 2]))
21
+ assert not expected.equals(date_range("20130101", periods=2))
22
+
23
+ expected_name1 = IntervalIndex.from_breaks(
24
+ np.arange(5), closed=closed, name="foo"
25
+ )
26
+ expected_name2 = IntervalIndex.from_breaks(
27
+ np.arange(5), closed=closed, name="bar"
28
+ )
29
+ assert expected.equals(expected_name1)
30
+ assert expected_name1.equals(expected_name2)
31
+
32
+ for other_closed in {"left", "right", "both", "neither"} - {closed}:
33
+ expected_other_closed = IntervalIndex.from_breaks(
34
+ np.arange(5), closed=other_closed
35
+ )
36
+ assert not expected.equals(expected_other_closed)
lib/python3.10/site-packages/pandas/tests/indexes/interval/test_formats.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas._config import using_pyarrow_string_dtype
5
+
6
+ from pandas import (
7
+ DataFrame,
8
+ DatetimeIndex,
9
+ Index,
10
+ Interval,
11
+ IntervalIndex,
12
+ Series,
13
+ Timedelta,
14
+ Timestamp,
15
+ )
16
+ import pandas._testing as tm
17
+
18
+
19
+ class TestIntervalIndexRendering:
20
+ # TODO: this is a test for DataFrame/Series, not IntervalIndex
21
+ @pytest.mark.parametrize(
22
+ "constructor,expected",
23
+ [
24
+ (
25
+ Series,
26
+ (
27
+ "(0.0, 1.0] a\n"
28
+ "NaN b\n"
29
+ "(2.0, 3.0] c\n"
30
+ "dtype: object"
31
+ ),
32
+ ),
33
+ (DataFrame, (" 0\n(0.0, 1.0] a\nNaN b\n(2.0, 3.0] c")),
34
+ ],
35
+ )
36
+ def test_repr_missing(self, constructor, expected, using_infer_string, request):
37
+ # GH 25984
38
+ if using_infer_string and constructor is Series:
39
+ request.applymarker(pytest.mark.xfail(reason="repr different"))
40
+ index = IntervalIndex.from_tuples([(0, 1), np.nan, (2, 3)])
41
+ obj = constructor(list("abc"), index=index)
42
+ result = repr(obj)
43
+ assert result == expected
44
+
45
+ @pytest.mark.xfail(using_pyarrow_string_dtype(), reason="repr different")
46
+ def test_repr_floats(self):
47
+ # GH 32553
48
+
49
+ markers = Series(
50
+ ["foo", "bar"],
51
+ index=IntervalIndex(
52
+ [
53
+ Interval(left, right)
54
+ for left, right in zip(
55
+ Index([329.973, 345.137], dtype="float64"),
56
+ Index([345.137, 360.191], dtype="float64"),
57
+ )
58
+ ]
59
+ ),
60
+ )
61
+ result = str(markers)
62
+ expected = "(329.973, 345.137] foo\n(345.137, 360.191] bar\ndtype: object"
63
+ assert result == expected
64
+
65
+ @pytest.mark.parametrize(
66
+ "tuples, closed, expected_data",
67
+ [
68
+ ([(0, 1), (1, 2), (2, 3)], "left", ["[0, 1)", "[1, 2)", "[2, 3)"]),
69
+ (
70
+ [(0.5, 1.0), np.nan, (2.0, 3.0)],
71
+ "right",
72
+ ["(0.5, 1.0]", "NaN", "(2.0, 3.0]"],
73
+ ),
74
+ (
75
+ [
76
+ (Timestamp("20180101"), Timestamp("20180102")),
77
+ np.nan,
78
+ ((Timestamp("20180102"), Timestamp("20180103"))),
79
+ ],
80
+ "both",
81
+ [
82
+ "[2018-01-01 00:00:00, 2018-01-02 00:00:00]",
83
+ "NaN",
84
+ "[2018-01-02 00:00:00, 2018-01-03 00:00:00]",
85
+ ],
86
+ ),
87
+ (
88
+ [
89
+ (Timedelta("0 days"), Timedelta("1 days")),
90
+ (Timedelta("1 days"), Timedelta("2 days")),
91
+ np.nan,
92
+ ],
93
+ "neither",
94
+ [
95
+ "(0 days 00:00:00, 1 days 00:00:00)",
96
+ "(1 days 00:00:00, 2 days 00:00:00)",
97
+ "NaN",
98
+ ],
99
+ ),
100
+ ],
101
+ )
102
+ def test_get_values_for_csv(self, tuples, closed, expected_data):
103
+ # GH 28210
104
+ index = IntervalIndex.from_tuples(tuples, closed=closed)
105
+ result = index._get_values_for_csv(na_rep="NaN")
106
+ expected = np.array(expected_data)
107
+ tm.assert_numpy_array_equal(result, expected)
108
+
109
+ def test_timestamp_with_timezone(self, unit):
110
+ # GH 55035
111
+ left = DatetimeIndex(["2020-01-01"], dtype=f"M8[{unit}, UTC]")
112
+ right = DatetimeIndex(["2020-01-02"], dtype=f"M8[{unit}, UTC]")
113
+ index = IntervalIndex.from_arrays(left, right)
114
+ result = repr(index)
115
+ expected = (
116
+ "IntervalIndex([(2020-01-01 00:00:00+00:00, 2020-01-02 00:00:00+00:00]], "
117
+ f"dtype='interval[datetime64[{unit}, UTC], right]')"
118
+ )
119
+ assert result == expected
lib/python3.10/site-packages/pandas/tests/indexes/interval/test_indexing.py ADDED
@@ -0,0 +1,671 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ from pandas.errors import InvalidIndexError
7
+
8
+ from pandas import (
9
+ NA,
10
+ CategoricalIndex,
11
+ DatetimeIndex,
12
+ Index,
13
+ Interval,
14
+ IntervalIndex,
15
+ MultiIndex,
16
+ NaT,
17
+ Timedelta,
18
+ Timestamp,
19
+ array,
20
+ date_range,
21
+ interval_range,
22
+ isna,
23
+ period_range,
24
+ timedelta_range,
25
+ )
26
+ import pandas._testing as tm
27
+
28
+
29
+ class TestGetItem:
30
+ def test_getitem(self, closed):
31
+ idx = IntervalIndex.from_arrays((0, 1, np.nan), (1, 2, np.nan), closed=closed)
32
+ assert idx[0] == Interval(0.0, 1.0, closed=closed)
33
+ assert idx[1] == Interval(1.0, 2.0, closed=closed)
34
+ assert isna(idx[2])
35
+
36
+ result = idx[0:1]
37
+ expected = IntervalIndex.from_arrays((0.0,), (1.0,), closed=closed)
38
+ tm.assert_index_equal(result, expected)
39
+
40
+ result = idx[0:2]
41
+ expected = IntervalIndex.from_arrays((0.0, 1), (1.0, 2.0), closed=closed)
42
+ tm.assert_index_equal(result, expected)
43
+
44
+ result = idx[1:3]
45
+ expected = IntervalIndex.from_arrays(
46
+ (1.0, np.nan), (2.0, np.nan), closed=closed
47
+ )
48
+ tm.assert_index_equal(result, expected)
49
+
50
+ def test_getitem_2d_deprecated(self):
51
+ # GH#30588 multi-dim indexing is deprecated, but raising is also acceptable
52
+ idx = IntervalIndex.from_breaks(range(11), closed="right")
53
+ with pytest.raises(ValueError, match="multi-dimensional indexing not allowed"):
54
+ idx[:, None]
55
+ with pytest.raises(ValueError, match="multi-dimensional indexing not allowed"):
56
+ # GH#44051
57
+ idx[True]
58
+ with pytest.raises(ValueError, match="multi-dimensional indexing not allowed"):
59
+ # GH#44051
60
+ idx[False]
61
+
62
+
63
+ class TestWhere:
64
+ def test_where(self, listlike_box):
65
+ klass = listlike_box
66
+
67
+ idx = IntervalIndex.from_breaks(range(11), closed="right")
68
+ cond = [True] * len(idx)
69
+ expected = idx
70
+ result = expected.where(klass(cond))
71
+ tm.assert_index_equal(result, expected)
72
+
73
+ cond = [False] + [True] * len(idx[1:])
74
+ expected = IntervalIndex([np.nan] + idx[1:].tolist())
75
+ result = idx.where(klass(cond))
76
+ tm.assert_index_equal(result, expected)
77
+
78
+
79
+ class TestTake:
80
+ def test_take(self, closed):
81
+ index = IntervalIndex.from_breaks(range(11), closed=closed)
82
+
83
+ result = index.take(range(10))
84
+ tm.assert_index_equal(result, index)
85
+
86
+ result = index.take([0, 0, 1])
87
+ expected = IntervalIndex.from_arrays([0, 0, 1], [1, 1, 2], closed=closed)
88
+ tm.assert_index_equal(result, expected)
89
+
90
+
91
+ class TestGetLoc:
92
+ @pytest.mark.parametrize("side", ["right", "left", "both", "neither"])
93
+ def test_get_loc_interval(self, closed, side):
94
+ idx = IntervalIndex.from_tuples([(0, 1), (2, 3)], closed=closed)
95
+
96
+ for bound in [[0, 1], [1, 2], [2, 3], [3, 4], [0, 2], [2.5, 3], [-1, 4]]:
97
+ # if get_loc is supplied an interval, it should only search
98
+ # for exact matches, not overlaps or covers, else KeyError.
99
+ msg = re.escape(f"Interval({bound[0]}, {bound[1]}, closed='{side}')")
100
+ if closed == side:
101
+ if bound == [0, 1]:
102
+ assert idx.get_loc(Interval(0, 1, closed=side)) == 0
103
+ elif bound == [2, 3]:
104
+ assert idx.get_loc(Interval(2, 3, closed=side)) == 1
105
+ else:
106
+ with pytest.raises(KeyError, match=msg):
107
+ idx.get_loc(Interval(*bound, closed=side))
108
+ else:
109
+ with pytest.raises(KeyError, match=msg):
110
+ idx.get_loc(Interval(*bound, closed=side))
111
+
112
+ @pytest.mark.parametrize("scalar", [-0.5, 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5])
113
+ def test_get_loc_scalar(self, closed, scalar):
114
+ # correct = {side: {query: answer}}.
115
+ # If query is not in the dict, that query should raise a KeyError
116
+ correct = {
117
+ "right": {0.5: 0, 1: 0, 2.5: 1, 3: 1},
118
+ "left": {0: 0, 0.5: 0, 2: 1, 2.5: 1},
119
+ "both": {0: 0, 0.5: 0, 1: 0, 2: 1, 2.5: 1, 3: 1},
120
+ "neither": {0.5: 0, 2.5: 1},
121
+ }
122
+
123
+ idx = IntervalIndex.from_tuples([(0, 1), (2, 3)], closed=closed)
124
+
125
+ # if get_loc is supplied a scalar, it should return the index of
126
+ # the interval which contains the scalar, or KeyError.
127
+ if scalar in correct[closed].keys():
128
+ assert idx.get_loc(scalar) == correct[closed][scalar]
129
+ else:
130
+ with pytest.raises(KeyError, match=str(scalar)):
131
+ idx.get_loc(scalar)
132
+
133
+ @pytest.mark.parametrize("scalar", [-1, 0, 0.5, 3, 4.5, 5, 6])
134
+ def test_get_loc_length_one_scalar(self, scalar, closed):
135
+ # GH 20921
136
+ index = IntervalIndex.from_tuples([(0, 5)], closed=closed)
137
+ if scalar in index[0]:
138
+ result = index.get_loc(scalar)
139
+ assert result == 0
140
+ else:
141
+ with pytest.raises(KeyError, match=str(scalar)):
142
+ index.get_loc(scalar)
143
+
144
+ @pytest.mark.parametrize("other_closed", ["left", "right", "both", "neither"])
145
+ @pytest.mark.parametrize("left, right", [(0, 5), (-1, 4), (-1, 6), (6, 7)])
146
+ def test_get_loc_length_one_interval(self, left, right, closed, other_closed):
147
+ # GH 20921
148
+ index = IntervalIndex.from_tuples([(0, 5)], closed=closed)
149
+ interval = Interval(left, right, closed=other_closed)
150
+ if interval == index[0]:
151
+ result = index.get_loc(interval)
152
+ assert result == 0
153
+ else:
154
+ with pytest.raises(
155
+ KeyError,
156
+ match=re.escape(f"Interval({left}, {right}, closed='{other_closed}')"),
157
+ ):
158
+ index.get_loc(interval)
159
+
160
+ # Make consistent with test_interval_new.py (see #16316, #16386)
161
+ @pytest.mark.parametrize(
162
+ "breaks",
163
+ [
164
+ date_range("20180101", periods=4),
165
+ date_range("20180101", periods=4, tz="US/Eastern"),
166
+ timedelta_range("0 days", periods=4),
167
+ ],
168
+ ids=lambda x: str(x.dtype),
169
+ )
170
+ def test_get_loc_datetimelike_nonoverlapping(self, breaks):
171
+ # GH 20636
172
+ # nonoverlapping = IntervalIndex method and no i8 conversion
173
+ index = IntervalIndex.from_breaks(breaks)
174
+
175
+ value = index[0].mid
176
+ result = index.get_loc(value)
177
+ expected = 0
178
+ assert result == expected
179
+
180
+ interval = Interval(index[0].left, index[0].right)
181
+ result = index.get_loc(interval)
182
+ expected = 0
183
+ assert result == expected
184
+
185
+ @pytest.mark.parametrize(
186
+ "arrays",
187
+ [
188
+ (date_range("20180101", periods=4), date_range("20180103", periods=4)),
189
+ (
190
+ date_range("20180101", periods=4, tz="US/Eastern"),
191
+ date_range("20180103", periods=4, tz="US/Eastern"),
192
+ ),
193
+ (
194
+ timedelta_range("0 days", periods=4),
195
+ timedelta_range("2 days", periods=4),
196
+ ),
197
+ ],
198
+ ids=lambda x: str(x[0].dtype),
199
+ )
200
+ def test_get_loc_datetimelike_overlapping(self, arrays):
201
+ # GH 20636
202
+ index = IntervalIndex.from_arrays(*arrays)
203
+
204
+ value = index[0].mid + Timedelta("12 hours")
205
+ result = index.get_loc(value)
206
+ expected = slice(0, 2, None)
207
+ assert result == expected
208
+
209
+ interval = Interval(index[0].left, index[0].right)
210
+ result = index.get_loc(interval)
211
+ expected = 0
212
+ assert result == expected
213
+
214
+ @pytest.mark.parametrize(
215
+ "values",
216
+ [
217
+ date_range("2018-01-04", periods=4, freq="-1D"),
218
+ date_range("2018-01-04", periods=4, freq="-1D", tz="US/Eastern"),
219
+ timedelta_range("3 days", periods=4, freq="-1D"),
220
+ np.arange(3.0, -1.0, -1.0),
221
+ np.arange(3, -1, -1),
222
+ ],
223
+ ids=lambda x: str(x.dtype),
224
+ )
225
+ def test_get_loc_decreasing(self, values):
226
+ # GH 25860
227
+ index = IntervalIndex.from_arrays(values[1:], values[:-1])
228
+ result = index.get_loc(index[0])
229
+ expected = 0
230
+ assert result == expected
231
+
232
+ @pytest.mark.parametrize("key", [[5], (2, 3)])
233
+ def test_get_loc_non_scalar_errors(self, key):
234
+ # GH 31117
235
+ idx = IntervalIndex.from_tuples([(1, 3), (2, 4), (3, 5), (7, 10), (3, 10)])
236
+
237
+ msg = str(key)
238
+ with pytest.raises(InvalidIndexError, match=msg):
239
+ idx.get_loc(key)
240
+
241
+ def test_get_indexer_with_nans(self):
242
+ # GH#41831
243
+ index = IntervalIndex([np.nan, Interval(1, 2), np.nan])
244
+
245
+ expected = np.array([True, False, True])
246
+ for key in [None, np.nan, NA]:
247
+ assert key in index
248
+ result = index.get_loc(key)
249
+ tm.assert_numpy_array_equal(result, expected)
250
+
251
+ for key in [NaT, np.timedelta64("NaT", "ns"), np.datetime64("NaT", "ns")]:
252
+ with pytest.raises(KeyError, match=str(key)):
253
+ index.get_loc(key)
254
+
255
+
256
+ class TestGetIndexer:
257
+ @pytest.mark.parametrize(
258
+ "query, expected",
259
+ [
260
+ ([Interval(2, 4, closed="right")], [1]),
261
+ ([Interval(2, 4, closed="left")], [-1]),
262
+ ([Interval(2, 4, closed="both")], [-1]),
263
+ ([Interval(2, 4, closed="neither")], [-1]),
264
+ ([Interval(1, 4, closed="right")], [-1]),
265
+ ([Interval(0, 4, closed="right")], [-1]),
266
+ ([Interval(0.5, 1.5, closed="right")], [-1]),
267
+ ([Interval(2, 4, closed="right"), Interval(0, 1, closed="right")], [1, -1]),
268
+ ([Interval(2, 4, closed="right"), Interval(2, 4, closed="right")], [1, 1]),
269
+ ([Interval(5, 7, closed="right"), Interval(2, 4, closed="right")], [2, 1]),
270
+ ([Interval(2, 4, closed="right"), Interval(2, 4, closed="left")], [1, -1]),
271
+ ],
272
+ )
273
+ def test_get_indexer_with_interval(self, query, expected):
274
+ tuples = [(0, 2), (2, 4), (5, 7)]
275
+ index = IntervalIndex.from_tuples(tuples, closed="right")
276
+
277
+ result = index.get_indexer(query)
278
+ expected = np.array(expected, dtype="intp")
279
+ tm.assert_numpy_array_equal(result, expected)
280
+
281
+ @pytest.mark.parametrize(
282
+ "query, expected",
283
+ [
284
+ ([-0.5], [-1]),
285
+ ([0], [-1]),
286
+ ([0.5], [0]),
287
+ ([1], [0]),
288
+ ([1.5], [1]),
289
+ ([2], [1]),
290
+ ([2.5], [-1]),
291
+ ([3], [-1]),
292
+ ([3.5], [2]),
293
+ ([4], [2]),
294
+ ([4.5], [-1]),
295
+ ([1, 2], [0, 1]),
296
+ ([1, 2, 3], [0, 1, -1]),
297
+ ([1, 2, 3, 4], [0, 1, -1, 2]),
298
+ ([1, 2, 3, 4, 2], [0, 1, -1, 2, 1]),
299
+ ],
300
+ )
301
+ def test_get_indexer_with_int_and_float(self, query, expected):
302
+ tuples = [(0, 1), (1, 2), (3, 4)]
303
+ index = IntervalIndex.from_tuples(tuples, closed="right")
304
+
305
+ result = index.get_indexer(query)
306
+ expected = np.array(expected, dtype="intp")
307
+ tm.assert_numpy_array_equal(result, expected)
308
+
309
+ @pytest.mark.parametrize("item", [[3], np.arange(0.5, 5, 0.5)])
310
+ def test_get_indexer_length_one(self, item, closed):
311
+ # GH 17284
312
+ index = IntervalIndex.from_tuples([(0, 5)], closed=closed)
313
+ result = index.get_indexer(item)
314
+ expected = np.array([0] * len(item), dtype="intp")
315
+ tm.assert_numpy_array_equal(result, expected)
316
+
317
+ @pytest.mark.parametrize("size", [1, 5])
318
+ def test_get_indexer_length_one_interval(self, size, closed):
319
+ # GH 17284
320
+ index = IntervalIndex.from_tuples([(0, 5)], closed=closed)
321
+ result = index.get_indexer([Interval(0, 5, closed)] * size)
322
+ expected = np.array([0] * size, dtype="intp")
323
+ tm.assert_numpy_array_equal(result, expected)
324
+
325
+ @pytest.mark.parametrize(
326
+ "target",
327
+ [
328
+ IntervalIndex.from_tuples([(7, 8), (1, 2), (3, 4), (0, 1)]),
329
+ IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4), np.nan]),
330
+ IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4)], closed="both"),
331
+ [-1, 0, 0.5, 1, 2, 2.5, np.nan],
332
+ ["foo", "foo", "bar", "baz"],
333
+ ],
334
+ )
335
+ def test_get_indexer_categorical(self, target, ordered):
336
+ # GH 30063: categorical and non-categorical results should be consistent
337
+ index = IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4)])
338
+ categorical_target = CategoricalIndex(target, ordered=ordered)
339
+
340
+ result = index.get_indexer(categorical_target)
341
+ expected = index.get_indexer(target)
342
+ tm.assert_numpy_array_equal(result, expected)
343
+
344
+ def test_get_indexer_categorical_with_nans(self):
345
+ # GH#41934 nans in both index and in target
346
+ ii = IntervalIndex.from_breaks(range(5))
347
+ ii2 = ii.append(IntervalIndex([np.nan]))
348
+ ci2 = CategoricalIndex(ii2)
349
+
350
+ result = ii2.get_indexer(ci2)
351
+ expected = np.arange(5, dtype=np.intp)
352
+ tm.assert_numpy_array_equal(result, expected)
353
+
354
+ # not-all-matches
355
+ result = ii2[1:].get_indexer(ci2[::-1])
356
+ expected = np.array([3, 2, 1, 0, -1], dtype=np.intp)
357
+ tm.assert_numpy_array_equal(result, expected)
358
+
359
+ # non-unique target, non-unique nans
360
+ result = ii2.get_indexer(ci2.append(ci2))
361
+ expected = np.array([0, 1, 2, 3, 4, 0, 1, 2, 3, 4], dtype=np.intp)
362
+ tm.assert_numpy_array_equal(result, expected)
363
+
364
+ def test_get_indexer_datetime(self):
365
+ ii = IntervalIndex.from_breaks(date_range("2018-01-01", periods=4))
366
+ # TODO: with mismatched resolution get_indexer currently raises;
367
+ # this should probably coerce?
368
+ target = DatetimeIndex(["2018-01-02"], dtype="M8[ns]")
369
+ result = ii.get_indexer(target)
370
+ expected = np.array([0], dtype=np.intp)
371
+ tm.assert_numpy_array_equal(result, expected)
372
+
373
+ result = ii.get_indexer(target.astype(str))
374
+ tm.assert_numpy_array_equal(result, expected)
375
+
376
+ # https://github.com/pandas-dev/pandas/issues/47772
377
+ result = ii.get_indexer(target.asi8)
378
+ expected = np.array([-1], dtype=np.intp)
379
+ tm.assert_numpy_array_equal(result, expected)
380
+
381
+ @pytest.mark.parametrize(
382
+ "tuples, closed",
383
+ [
384
+ ([(0, 2), (1, 3), (3, 4)], "neither"),
385
+ ([(0, 5), (1, 4), (6, 7)], "left"),
386
+ ([(0, 1), (0, 1), (1, 2)], "right"),
387
+ ([(0, 1), (2, 3), (3, 4)], "both"),
388
+ ],
389
+ )
390
+ def test_get_indexer_errors(self, tuples, closed):
391
+ # IntervalIndex needs non-overlapping for uniqueness when querying
392
+ index = IntervalIndex.from_tuples(tuples, closed=closed)
393
+
394
+ msg = (
395
+ "cannot handle overlapping indices; use "
396
+ "IntervalIndex.get_indexer_non_unique"
397
+ )
398
+ with pytest.raises(InvalidIndexError, match=msg):
399
+ index.get_indexer([0, 2])
400
+
401
+ @pytest.mark.parametrize(
402
+ "query, expected",
403
+ [
404
+ ([-0.5], ([-1], [0])),
405
+ ([0], ([0], [])),
406
+ ([0.5], ([0], [])),
407
+ ([1], ([0, 1], [])),
408
+ ([1.5], ([0, 1], [])),
409
+ ([2], ([0, 1, 2], [])),
410
+ ([2.5], ([1, 2], [])),
411
+ ([3], ([2], [])),
412
+ ([3.5], ([2], [])),
413
+ ([4], ([-1], [0])),
414
+ ([4.5], ([-1], [0])),
415
+ ([1, 2], ([0, 1, 0, 1, 2], [])),
416
+ ([1, 2, 3], ([0, 1, 0, 1, 2, 2], [])),
417
+ ([1, 2, 3, 4], ([0, 1, 0, 1, 2, 2, -1], [3])),
418
+ ([1, 2, 3, 4, 2], ([0, 1, 0, 1, 2, 2, -1, 0, 1, 2], [3])),
419
+ ],
420
+ )
421
+ def test_get_indexer_non_unique_with_int_and_float(self, query, expected):
422
+ tuples = [(0, 2.5), (1, 3), (2, 4)]
423
+ index = IntervalIndex.from_tuples(tuples, closed="left")
424
+
425
+ result_indexer, result_missing = index.get_indexer_non_unique(query)
426
+ expected_indexer = np.array(expected[0], dtype="intp")
427
+ expected_missing = np.array(expected[1], dtype="intp")
428
+
429
+ tm.assert_numpy_array_equal(result_indexer, expected_indexer)
430
+ tm.assert_numpy_array_equal(result_missing, expected_missing)
431
+
432
+ # TODO we may also want to test get_indexer for the case when
433
+ # the intervals are duplicated, decreasing, non-monotonic, etc..
434
+
435
+ def test_get_indexer_non_monotonic(self):
436
+ # GH 16410
437
+ idx1 = IntervalIndex.from_tuples([(2, 3), (4, 5), (0, 1)])
438
+ idx2 = IntervalIndex.from_tuples([(0, 1), (2, 3), (6, 7), (8, 9)])
439
+ result = idx1.get_indexer(idx2)
440
+ expected = np.array([2, 0, -1, -1], dtype=np.intp)
441
+ tm.assert_numpy_array_equal(result, expected)
442
+
443
+ result = idx1.get_indexer(idx1[1:])
444
+ expected = np.array([1, 2], dtype=np.intp)
445
+ tm.assert_numpy_array_equal(result, expected)
446
+
447
+ def test_get_indexer_with_nans(self):
448
+ # GH#41831
449
+ index = IntervalIndex([np.nan, np.nan])
450
+ other = IntervalIndex([np.nan])
451
+
452
+ assert not index._index_as_unique
453
+
454
+ result = index.get_indexer_for(other)
455
+ expected = np.array([0, 1], dtype=np.intp)
456
+ tm.assert_numpy_array_equal(result, expected)
457
+
458
+ def test_get_index_non_unique_non_monotonic(self):
459
+ # GH#44084 (root cause)
460
+ index = IntervalIndex.from_tuples(
461
+ [(0.0, 1.0), (1.0, 2.0), (0.0, 1.0), (1.0, 2.0)]
462
+ )
463
+
464
+ result, _ = index.get_indexer_non_unique([Interval(1.0, 2.0)])
465
+ expected = np.array([1, 3], dtype=np.intp)
466
+ tm.assert_numpy_array_equal(result, expected)
467
+
468
+ def test_get_indexer_multiindex_with_intervals(self):
469
+ # GH#44084 (MultiIndex case as reported)
470
+ interval_index = IntervalIndex.from_tuples(
471
+ [(2.0, 3.0), (0.0, 1.0), (1.0, 2.0)], name="interval"
472
+ )
473
+ foo_index = Index([1, 2, 3], name="foo")
474
+
475
+ multi_index = MultiIndex.from_product([foo_index, interval_index])
476
+
477
+ result = multi_index.get_level_values("interval").get_indexer_for(
478
+ [Interval(0.0, 1.0)]
479
+ )
480
+ expected = np.array([1, 4, 7], dtype=np.intp)
481
+ tm.assert_numpy_array_equal(result, expected)
482
+
483
+ @pytest.mark.parametrize("box", [IntervalIndex, array, list])
484
+ def test_get_indexer_interval_index(self, box):
485
+ # GH#30178
486
+ rng = period_range("2022-07-01", freq="D", periods=3)
487
+ idx = box(interval_range(Timestamp("2022-07-01"), freq="3D", periods=3))
488
+
489
+ actual = rng.get_indexer(idx)
490
+ expected = np.array([-1, -1, -1], dtype=np.intp)
491
+ tm.assert_numpy_array_equal(actual, expected)
492
+
493
+ def test_get_indexer_read_only(self):
494
+ idx = interval_range(start=0, end=5)
495
+ arr = np.array([1, 2])
496
+ arr.flags.writeable = False
497
+ result = idx.get_indexer(arr)
498
+ expected = np.array([0, 1])
499
+ tm.assert_numpy_array_equal(result, expected, check_dtype=False)
500
+
501
+ result = idx.get_indexer_non_unique(arr)[0]
502
+ tm.assert_numpy_array_equal(result, expected, check_dtype=False)
503
+
504
+
505
+ class TestSliceLocs:
506
+ def test_slice_locs_with_interval(self):
507
+ # increasing monotonically
508
+ index = IntervalIndex.from_tuples([(0, 2), (1, 3), (2, 4)])
509
+
510
+ assert index.slice_locs(start=Interval(0, 2), end=Interval(2, 4)) == (0, 3)
511
+ assert index.slice_locs(start=Interval(0, 2)) == (0, 3)
512
+ assert index.slice_locs(end=Interval(2, 4)) == (0, 3)
513
+ assert index.slice_locs(end=Interval(0, 2)) == (0, 1)
514
+ assert index.slice_locs(start=Interval(2, 4), end=Interval(0, 2)) == (2, 1)
515
+
516
+ # decreasing monotonically
517
+ index = IntervalIndex.from_tuples([(2, 4), (1, 3), (0, 2)])
518
+
519
+ assert index.slice_locs(start=Interval(0, 2), end=Interval(2, 4)) == (2, 1)
520
+ assert index.slice_locs(start=Interval(0, 2)) == (2, 3)
521
+ assert index.slice_locs(end=Interval(2, 4)) == (0, 1)
522
+ assert index.slice_locs(end=Interval(0, 2)) == (0, 3)
523
+ assert index.slice_locs(start=Interval(2, 4), end=Interval(0, 2)) == (0, 3)
524
+
525
+ # sorted duplicates
526
+ index = IntervalIndex.from_tuples([(0, 2), (0, 2), (2, 4)])
527
+
528
+ assert index.slice_locs(start=Interval(0, 2), end=Interval(2, 4)) == (0, 3)
529
+ assert index.slice_locs(start=Interval(0, 2)) == (0, 3)
530
+ assert index.slice_locs(end=Interval(2, 4)) == (0, 3)
531
+ assert index.slice_locs(end=Interval(0, 2)) == (0, 2)
532
+ assert index.slice_locs(start=Interval(2, 4), end=Interval(0, 2)) == (2, 2)
533
+
534
+ # unsorted duplicates
535
+ index = IntervalIndex.from_tuples([(0, 2), (2, 4), (0, 2)])
536
+
537
+ with pytest.raises(
538
+ KeyError,
539
+ match=re.escape(
540
+ '"Cannot get left slice bound for non-unique label: '
541
+ "Interval(0, 2, closed='right')\""
542
+ ),
543
+ ):
544
+ index.slice_locs(start=Interval(0, 2), end=Interval(2, 4))
545
+
546
+ with pytest.raises(
547
+ KeyError,
548
+ match=re.escape(
549
+ '"Cannot get left slice bound for non-unique label: '
550
+ "Interval(0, 2, closed='right')\""
551
+ ),
552
+ ):
553
+ index.slice_locs(start=Interval(0, 2))
554
+
555
+ assert index.slice_locs(end=Interval(2, 4)) == (0, 2)
556
+
557
+ with pytest.raises(
558
+ KeyError,
559
+ match=re.escape(
560
+ '"Cannot get right slice bound for non-unique label: '
561
+ "Interval(0, 2, closed='right')\""
562
+ ),
563
+ ):
564
+ index.slice_locs(end=Interval(0, 2))
565
+
566
+ with pytest.raises(
567
+ KeyError,
568
+ match=re.escape(
569
+ '"Cannot get right slice bound for non-unique label: '
570
+ "Interval(0, 2, closed='right')\""
571
+ ),
572
+ ):
573
+ index.slice_locs(start=Interval(2, 4), end=Interval(0, 2))
574
+
575
+ # another unsorted duplicates
576
+ index = IntervalIndex.from_tuples([(0, 2), (0, 2), (2, 4), (1, 3)])
577
+
578
+ assert index.slice_locs(start=Interval(0, 2), end=Interval(2, 4)) == (0, 3)
579
+ assert index.slice_locs(start=Interval(0, 2)) == (0, 4)
580
+ assert index.slice_locs(end=Interval(2, 4)) == (0, 3)
581
+ assert index.slice_locs(end=Interval(0, 2)) == (0, 2)
582
+ assert index.slice_locs(start=Interval(2, 4), end=Interval(0, 2)) == (2, 2)
583
+
584
+ def test_slice_locs_with_ints_and_floats_succeeds(self):
585
+ # increasing non-overlapping
586
+ index = IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4)])
587
+
588
+ assert index.slice_locs(0, 1) == (0, 1)
589
+ assert index.slice_locs(0, 2) == (0, 2)
590
+ assert index.slice_locs(0, 3) == (0, 2)
591
+ assert index.slice_locs(3, 1) == (2, 1)
592
+ assert index.slice_locs(3, 4) == (2, 3)
593
+ assert index.slice_locs(0, 4) == (0, 3)
594
+
595
+ # decreasing non-overlapping
596
+ index = IntervalIndex.from_tuples([(3, 4), (1, 2), (0, 1)])
597
+ assert index.slice_locs(0, 1) == (3, 3)
598
+ assert index.slice_locs(0, 2) == (3, 2)
599
+ assert index.slice_locs(0, 3) == (3, 1)
600
+ assert index.slice_locs(3, 1) == (1, 3)
601
+ assert index.slice_locs(3, 4) == (1, 1)
602
+ assert index.slice_locs(0, 4) == (3, 1)
603
+
604
+ @pytest.mark.parametrize("query", [[0, 1], [0, 2], [0, 3], [0, 4]])
605
+ @pytest.mark.parametrize(
606
+ "tuples",
607
+ [
608
+ [(0, 2), (1, 3), (2, 4)],
609
+ [(2, 4), (1, 3), (0, 2)],
610
+ [(0, 2), (0, 2), (2, 4)],
611
+ [(0, 2), (2, 4), (0, 2)],
612
+ [(0, 2), (0, 2), (2, 4), (1, 3)],
613
+ ],
614
+ )
615
+ def test_slice_locs_with_ints_and_floats_errors(self, tuples, query):
616
+ start, stop = query
617
+ index = IntervalIndex.from_tuples(tuples)
618
+ with pytest.raises(
619
+ KeyError,
620
+ match=(
621
+ "'can only get slices from an IntervalIndex if bounds are "
622
+ "non-overlapping and all monotonic increasing or decreasing'"
623
+ ),
624
+ ):
625
+ index.slice_locs(start, stop)
626
+
627
+
628
+ class TestPutmask:
629
+ @pytest.mark.parametrize("tz", ["US/Pacific", None])
630
+ def test_putmask_dt64(self, tz):
631
+ # GH#37968
632
+ dti = date_range("2016-01-01", periods=9, tz=tz)
633
+ idx = IntervalIndex.from_breaks(dti)
634
+ mask = np.zeros(idx.shape, dtype=bool)
635
+ mask[0:3] = True
636
+
637
+ result = idx.putmask(mask, idx[-1])
638
+ expected = IntervalIndex([idx[-1]] * 3 + list(idx[3:]))
639
+ tm.assert_index_equal(result, expected)
640
+
641
+ def test_putmask_td64(self):
642
+ # GH#37968
643
+ dti = date_range("2016-01-01", periods=9)
644
+ tdi = dti - dti[0]
645
+ idx = IntervalIndex.from_breaks(tdi)
646
+ mask = np.zeros(idx.shape, dtype=bool)
647
+ mask[0:3] = True
648
+
649
+ result = idx.putmask(mask, idx[-1])
650
+ expected = IntervalIndex([idx[-1]] * 3 + list(idx[3:]))
651
+ tm.assert_index_equal(result, expected)
652
+
653
+
654
+ class TestContains:
655
+ # .__contains__, not .contains
656
+
657
+ def test_contains_dunder(self):
658
+ index = IntervalIndex.from_arrays([0, 1], [1, 2], closed="right")
659
+
660
+ # __contains__ requires perfect matches to intervals.
661
+ assert 0 not in index
662
+ assert 1 not in index
663
+ assert 2 not in index
664
+
665
+ assert Interval(0, 1, closed="right") in index
666
+ assert Interval(0, 2, closed="right") not in index
667
+ assert Interval(0, 0.5, closed="right") not in index
668
+ assert Interval(3, 5, closed="right") not in index
669
+ assert Interval(-1, 0, closed="left") not in index
670
+ assert Interval(0, 1, closed="left") not in index
671
+ assert Interval(0, 1, closed="both") not in index
lib/python3.10/site-packages/pandas/tests/indexes/interval/test_interval.py ADDED
@@ -0,0 +1,918 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import permutations
2
+ import re
3
+
4
+ import numpy as np
5
+ import pytest
6
+
7
+ import pandas as pd
8
+ from pandas import (
9
+ Index,
10
+ Interval,
11
+ IntervalIndex,
12
+ Timedelta,
13
+ Timestamp,
14
+ date_range,
15
+ interval_range,
16
+ isna,
17
+ notna,
18
+ timedelta_range,
19
+ )
20
+ import pandas._testing as tm
21
+ import pandas.core.common as com
22
+
23
+
24
+ @pytest.fixture(params=[None, "foo"])
25
+ def name(request):
26
+ return request.param
27
+
28
+
29
+ class TestIntervalIndex:
30
+ index = IntervalIndex.from_arrays([0, 1], [1, 2])
31
+
32
+ def create_index(self, closed="right"):
33
+ return IntervalIndex.from_breaks(range(11), closed=closed)
34
+
35
+ def create_index_with_nan(self, closed="right"):
36
+ mask = [True, False] + [True] * 8
37
+ return IntervalIndex.from_arrays(
38
+ np.where(mask, np.arange(10), np.nan),
39
+ np.where(mask, np.arange(1, 11), np.nan),
40
+ closed=closed,
41
+ )
42
+
43
+ def test_properties(self, closed):
44
+ index = self.create_index(closed=closed)
45
+ assert len(index) == 10
46
+ assert index.size == 10
47
+ assert index.shape == (10,)
48
+
49
+ tm.assert_index_equal(index.left, Index(np.arange(10, dtype=np.int64)))
50
+ tm.assert_index_equal(index.right, Index(np.arange(1, 11, dtype=np.int64)))
51
+ tm.assert_index_equal(index.mid, Index(np.arange(0.5, 10.5, dtype=np.float64)))
52
+
53
+ assert index.closed == closed
54
+
55
+ ivs = [
56
+ Interval(left, right, closed)
57
+ for left, right in zip(range(10), range(1, 11))
58
+ ]
59
+ expected = np.array(ivs, dtype=object)
60
+ tm.assert_numpy_array_equal(np.asarray(index), expected)
61
+
62
+ # with nans
63
+ index = self.create_index_with_nan(closed=closed)
64
+ assert len(index) == 10
65
+ assert index.size == 10
66
+ assert index.shape == (10,)
67
+
68
+ expected_left = Index([0, np.nan, 2, 3, 4, 5, 6, 7, 8, 9])
69
+ expected_right = expected_left + 1
70
+ expected_mid = expected_left + 0.5
71
+ tm.assert_index_equal(index.left, expected_left)
72
+ tm.assert_index_equal(index.right, expected_right)
73
+ tm.assert_index_equal(index.mid, expected_mid)
74
+
75
+ assert index.closed == closed
76
+
77
+ ivs = [
78
+ Interval(left, right, closed) if notna(left) else np.nan
79
+ for left, right in zip(expected_left, expected_right)
80
+ ]
81
+ expected = np.array(ivs, dtype=object)
82
+ tm.assert_numpy_array_equal(np.asarray(index), expected)
83
+
84
+ @pytest.mark.parametrize(
85
+ "breaks",
86
+ [
87
+ [1, 1, 2, 5, 15, 53, 217, 1014, 5335, 31240, 201608],
88
+ [-np.inf, -100, -10, 0.5, 1, 1.5, 3.8, 101, 202, np.inf],
89
+ date_range("2017-01-01", "2017-01-04"),
90
+ pytest.param(
91
+ date_range("2017-01-01", "2017-01-04", unit="s"),
92
+ marks=pytest.mark.xfail(reason="mismatched result unit"),
93
+ ),
94
+ pd.to_timedelta(["1ns", "2ms", "3s", "4min", "5h", "6D"]),
95
+ ],
96
+ )
97
+ def test_length(self, closed, breaks):
98
+ # GH 18789
99
+ index = IntervalIndex.from_breaks(breaks, closed=closed)
100
+ result = index.length
101
+ expected = Index(iv.length for iv in index)
102
+ tm.assert_index_equal(result, expected)
103
+
104
+ # with NA
105
+ index = index.insert(1, np.nan)
106
+ result = index.length
107
+ expected = Index(iv.length if notna(iv) else iv for iv in index)
108
+ tm.assert_index_equal(result, expected)
109
+
110
+ def test_with_nans(self, closed):
111
+ index = self.create_index(closed=closed)
112
+ assert index.hasnans is False
113
+
114
+ result = index.isna()
115
+ expected = np.zeros(len(index), dtype=bool)
116
+ tm.assert_numpy_array_equal(result, expected)
117
+
118
+ result = index.notna()
119
+ expected = np.ones(len(index), dtype=bool)
120
+ tm.assert_numpy_array_equal(result, expected)
121
+
122
+ index = self.create_index_with_nan(closed=closed)
123
+ assert index.hasnans is True
124
+
125
+ result = index.isna()
126
+ expected = np.array([False, True] + [False] * (len(index) - 2))
127
+ tm.assert_numpy_array_equal(result, expected)
128
+
129
+ result = index.notna()
130
+ expected = np.array([True, False] + [True] * (len(index) - 2))
131
+ tm.assert_numpy_array_equal(result, expected)
132
+
133
+ def test_copy(self, closed):
134
+ expected = self.create_index(closed=closed)
135
+
136
+ result = expected.copy()
137
+ assert result.equals(expected)
138
+
139
+ result = expected.copy(deep=True)
140
+ assert result.equals(expected)
141
+ assert result.left is not expected.left
142
+
143
+ def test_ensure_copied_data(self, closed):
144
+ # exercise the copy flag in the constructor
145
+
146
+ # not copying
147
+ index = self.create_index(closed=closed)
148
+ result = IntervalIndex(index, copy=False)
149
+ tm.assert_numpy_array_equal(
150
+ index.left.values, result.left.values, check_same="same"
151
+ )
152
+ tm.assert_numpy_array_equal(
153
+ index.right.values, result.right.values, check_same="same"
154
+ )
155
+
156
+ # by-definition make a copy
157
+ result = IntervalIndex(np.array(index), copy=False)
158
+ tm.assert_numpy_array_equal(
159
+ index.left.values, result.left.values, check_same="copy"
160
+ )
161
+ tm.assert_numpy_array_equal(
162
+ index.right.values, result.right.values, check_same="copy"
163
+ )
164
+
165
+ def test_delete(self, closed):
166
+ breaks = np.arange(1, 11, dtype=np.int64)
167
+ expected = IntervalIndex.from_breaks(breaks, closed=closed)
168
+ result = self.create_index(closed=closed).delete(0)
169
+ tm.assert_index_equal(result, expected)
170
+
171
+ @pytest.mark.parametrize(
172
+ "data",
173
+ [
174
+ interval_range(0, periods=10, closed="neither"),
175
+ interval_range(1.7, periods=8, freq=2.5, closed="both"),
176
+ interval_range(Timestamp("20170101"), periods=12, closed="left"),
177
+ interval_range(Timedelta("1 day"), periods=6, closed="right"),
178
+ ],
179
+ )
180
+ def test_insert(self, data):
181
+ item = data[0]
182
+ idx_item = IntervalIndex([item])
183
+
184
+ # start
185
+ expected = idx_item.append(data)
186
+ result = data.insert(0, item)
187
+ tm.assert_index_equal(result, expected)
188
+
189
+ # end
190
+ expected = data.append(idx_item)
191
+ result = data.insert(len(data), item)
192
+ tm.assert_index_equal(result, expected)
193
+
194
+ # mid
195
+ expected = data[:3].append(idx_item).append(data[3:])
196
+ result = data.insert(3, item)
197
+ tm.assert_index_equal(result, expected)
198
+
199
+ # invalid type
200
+ res = data.insert(1, "foo")
201
+ expected = data.astype(object).insert(1, "foo")
202
+ tm.assert_index_equal(res, expected)
203
+
204
+ msg = "can only insert Interval objects and NA into an IntervalArray"
205
+ with pytest.raises(TypeError, match=msg):
206
+ data._data.insert(1, "foo")
207
+
208
+ # invalid closed
209
+ msg = "'value.closed' is 'left', expected 'right'."
210
+ for closed in {"left", "right", "both", "neither"} - {item.closed}:
211
+ msg = f"'value.closed' is '{closed}', expected '{item.closed}'."
212
+ bad_item = Interval(item.left, item.right, closed=closed)
213
+ res = data.insert(1, bad_item)
214
+ expected = data.astype(object).insert(1, bad_item)
215
+ tm.assert_index_equal(res, expected)
216
+ with pytest.raises(ValueError, match=msg):
217
+ data._data.insert(1, bad_item)
218
+
219
+ # GH 18295 (test missing)
220
+ na_idx = IntervalIndex([np.nan], closed=data.closed)
221
+ for na in [np.nan, None, pd.NA]:
222
+ expected = data[:1].append(na_idx).append(data[1:])
223
+ result = data.insert(1, na)
224
+ tm.assert_index_equal(result, expected)
225
+
226
+ if data.left.dtype.kind not in ["m", "M"]:
227
+ # trying to insert pd.NaT into a numeric-dtyped Index should cast
228
+ expected = data.astype(object).insert(1, pd.NaT)
229
+
230
+ msg = "can only insert Interval objects and NA into an IntervalArray"
231
+ with pytest.raises(TypeError, match=msg):
232
+ data._data.insert(1, pd.NaT)
233
+
234
+ result = data.insert(1, pd.NaT)
235
+ tm.assert_index_equal(result, expected)
236
+
237
+ def test_is_unique_interval(self, closed):
238
+ """
239
+ Interval specific tests for is_unique in addition to base class tests
240
+ """
241
+ # unique overlapping - distinct endpoints
242
+ idx = IntervalIndex.from_tuples([(0, 1), (0.5, 1.5)], closed=closed)
243
+ assert idx.is_unique is True
244
+
245
+ # unique overlapping - shared endpoints
246
+ idx = IntervalIndex.from_tuples([(1, 2), (1, 3), (2, 3)], closed=closed)
247
+ assert idx.is_unique is True
248
+
249
+ # unique nested
250
+ idx = IntervalIndex.from_tuples([(-1, 1), (-2, 2)], closed=closed)
251
+ assert idx.is_unique is True
252
+
253
+ # unique NaN
254
+ idx = IntervalIndex.from_tuples([(np.nan, np.nan)], closed=closed)
255
+ assert idx.is_unique is True
256
+
257
+ # non-unique NaN
258
+ idx = IntervalIndex.from_tuples(
259
+ [(np.nan, np.nan), (np.nan, np.nan)], closed=closed
260
+ )
261
+ assert idx.is_unique is False
262
+
263
+ def test_monotonic(self, closed):
264
+ # increasing non-overlapping
265
+ idx = IntervalIndex.from_tuples([(0, 1), (2, 3), (4, 5)], closed=closed)
266
+ assert idx.is_monotonic_increasing is True
267
+ assert idx._is_strictly_monotonic_increasing is True
268
+ assert idx.is_monotonic_decreasing is False
269
+ assert idx._is_strictly_monotonic_decreasing is False
270
+
271
+ # decreasing non-overlapping
272
+ idx = IntervalIndex.from_tuples([(4, 5), (2, 3), (1, 2)], closed=closed)
273
+ assert idx.is_monotonic_increasing is False
274
+ assert idx._is_strictly_monotonic_increasing is False
275
+ assert idx.is_monotonic_decreasing is True
276
+ assert idx._is_strictly_monotonic_decreasing is True
277
+
278
+ # unordered non-overlapping
279
+ idx = IntervalIndex.from_tuples([(0, 1), (4, 5), (2, 3)], closed=closed)
280
+ assert idx.is_monotonic_increasing is False
281
+ assert idx._is_strictly_monotonic_increasing is False
282
+ assert idx.is_monotonic_decreasing is False
283
+ assert idx._is_strictly_monotonic_decreasing is False
284
+
285
+ # increasing overlapping
286
+ idx = IntervalIndex.from_tuples([(0, 2), (0.5, 2.5), (1, 3)], closed=closed)
287
+ assert idx.is_monotonic_increasing is True
288
+ assert idx._is_strictly_monotonic_increasing is True
289
+ assert idx.is_monotonic_decreasing is False
290
+ assert idx._is_strictly_monotonic_decreasing is False
291
+
292
+ # decreasing overlapping
293
+ idx = IntervalIndex.from_tuples([(1, 3), (0.5, 2.5), (0, 2)], closed=closed)
294
+ assert idx.is_monotonic_increasing is False
295
+ assert idx._is_strictly_monotonic_increasing is False
296
+ assert idx.is_monotonic_decreasing is True
297
+ assert idx._is_strictly_monotonic_decreasing is True
298
+
299
+ # unordered overlapping
300
+ idx = IntervalIndex.from_tuples([(0.5, 2.5), (0, 2), (1, 3)], closed=closed)
301
+ assert idx.is_monotonic_increasing is False
302
+ assert idx._is_strictly_monotonic_increasing is False
303
+ assert idx.is_monotonic_decreasing is False
304
+ assert idx._is_strictly_monotonic_decreasing is False
305
+
306
+ # increasing overlapping shared endpoints
307
+ idx = IntervalIndex.from_tuples([(1, 2), (1, 3), (2, 3)], closed=closed)
308
+ assert idx.is_monotonic_increasing is True
309
+ assert idx._is_strictly_monotonic_increasing is True
310
+ assert idx.is_monotonic_decreasing is False
311
+ assert idx._is_strictly_monotonic_decreasing is False
312
+
313
+ # decreasing overlapping shared endpoints
314
+ idx = IntervalIndex.from_tuples([(2, 3), (1, 3), (1, 2)], closed=closed)
315
+ assert idx.is_monotonic_increasing is False
316
+ assert idx._is_strictly_monotonic_increasing is False
317
+ assert idx.is_monotonic_decreasing is True
318
+ assert idx._is_strictly_monotonic_decreasing is True
319
+
320
+ # stationary
321
+ idx = IntervalIndex.from_tuples([(0, 1), (0, 1)], closed=closed)
322
+ assert idx.is_monotonic_increasing is True
323
+ assert idx._is_strictly_monotonic_increasing is False
324
+ assert idx.is_monotonic_decreasing is True
325
+ assert idx._is_strictly_monotonic_decreasing is False
326
+
327
+ # empty
328
+ idx = IntervalIndex([], closed=closed)
329
+ assert idx.is_monotonic_increasing is True
330
+ assert idx._is_strictly_monotonic_increasing is True
331
+ assert idx.is_monotonic_decreasing is True
332
+ assert idx._is_strictly_monotonic_decreasing is True
333
+
334
+ def test_is_monotonic_with_nans(self):
335
+ # GH#41831
336
+ index = IntervalIndex([np.nan, np.nan])
337
+
338
+ assert not index.is_monotonic_increasing
339
+ assert not index._is_strictly_monotonic_increasing
340
+ assert not index.is_monotonic_increasing
341
+ assert not index._is_strictly_monotonic_decreasing
342
+ assert not index.is_monotonic_decreasing
343
+
344
+ @pytest.mark.parametrize(
345
+ "breaks",
346
+ [
347
+ date_range("20180101", periods=4),
348
+ date_range("20180101", periods=4, tz="US/Eastern"),
349
+ timedelta_range("0 days", periods=4),
350
+ ],
351
+ ids=lambda x: str(x.dtype),
352
+ )
353
+ def test_maybe_convert_i8(self, breaks):
354
+ # GH 20636
355
+ index = IntervalIndex.from_breaks(breaks)
356
+
357
+ # intervalindex
358
+ result = index._maybe_convert_i8(index)
359
+ expected = IntervalIndex.from_breaks(breaks.asi8)
360
+ tm.assert_index_equal(result, expected)
361
+
362
+ # interval
363
+ interval = Interval(breaks[0], breaks[1])
364
+ result = index._maybe_convert_i8(interval)
365
+ expected = Interval(breaks[0]._value, breaks[1]._value)
366
+ assert result == expected
367
+
368
+ # datetimelike index
369
+ result = index._maybe_convert_i8(breaks)
370
+ expected = Index(breaks.asi8)
371
+ tm.assert_index_equal(result, expected)
372
+
373
+ # datetimelike scalar
374
+ result = index._maybe_convert_i8(breaks[0])
375
+ expected = breaks[0]._value
376
+ assert result == expected
377
+
378
+ # list-like of datetimelike scalars
379
+ result = index._maybe_convert_i8(list(breaks))
380
+ expected = Index(breaks.asi8)
381
+ tm.assert_index_equal(result, expected)
382
+
383
+ @pytest.mark.parametrize(
384
+ "breaks",
385
+ [date_range("2018-01-01", periods=5), timedelta_range("0 days", periods=5)],
386
+ )
387
+ def test_maybe_convert_i8_nat(self, breaks):
388
+ # GH 20636
389
+ index = IntervalIndex.from_breaks(breaks)
390
+
391
+ to_convert = breaks._constructor([pd.NaT] * 3).as_unit("ns")
392
+ expected = Index([np.nan] * 3, dtype=np.float64)
393
+ result = index._maybe_convert_i8(to_convert)
394
+ tm.assert_index_equal(result, expected)
395
+
396
+ to_convert = to_convert.insert(0, breaks[0])
397
+ expected = expected.insert(0, float(breaks[0]._value))
398
+ result = index._maybe_convert_i8(to_convert)
399
+ tm.assert_index_equal(result, expected)
400
+
401
+ @pytest.mark.parametrize(
402
+ "make_key",
403
+ [lambda breaks: breaks, list],
404
+ ids=["lambda", "list"],
405
+ )
406
+ def test_maybe_convert_i8_numeric(self, make_key, any_real_numpy_dtype):
407
+ # GH 20636
408
+ breaks = np.arange(5, dtype=any_real_numpy_dtype)
409
+ index = IntervalIndex.from_breaks(breaks)
410
+ key = make_key(breaks)
411
+
412
+ result = index._maybe_convert_i8(key)
413
+ kind = breaks.dtype.kind
414
+ expected_dtype = {"i": np.int64, "u": np.uint64, "f": np.float64}[kind]
415
+ expected = Index(key, dtype=expected_dtype)
416
+ tm.assert_index_equal(result, expected)
417
+
418
+ @pytest.mark.parametrize(
419
+ "make_key",
420
+ [
421
+ IntervalIndex.from_breaks,
422
+ lambda breaks: Interval(breaks[0], breaks[1]),
423
+ lambda breaks: breaks[0],
424
+ ],
425
+ ids=["IntervalIndex", "Interval", "scalar"],
426
+ )
427
+ def test_maybe_convert_i8_numeric_identical(self, make_key, any_real_numpy_dtype):
428
+ # GH 20636
429
+ breaks = np.arange(5, dtype=any_real_numpy_dtype)
430
+ index = IntervalIndex.from_breaks(breaks)
431
+ key = make_key(breaks)
432
+
433
+ # test if _maybe_convert_i8 won't change key if an Interval or IntervalIndex
434
+ result = index._maybe_convert_i8(key)
435
+ assert result is key
436
+
437
+ @pytest.mark.parametrize(
438
+ "breaks1, breaks2",
439
+ permutations(
440
+ [
441
+ date_range("20180101", periods=4),
442
+ date_range("20180101", periods=4, tz="US/Eastern"),
443
+ timedelta_range("0 days", periods=4),
444
+ ],
445
+ 2,
446
+ ),
447
+ ids=lambda x: str(x.dtype),
448
+ )
449
+ @pytest.mark.parametrize(
450
+ "make_key",
451
+ [
452
+ IntervalIndex.from_breaks,
453
+ lambda breaks: Interval(breaks[0], breaks[1]),
454
+ lambda breaks: breaks,
455
+ lambda breaks: breaks[0],
456
+ list,
457
+ ],
458
+ ids=["IntervalIndex", "Interval", "Index", "scalar", "list"],
459
+ )
460
+ def test_maybe_convert_i8_errors(self, breaks1, breaks2, make_key):
461
+ # GH 20636
462
+ index = IntervalIndex.from_breaks(breaks1)
463
+ key = make_key(breaks2)
464
+
465
+ msg = (
466
+ f"Cannot index an IntervalIndex of subtype {breaks1.dtype} with "
467
+ f"values of dtype {breaks2.dtype}"
468
+ )
469
+ msg = re.escape(msg)
470
+ with pytest.raises(ValueError, match=msg):
471
+ index._maybe_convert_i8(key)
472
+
473
+ def test_contains_method(self):
474
+ # can select values that are IN the range of a value
475
+ i = IntervalIndex.from_arrays([0, 1], [1, 2])
476
+
477
+ expected = np.array([False, False], dtype="bool")
478
+ actual = i.contains(0)
479
+ tm.assert_numpy_array_equal(actual, expected)
480
+ actual = i.contains(3)
481
+ tm.assert_numpy_array_equal(actual, expected)
482
+
483
+ expected = np.array([True, False], dtype="bool")
484
+ actual = i.contains(0.5)
485
+ tm.assert_numpy_array_equal(actual, expected)
486
+ actual = i.contains(1)
487
+ tm.assert_numpy_array_equal(actual, expected)
488
+
489
+ # __contains__ not implemented for "interval in interval", follow
490
+ # that for the contains method for now
491
+ with pytest.raises(
492
+ NotImplementedError, match="contains not implemented for two"
493
+ ):
494
+ i.contains(Interval(0, 1))
495
+
496
+ def test_dropna(self, closed):
497
+ expected = IntervalIndex.from_tuples([(0.0, 1.0), (1.0, 2.0)], closed=closed)
498
+
499
+ ii = IntervalIndex.from_tuples([(0, 1), (1, 2), np.nan], closed=closed)
500
+ result = ii.dropna()
501
+ tm.assert_index_equal(result, expected)
502
+
503
+ ii = IntervalIndex.from_arrays([0, 1, np.nan], [1, 2, np.nan], closed=closed)
504
+ result = ii.dropna()
505
+ tm.assert_index_equal(result, expected)
506
+
507
+ def test_non_contiguous(self, closed):
508
+ index = IntervalIndex.from_tuples([(0, 1), (2, 3)], closed=closed)
509
+ target = [0.5, 1.5, 2.5]
510
+ actual = index.get_indexer(target)
511
+ expected = np.array([0, -1, 1], dtype="intp")
512
+ tm.assert_numpy_array_equal(actual, expected)
513
+
514
+ assert 1.5 not in index
515
+
516
+ def test_isin(self, closed):
517
+ index = self.create_index(closed=closed)
518
+
519
+ expected = np.array([True] + [False] * (len(index) - 1))
520
+ result = index.isin(index[:1])
521
+ tm.assert_numpy_array_equal(result, expected)
522
+
523
+ result = index.isin([index[0]])
524
+ tm.assert_numpy_array_equal(result, expected)
525
+
526
+ other = IntervalIndex.from_breaks(np.arange(-2, 10), closed=closed)
527
+ expected = np.array([True] * (len(index) - 1) + [False])
528
+ result = index.isin(other)
529
+ tm.assert_numpy_array_equal(result, expected)
530
+
531
+ result = index.isin(other.tolist())
532
+ tm.assert_numpy_array_equal(result, expected)
533
+
534
+ for other_closed in ["right", "left", "both", "neither"]:
535
+ other = self.create_index(closed=other_closed)
536
+ expected = np.repeat(closed == other_closed, len(index))
537
+ result = index.isin(other)
538
+ tm.assert_numpy_array_equal(result, expected)
539
+
540
+ result = index.isin(other.tolist())
541
+ tm.assert_numpy_array_equal(result, expected)
542
+
543
+ def test_comparison(self):
544
+ actual = Interval(0, 1) < self.index
545
+ expected = np.array([False, True])
546
+ tm.assert_numpy_array_equal(actual, expected)
547
+
548
+ actual = Interval(0.5, 1.5) < self.index
549
+ expected = np.array([False, True])
550
+ tm.assert_numpy_array_equal(actual, expected)
551
+ actual = self.index > Interval(0.5, 1.5)
552
+ tm.assert_numpy_array_equal(actual, expected)
553
+
554
+ actual = self.index == self.index
555
+ expected = np.array([True, True])
556
+ tm.assert_numpy_array_equal(actual, expected)
557
+ actual = self.index <= self.index
558
+ tm.assert_numpy_array_equal(actual, expected)
559
+ actual = self.index >= self.index
560
+ tm.assert_numpy_array_equal(actual, expected)
561
+
562
+ actual = self.index < self.index
563
+ expected = np.array([False, False])
564
+ tm.assert_numpy_array_equal(actual, expected)
565
+ actual = self.index > self.index
566
+ tm.assert_numpy_array_equal(actual, expected)
567
+
568
+ actual = self.index == IntervalIndex.from_breaks([0, 1, 2], "left")
569
+ tm.assert_numpy_array_equal(actual, expected)
570
+
571
+ actual = self.index == self.index.values
572
+ tm.assert_numpy_array_equal(actual, np.array([True, True]))
573
+ actual = self.index.values == self.index
574
+ tm.assert_numpy_array_equal(actual, np.array([True, True]))
575
+ actual = self.index <= self.index.values
576
+ tm.assert_numpy_array_equal(actual, np.array([True, True]))
577
+ actual = self.index != self.index.values
578
+ tm.assert_numpy_array_equal(actual, np.array([False, False]))
579
+ actual = self.index > self.index.values
580
+ tm.assert_numpy_array_equal(actual, np.array([False, False]))
581
+ actual = self.index.values > self.index
582
+ tm.assert_numpy_array_equal(actual, np.array([False, False]))
583
+
584
+ # invalid comparisons
585
+ actual = self.index == 0
586
+ tm.assert_numpy_array_equal(actual, np.array([False, False]))
587
+ actual = self.index == self.index.left
588
+ tm.assert_numpy_array_equal(actual, np.array([False, False]))
589
+
590
+ msg = "|".join(
591
+ [
592
+ "not supported between instances of 'int' and '.*.Interval'",
593
+ r"Invalid comparison between dtype=interval\[int64, right\] and ",
594
+ ]
595
+ )
596
+ with pytest.raises(TypeError, match=msg):
597
+ self.index > 0
598
+ with pytest.raises(TypeError, match=msg):
599
+ self.index <= 0
600
+ with pytest.raises(TypeError, match=msg):
601
+ self.index > np.arange(2)
602
+
603
+ msg = "Lengths must match to compare"
604
+ with pytest.raises(ValueError, match=msg):
605
+ self.index > np.arange(3)
606
+
607
+ def test_missing_values(self, closed):
608
+ idx = Index(
609
+ [np.nan, Interval(0, 1, closed=closed), Interval(1, 2, closed=closed)]
610
+ )
611
+ idx2 = IntervalIndex.from_arrays([np.nan, 0, 1], [np.nan, 1, 2], closed=closed)
612
+ assert idx.equals(idx2)
613
+
614
+ msg = (
615
+ "missing values must be missing in the same location both left "
616
+ "and right sides"
617
+ )
618
+ with pytest.raises(ValueError, match=msg):
619
+ IntervalIndex.from_arrays(
620
+ [np.nan, 0, 1], np.array([0, 1, 2]), closed=closed
621
+ )
622
+
623
+ tm.assert_numpy_array_equal(isna(idx), np.array([True, False, False]))
624
+
625
+ def test_sort_values(self, closed):
626
+ index = self.create_index(closed=closed)
627
+
628
+ result = index.sort_values()
629
+ tm.assert_index_equal(result, index)
630
+
631
+ result = index.sort_values(ascending=False)
632
+ tm.assert_index_equal(result, index[::-1])
633
+
634
+ # with nan
635
+ index = IntervalIndex([Interval(1, 2), np.nan, Interval(0, 1)])
636
+
637
+ result = index.sort_values()
638
+ expected = IntervalIndex([Interval(0, 1), Interval(1, 2), np.nan])
639
+ tm.assert_index_equal(result, expected)
640
+
641
+ result = index.sort_values(ascending=False, na_position="first")
642
+ expected = IntervalIndex([np.nan, Interval(1, 2), Interval(0, 1)])
643
+ tm.assert_index_equal(result, expected)
644
+
645
+ @pytest.mark.parametrize("tz", [None, "US/Eastern"])
646
+ def test_datetime(self, tz):
647
+ start = Timestamp("2000-01-01", tz=tz)
648
+ dates = date_range(start=start, periods=10)
649
+ index = IntervalIndex.from_breaks(dates)
650
+
651
+ # test mid
652
+ start = Timestamp("2000-01-01T12:00", tz=tz)
653
+ expected = date_range(start=start, periods=9)
654
+ tm.assert_index_equal(index.mid, expected)
655
+
656
+ # __contains__ doesn't check individual points
657
+ assert Timestamp("2000-01-01", tz=tz) not in index
658
+ assert Timestamp("2000-01-01T12", tz=tz) not in index
659
+ assert Timestamp("2000-01-02", tz=tz) not in index
660
+ iv_true = Interval(
661
+ Timestamp("2000-01-02", tz=tz), Timestamp("2000-01-03", tz=tz)
662
+ )
663
+ iv_false = Interval(
664
+ Timestamp("1999-12-31", tz=tz), Timestamp("2000-01-01", tz=tz)
665
+ )
666
+ assert iv_true in index
667
+ assert iv_false not in index
668
+
669
+ # .contains does check individual points
670
+ assert not index.contains(Timestamp("2000-01-01", tz=tz)).any()
671
+ assert index.contains(Timestamp("2000-01-01T12", tz=tz)).any()
672
+ assert index.contains(Timestamp("2000-01-02", tz=tz)).any()
673
+
674
+ # test get_indexer
675
+ start = Timestamp("1999-12-31T12:00", tz=tz)
676
+ target = date_range(start=start, periods=7, freq="12h")
677
+ actual = index.get_indexer(target)
678
+ expected = np.array([-1, -1, 0, 0, 1, 1, 2], dtype="intp")
679
+ tm.assert_numpy_array_equal(actual, expected)
680
+
681
+ start = Timestamp("2000-01-08T18:00", tz=tz)
682
+ target = date_range(start=start, periods=7, freq="6h")
683
+ actual = index.get_indexer(target)
684
+ expected = np.array([7, 7, 8, 8, 8, 8, -1], dtype="intp")
685
+ tm.assert_numpy_array_equal(actual, expected)
686
+
687
+ def test_append(self, closed):
688
+ index1 = IntervalIndex.from_arrays([0, 1], [1, 2], closed=closed)
689
+ index2 = IntervalIndex.from_arrays([1, 2], [2, 3], closed=closed)
690
+
691
+ result = index1.append(index2)
692
+ expected = IntervalIndex.from_arrays([0, 1, 1, 2], [1, 2, 2, 3], closed=closed)
693
+ tm.assert_index_equal(result, expected)
694
+
695
+ result = index1.append([index1, index2])
696
+ expected = IntervalIndex.from_arrays(
697
+ [0, 1, 0, 1, 1, 2], [1, 2, 1, 2, 2, 3], closed=closed
698
+ )
699
+ tm.assert_index_equal(result, expected)
700
+
701
+ for other_closed in {"left", "right", "both", "neither"} - {closed}:
702
+ index_other_closed = IntervalIndex.from_arrays(
703
+ [0, 1], [1, 2], closed=other_closed
704
+ )
705
+ result = index1.append(index_other_closed)
706
+ expected = index1.astype(object).append(index_other_closed.astype(object))
707
+ tm.assert_index_equal(result, expected)
708
+
709
+ def test_is_non_overlapping_monotonic(self, closed):
710
+ # Should be True in all cases
711
+ tpls = [(0, 1), (2, 3), (4, 5), (6, 7)]
712
+ idx = IntervalIndex.from_tuples(tpls, closed=closed)
713
+ assert idx.is_non_overlapping_monotonic is True
714
+
715
+ idx = IntervalIndex.from_tuples(tpls[::-1], closed=closed)
716
+ assert idx.is_non_overlapping_monotonic is True
717
+
718
+ # Should be False in all cases (overlapping)
719
+ tpls = [(0, 2), (1, 3), (4, 5), (6, 7)]
720
+ idx = IntervalIndex.from_tuples(tpls, closed=closed)
721
+ assert idx.is_non_overlapping_monotonic is False
722
+
723
+ idx = IntervalIndex.from_tuples(tpls[::-1], closed=closed)
724
+ assert idx.is_non_overlapping_monotonic is False
725
+
726
+ # Should be False in all cases (non-monotonic)
727
+ tpls = [(0, 1), (2, 3), (6, 7), (4, 5)]
728
+ idx = IntervalIndex.from_tuples(tpls, closed=closed)
729
+ assert idx.is_non_overlapping_monotonic is False
730
+
731
+ idx = IntervalIndex.from_tuples(tpls[::-1], closed=closed)
732
+ assert idx.is_non_overlapping_monotonic is False
733
+
734
+ # Should be False for closed='both', otherwise True (GH16560)
735
+ if closed == "both":
736
+ idx = IntervalIndex.from_breaks(range(4), closed=closed)
737
+ assert idx.is_non_overlapping_monotonic is False
738
+ else:
739
+ idx = IntervalIndex.from_breaks(range(4), closed=closed)
740
+ assert idx.is_non_overlapping_monotonic is True
741
+
742
+ @pytest.mark.parametrize(
743
+ "start, shift, na_value",
744
+ [
745
+ (0, 1, np.nan),
746
+ (Timestamp("2018-01-01"), Timedelta("1 day"), pd.NaT),
747
+ (Timedelta("0 days"), Timedelta("1 day"), pd.NaT),
748
+ ],
749
+ )
750
+ def test_is_overlapping(self, start, shift, na_value, closed):
751
+ # GH 23309
752
+ # see test_interval_tree.py for extensive tests; interface tests here
753
+
754
+ # non-overlapping
755
+ tuples = [(start + n * shift, start + (n + 1) * shift) for n in (0, 2, 4)]
756
+ index = IntervalIndex.from_tuples(tuples, closed=closed)
757
+ assert index.is_overlapping is False
758
+
759
+ # non-overlapping with NA
760
+ tuples = [(na_value, na_value)] + tuples + [(na_value, na_value)]
761
+ index = IntervalIndex.from_tuples(tuples, closed=closed)
762
+ assert index.is_overlapping is False
763
+
764
+ # overlapping
765
+ tuples = [(start + n * shift, start + (n + 2) * shift) for n in range(3)]
766
+ index = IntervalIndex.from_tuples(tuples, closed=closed)
767
+ assert index.is_overlapping is True
768
+
769
+ # overlapping with NA
770
+ tuples = [(na_value, na_value)] + tuples + [(na_value, na_value)]
771
+ index = IntervalIndex.from_tuples(tuples, closed=closed)
772
+ assert index.is_overlapping is True
773
+
774
+ # common endpoints
775
+ tuples = [(start + n * shift, start + (n + 1) * shift) for n in range(3)]
776
+ index = IntervalIndex.from_tuples(tuples, closed=closed)
777
+ result = index.is_overlapping
778
+ expected = closed == "both"
779
+ assert result is expected
780
+
781
+ # common endpoints with NA
782
+ tuples = [(na_value, na_value)] + tuples + [(na_value, na_value)]
783
+ index = IntervalIndex.from_tuples(tuples, closed=closed)
784
+ result = index.is_overlapping
785
+ assert result is expected
786
+
787
+ # intervals with duplicate left values
788
+ a = [10, 15, 20, 25, 30, 35, 40, 45, 45, 50, 55, 60, 65, 70, 75, 80, 85]
789
+ b = [15, 20, 25, 30, 35, 40, 45, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90]
790
+ index = IntervalIndex.from_arrays(a, b, closed="right")
791
+ result = index.is_overlapping
792
+ assert result is False
793
+
794
+ @pytest.mark.parametrize(
795
+ "tuples",
796
+ [
797
+ list(zip(range(10), range(1, 11))),
798
+ list(
799
+ zip(
800
+ date_range("20170101", periods=10),
801
+ date_range("20170101", periods=10),
802
+ )
803
+ ),
804
+ list(
805
+ zip(
806
+ timedelta_range("0 days", periods=10),
807
+ timedelta_range("1 day", periods=10),
808
+ )
809
+ ),
810
+ ],
811
+ )
812
+ def test_to_tuples(self, tuples):
813
+ # GH 18756
814
+ idx = IntervalIndex.from_tuples(tuples)
815
+ result = idx.to_tuples()
816
+ expected = Index(com.asarray_tuplesafe(tuples))
817
+ tm.assert_index_equal(result, expected)
818
+
819
+ @pytest.mark.parametrize(
820
+ "tuples",
821
+ [
822
+ list(zip(range(10), range(1, 11))) + [np.nan],
823
+ list(
824
+ zip(
825
+ date_range("20170101", periods=10),
826
+ date_range("20170101", periods=10),
827
+ )
828
+ )
829
+ + [np.nan],
830
+ list(
831
+ zip(
832
+ timedelta_range("0 days", periods=10),
833
+ timedelta_range("1 day", periods=10),
834
+ )
835
+ )
836
+ + [np.nan],
837
+ ],
838
+ )
839
+ @pytest.mark.parametrize("na_tuple", [True, False])
840
+ def test_to_tuples_na(self, tuples, na_tuple):
841
+ # GH 18756
842
+ idx = IntervalIndex.from_tuples(tuples)
843
+ result = idx.to_tuples(na_tuple=na_tuple)
844
+
845
+ # check the non-NA portion
846
+ expected_notna = Index(com.asarray_tuplesafe(tuples[:-1]))
847
+ result_notna = result[:-1]
848
+ tm.assert_index_equal(result_notna, expected_notna)
849
+
850
+ # check the NA portion
851
+ result_na = result[-1]
852
+ if na_tuple:
853
+ assert isinstance(result_na, tuple)
854
+ assert len(result_na) == 2
855
+ assert all(isna(x) for x in result_na)
856
+ else:
857
+ assert isna(result_na)
858
+
859
+ def test_nbytes(self):
860
+ # GH 19209
861
+ left = np.arange(0, 4, dtype="i8")
862
+ right = np.arange(1, 5, dtype="i8")
863
+
864
+ result = IntervalIndex.from_arrays(left, right).nbytes
865
+ expected = 64 # 4 * 8 * 2
866
+ assert result == expected
867
+
868
+ @pytest.mark.parametrize("new_closed", ["left", "right", "both", "neither"])
869
+ def test_set_closed(self, name, closed, new_closed):
870
+ # GH 21670
871
+ index = interval_range(0, 5, closed=closed, name=name)
872
+ result = index.set_closed(new_closed)
873
+ expected = interval_range(0, 5, closed=new_closed, name=name)
874
+ tm.assert_index_equal(result, expected)
875
+
876
+ @pytest.mark.parametrize("bad_closed", ["foo", 10, "LEFT", True, False])
877
+ def test_set_closed_errors(self, bad_closed):
878
+ # GH 21670
879
+ index = interval_range(0, 5)
880
+ msg = f"invalid option for 'closed': {bad_closed}"
881
+ with pytest.raises(ValueError, match=msg):
882
+ index.set_closed(bad_closed)
883
+
884
+ def test_is_all_dates(self):
885
+ # GH 23576
886
+ year_2017 = Interval(
887
+ Timestamp("2017-01-01 00:00:00"), Timestamp("2018-01-01 00:00:00")
888
+ )
889
+ year_2017_index = IntervalIndex([year_2017])
890
+ assert not year_2017_index._is_all_dates
891
+
892
+
893
+ def test_dir():
894
+ # GH#27571 dir(interval_index) should not raise
895
+ index = IntervalIndex.from_arrays([0, 1], [1, 2])
896
+ result = dir(index)
897
+ assert "str" not in result
898
+
899
+
900
+ def test_searchsorted_different_argument_classes(listlike_box):
901
+ # https://github.com/pandas-dev/pandas/issues/32762
902
+ values = IntervalIndex([Interval(0, 1), Interval(1, 2)])
903
+ result = values.searchsorted(listlike_box(values))
904
+ expected = np.array([0, 1], dtype=result.dtype)
905
+ tm.assert_numpy_array_equal(result, expected)
906
+
907
+ result = values._data.searchsorted(listlike_box(values))
908
+ tm.assert_numpy_array_equal(result, expected)
909
+
910
+
911
+ @pytest.mark.parametrize(
912
+ "arg", [[1, 2], ["a", "b"], [Timestamp("2020-01-01", tz="Europe/London")] * 2]
913
+ )
914
+ def test_searchsorted_invalid_argument(arg):
915
+ values = IntervalIndex([Interval(0, 1), Interval(1, 2)])
916
+ msg = "'<' not supported between instances of 'pandas._libs.interval.Interval' and "
917
+ with pytest.raises(TypeError, match=msg):
918
+ values.searchsorted(arg)
lib/python3.10/site-packages/pandas/tests/indexes/interval/test_interval_range.py ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import timedelta
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ from pandas.core.dtypes.common import is_integer
7
+
8
+ from pandas import (
9
+ DateOffset,
10
+ Interval,
11
+ IntervalIndex,
12
+ Timedelta,
13
+ Timestamp,
14
+ date_range,
15
+ interval_range,
16
+ timedelta_range,
17
+ )
18
+ import pandas._testing as tm
19
+
20
+ from pandas.tseries.offsets import Day
21
+
22
+
23
+ @pytest.fixture(params=[None, "foo"])
24
+ def name(request):
25
+ return request.param
26
+
27
+
28
+ class TestIntervalRange:
29
+ @pytest.mark.parametrize("freq, periods", [(1, 100), (2.5, 40), (5, 20), (25, 4)])
30
+ def test_constructor_numeric(self, closed, name, freq, periods):
31
+ start, end = 0, 100
32
+ breaks = np.arange(101, step=freq)
33
+ expected = IntervalIndex.from_breaks(breaks, name=name, closed=closed)
34
+
35
+ # defined from start/end/freq
36
+ result = interval_range(
37
+ start=start, end=end, freq=freq, name=name, closed=closed
38
+ )
39
+ tm.assert_index_equal(result, expected)
40
+
41
+ # defined from start/periods/freq
42
+ result = interval_range(
43
+ start=start, periods=periods, freq=freq, name=name, closed=closed
44
+ )
45
+ tm.assert_index_equal(result, expected)
46
+
47
+ # defined from end/periods/freq
48
+ result = interval_range(
49
+ end=end, periods=periods, freq=freq, name=name, closed=closed
50
+ )
51
+ tm.assert_index_equal(result, expected)
52
+
53
+ # GH 20976: linspace behavior defined from start/end/periods
54
+ result = interval_range(
55
+ start=start, end=end, periods=periods, name=name, closed=closed
56
+ )
57
+ tm.assert_index_equal(result, expected)
58
+
59
+ @pytest.mark.parametrize("tz", [None, "US/Eastern"])
60
+ @pytest.mark.parametrize(
61
+ "freq, periods", [("D", 364), ("2D", 182), ("22D18h", 16), ("ME", 11)]
62
+ )
63
+ def test_constructor_timestamp(self, closed, name, freq, periods, tz):
64
+ start, end = Timestamp("20180101", tz=tz), Timestamp("20181231", tz=tz)
65
+ breaks = date_range(start=start, end=end, freq=freq)
66
+ expected = IntervalIndex.from_breaks(breaks, name=name, closed=closed)
67
+
68
+ # defined from start/end/freq
69
+ result = interval_range(
70
+ start=start, end=end, freq=freq, name=name, closed=closed
71
+ )
72
+ tm.assert_index_equal(result, expected)
73
+
74
+ # defined from start/periods/freq
75
+ result = interval_range(
76
+ start=start, periods=periods, freq=freq, name=name, closed=closed
77
+ )
78
+ tm.assert_index_equal(result, expected)
79
+
80
+ # defined from end/periods/freq
81
+ result = interval_range(
82
+ end=end, periods=periods, freq=freq, name=name, closed=closed
83
+ )
84
+ tm.assert_index_equal(result, expected)
85
+
86
+ # GH 20976: linspace behavior defined from start/end/periods
87
+ if not breaks.freq.n == 1 and tz is None:
88
+ result = interval_range(
89
+ start=start, end=end, periods=periods, name=name, closed=closed
90
+ )
91
+ tm.assert_index_equal(result, expected)
92
+
93
+ @pytest.mark.parametrize(
94
+ "freq, periods", [("D", 100), ("2D12h", 40), ("5D", 20), ("25D", 4)]
95
+ )
96
+ def test_constructor_timedelta(self, closed, name, freq, periods):
97
+ start, end = Timedelta("0 days"), Timedelta("100 days")
98
+ breaks = timedelta_range(start=start, end=end, freq=freq)
99
+ expected = IntervalIndex.from_breaks(breaks, name=name, closed=closed)
100
+
101
+ # defined from start/end/freq
102
+ result = interval_range(
103
+ start=start, end=end, freq=freq, name=name, closed=closed
104
+ )
105
+ tm.assert_index_equal(result, expected)
106
+
107
+ # defined from start/periods/freq
108
+ result = interval_range(
109
+ start=start, periods=periods, freq=freq, name=name, closed=closed
110
+ )
111
+ tm.assert_index_equal(result, expected)
112
+
113
+ # defined from end/periods/freq
114
+ result = interval_range(
115
+ end=end, periods=periods, freq=freq, name=name, closed=closed
116
+ )
117
+ tm.assert_index_equal(result, expected)
118
+
119
+ # GH 20976: linspace behavior defined from start/end/periods
120
+ result = interval_range(
121
+ start=start, end=end, periods=periods, name=name, closed=closed
122
+ )
123
+ tm.assert_index_equal(result, expected)
124
+
125
+ @pytest.mark.parametrize(
126
+ "start, end, freq, expected_endpoint",
127
+ [
128
+ (0, 10, 3, 9),
129
+ (0, 10, 1.5, 9),
130
+ (0.5, 10, 3, 9.5),
131
+ (Timedelta("0D"), Timedelta("10D"), "2D4h", Timedelta("8D16h")),
132
+ (
133
+ Timestamp("2018-01-01"),
134
+ Timestamp("2018-02-09"),
135
+ "MS",
136
+ Timestamp("2018-02-01"),
137
+ ),
138
+ (
139
+ Timestamp("2018-01-01", tz="US/Eastern"),
140
+ Timestamp("2018-01-20", tz="US/Eastern"),
141
+ "5D12h",
142
+ Timestamp("2018-01-17 12:00:00", tz="US/Eastern"),
143
+ ),
144
+ ],
145
+ )
146
+ def test_early_truncation(self, start, end, freq, expected_endpoint):
147
+ # index truncates early if freq causes end to be skipped
148
+ result = interval_range(start=start, end=end, freq=freq)
149
+ result_endpoint = result.right[-1]
150
+ assert result_endpoint == expected_endpoint
151
+
152
+ @pytest.mark.parametrize(
153
+ "start, end, freq",
154
+ [(0.5, None, None), (None, 4.5, None), (0.5, None, 1.5), (None, 6.5, 1.5)],
155
+ )
156
+ def test_no_invalid_float_truncation(self, start, end, freq):
157
+ # GH 21161
158
+ if freq is None:
159
+ breaks = [0.5, 1.5, 2.5, 3.5, 4.5]
160
+ else:
161
+ breaks = [0.5, 2.0, 3.5, 5.0, 6.5]
162
+ expected = IntervalIndex.from_breaks(breaks)
163
+
164
+ result = interval_range(start=start, end=end, periods=4, freq=freq)
165
+ tm.assert_index_equal(result, expected)
166
+
167
+ @pytest.mark.parametrize(
168
+ "start, mid, end",
169
+ [
170
+ (
171
+ Timestamp("2018-03-10", tz="US/Eastern"),
172
+ Timestamp("2018-03-10 23:30:00", tz="US/Eastern"),
173
+ Timestamp("2018-03-12", tz="US/Eastern"),
174
+ ),
175
+ (
176
+ Timestamp("2018-11-03", tz="US/Eastern"),
177
+ Timestamp("2018-11-04 00:30:00", tz="US/Eastern"),
178
+ Timestamp("2018-11-05", tz="US/Eastern"),
179
+ ),
180
+ ],
181
+ )
182
+ def test_linspace_dst_transition(self, start, mid, end):
183
+ # GH 20976: linspace behavior defined from start/end/periods
184
+ # accounts for the hour gained/lost during DST transition
185
+ start = start.as_unit("ns")
186
+ mid = mid.as_unit("ns")
187
+ end = end.as_unit("ns")
188
+ result = interval_range(start=start, end=end, periods=2)
189
+ expected = IntervalIndex.from_breaks([start, mid, end])
190
+ tm.assert_index_equal(result, expected)
191
+
192
+ @pytest.mark.parametrize("freq", [2, 2.0])
193
+ @pytest.mark.parametrize("end", [10, 10.0])
194
+ @pytest.mark.parametrize("start", [0, 0.0])
195
+ def test_float_subtype(self, start, end, freq):
196
+ # Has float subtype if any of start/end/freq are float, even if all
197
+ # resulting endpoints can safely be upcast to integers
198
+
199
+ # defined from start/end/freq
200
+ index = interval_range(start=start, end=end, freq=freq)
201
+ result = index.dtype.subtype
202
+ expected = "int64" if is_integer(start + end + freq) else "float64"
203
+ assert result == expected
204
+
205
+ # defined from start/periods/freq
206
+ index = interval_range(start=start, periods=5, freq=freq)
207
+ result = index.dtype.subtype
208
+ expected = "int64" if is_integer(start + freq) else "float64"
209
+ assert result == expected
210
+
211
+ # defined from end/periods/freq
212
+ index = interval_range(end=end, periods=5, freq=freq)
213
+ result = index.dtype.subtype
214
+ expected = "int64" if is_integer(end + freq) else "float64"
215
+ assert result == expected
216
+
217
+ # GH 20976: linspace behavior defined from start/end/periods
218
+ index = interval_range(start=start, end=end, periods=5)
219
+ result = index.dtype.subtype
220
+ expected = "int64" if is_integer(start + end) else "float64"
221
+ assert result == expected
222
+
223
+ def test_interval_range_fractional_period(self):
224
+ # float value for periods
225
+ expected = interval_range(start=0, periods=10)
226
+ msg = "Non-integer 'periods' in pd.date_range, .* pd.interval_range"
227
+ with tm.assert_produces_warning(FutureWarning, match=msg):
228
+ result = interval_range(start=0, periods=10.5)
229
+ tm.assert_index_equal(result, expected)
230
+
231
+ def test_constructor_coverage(self):
232
+ # equivalent timestamp-like start/end
233
+ start, end = Timestamp("2017-01-01"), Timestamp("2017-01-15")
234
+ expected = interval_range(start=start, end=end)
235
+
236
+ result = interval_range(start=start.to_pydatetime(), end=end.to_pydatetime())
237
+ tm.assert_index_equal(result, expected)
238
+
239
+ result = interval_range(start=start.asm8, end=end.asm8)
240
+ tm.assert_index_equal(result, expected)
241
+
242
+ # equivalent freq with timestamp
243
+ equiv_freq = [
244
+ "D",
245
+ Day(),
246
+ Timedelta(days=1),
247
+ timedelta(days=1),
248
+ DateOffset(days=1),
249
+ ]
250
+ for freq in equiv_freq:
251
+ result = interval_range(start=start, end=end, freq=freq)
252
+ tm.assert_index_equal(result, expected)
253
+
254
+ # equivalent timedelta-like start/end
255
+ start, end = Timedelta(days=1), Timedelta(days=10)
256
+ expected = interval_range(start=start, end=end)
257
+
258
+ result = interval_range(start=start.to_pytimedelta(), end=end.to_pytimedelta())
259
+ tm.assert_index_equal(result, expected)
260
+
261
+ result = interval_range(start=start.asm8, end=end.asm8)
262
+ tm.assert_index_equal(result, expected)
263
+
264
+ # equivalent freq with timedelta
265
+ equiv_freq = ["D", Day(), Timedelta(days=1), timedelta(days=1)]
266
+ for freq in equiv_freq:
267
+ result = interval_range(start=start, end=end, freq=freq)
268
+ tm.assert_index_equal(result, expected)
269
+
270
+ def test_errors(self):
271
+ # not enough params
272
+ msg = (
273
+ "Of the four parameters: start, end, periods, and freq, "
274
+ "exactly three must be specified"
275
+ )
276
+
277
+ with pytest.raises(ValueError, match=msg):
278
+ interval_range(start=0)
279
+
280
+ with pytest.raises(ValueError, match=msg):
281
+ interval_range(end=5)
282
+
283
+ with pytest.raises(ValueError, match=msg):
284
+ interval_range(periods=2)
285
+
286
+ with pytest.raises(ValueError, match=msg):
287
+ interval_range()
288
+
289
+ # too many params
290
+ with pytest.raises(ValueError, match=msg):
291
+ interval_range(start=0, end=5, periods=6, freq=1.5)
292
+
293
+ # mixed units
294
+ msg = "start, end, freq need to be type compatible"
295
+ with pytest.raises(TypeError, match=msg):
296
+ interval_range(start=0, end=Timestamp("20130101"), freq=2)
297
+
298
+ with pytest.raises(TypeError, match=msg):
299
+ interval_range(start=0, end=Timedelta("1 day"), freq=2)
300
+
301
+ with pytest.raises(TypeError, match=msg):
302
+ interval_range(start=0, end=10, freq="D")
303
+
304
+ with pytest.raises(TypeError, match=msg):
305
+ interval_range(start=Timestamp("20130101"), end=10, freq="D")
306
+
307
+ with pytest.raises(TypeError, match=msg):
308
+ interval_range(
309
+ start=Timestamp("20130101"), end=Timedelta("1 day"), freq="D"
310
+ )
311
+
312
+ with pytest.raises(TypeError, match=msg):
313
+ interval_range(
314
+ start=Timestamp("20130101"), end=Timestamp("20130110"), freq=2
315
+ )
316
+
317
+ with pytest.raises(TypeError, match=msg):
318
+ interval_range(start=Timedelta("1 day"), end=10, freq="D")
319
+
320
+ with pytest.raises(TypeError, match=msg):
321
+ interval_range(
322
+ start=Timedelta("1 day"), end=Timestamp("20130110"), freq="D"
323
+ )
324
+
325
+ with pytest.raises(TypeError, match=msg):
326
+ interval_range(start=Timedelta("1 day"), end=Timedelta("10 days"), freq=2)
327
+
328
+ # invalid periods
329
+ msg = "periods must be a number, got foo"
330
+ with pytest.raises(TypeError, match=msg):
331
+ interval_range(start=0, periods="foo")
332
+
333
+ # invalid start
334
+ msg = "start must be numeric or datetime-like, got foo"
335
+ with pytest.raises(ValueError, match=msg):
336
+ interval_range(start="foo", periods=10)
337
+
338
+ # invalid end
339
+ msg = r"end must be numeric or datetime-like, got \(0, 1\]"
340
+ with pytest.raises(ValueError, match=msg):
341
+ interval_range(end=Interval(0, 1), periods=10)
342
+
343
+ # invalid freq for datetime-like
344
+ msg = "freq must be numeric or convertible to DateOffset, got foo"
345
+ with pytest.raises(ValueError, match=msg):
346
+ interval_range(start=0, end=10, freq="foo")
347
+
348
+ with pytest.raises(ValueError, match=msg):
349
+ interval_range(start=Timestamp("20130101"), periods=10, freq="foo")
350
+
351
+ with pytest.raises(ValueError, match=msg):
352
+ interval_range(end=Timedelta("1 day"), periods=10, freq="foo")
353
+
354
+ # mixed tz
355
+ start = Timestamp("2017-01-01", tz="US/Eastern")
356
+ end = Timestamp("2017-01-07", tz="US/Pacific")
357
+ msg = "Start and end cannot both be tz-aware with different timezones"
358
+ with pytest.raises(TypeError, match=msg):
359
+ interval_range(start=start, end=end)
360
+
361
+ def test_float_freq(self):
362
+ # GH 54477
363
+ result = interval_range(0, 1, freq=0.1)
364
+ expected = IntervalIndex.from_breaks([0 + 0.1 * n for n in range(11)])
365
+ tm.assert_index_equal(result, expected)
366
+
367
+ result = interval_range(0, 1, freq=0.6)
368
+ expected = IntervalIndex.from_breaks([0, 0.6])
369
+ tm.assert_index_equal(result, expected)
lib/python3.10/site-packages/pandas/tests/indexes/interval/test_interval_tree.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import permutations
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ from pandas._libs.interval import IntervalTree
7
+ from pandas.compat import IS64
8
+
9
+ import pandas._testing as tm
10
+
11
+
12
+ def skipif_32bit(param):
13
+ """
14
+ Skip parameters in a parametrize on 32bit systems. Specifically used
15
+ here to skip leaf_size parameters related to GH 23440.
16
+ """
17
+ marks = pytest.mark.skipif(not IS64, reason="GH 23440: int type mismatch on 32bit")
18
+ return pytest.param(param, marks=marks)
19
+
20
+
21
+ @pytest.fixture(params=["int64", "float64", "uint64"])
22
+ def dtype(request):
23
+ return request.param
24
+
25
+
26
+ @pytest.fixture(params=[skipif_32bit(1), skipif_32bit(2), 10])
27
+ def leaf_size(request):
28
+ """
29
+ Fixture to specify IntervalTree leaf_size parameter; to be used with the
30
+ tree fixture.
31
+ """
32
+ return request.param
33
+
34
+
35
+ @pytest.fixture(
36
+ params=[
37
+ np.arange(5, dtype="int64"),
38
+ np.arange(5, dtype="uint64"),
39
+ np.arange(5, dtype="float64"),
40
+ np.array([0, 1, 2, 3, 4, np.nan], dtype="float64"),
41
+ ]
42
+ )
43
+ def tree(request, leaf_size):
44
+ left = request.param
45
+ return IntervalTree(left, left + 2, leaf_size=leaf_size)
46
+
47
+
48
+ class TestIntervalTree:
49
+ def test_get_indexer(self, tree):
50
+ result = tree.get_indexer(np.array([1.0, 5.5, 6.5]))
51
+ expected = np.array([0, 4, -1], dtype="intp")
52
+ tm.assert_numpy_array_equal(result, expected)
53
+
54
+ with pytest.raises(
55
+ KeyError, match="'indexer does not intersect a unique set of intervals'"
56
+ ):
57
+ tree.get_indexer(np.array([3.0]))
58
+
59
+ @pytest.mark.parametrize(
60
+ "dtype, target_value, target_dtype",
61
+ [("int64", 2**63 + 1, "uint64"), ("uint64", -1, "int64")],
62
+ )
63
+ def test_get_indexer_overflow(self, dtype, target_value, target_dtype):
64
+ left, right = np.array([0, 1], dtype=dtype), np.array([1, 2], dtype=dtype)
65
+ tree = IntervalTree(left, right)
66
+
67
+ result = tree.get_indexer(np.array([target_value], dtype=target_dtype))
68
+ expected = np.array([-1], dtype="intp")
69
+ tm.assert_numpy_array_equal(result, expected)
70
+
71
+ def test_get_indexer_non_unique(self, tree):
72
+ indexer, missing = tree.get_indexer_non_unique(np.array([1.0, 2.0, 6.5]))
73
+
74
+ result = indexer[:1]
75
+ expected = np.array([0], dtype="intp")
76
+ tm.assert_numpy_array_equal(result, expected)
77
+
78
+ result = np.sort(indexer[1:3])
79
+ expected = np.array([0, 1], dtype="intp")
80
+ tm.assert_numpy_array_equal(result, expected)
81
+
82
+ result = np.sort(indexer[3:])
83
+ expected = np.array([-1], dtype="intp")
84
+ tm.assert_numpy_array_equal(result, expected)
85
+
86
+ result = missing
87
+ expected = np.array([2], dtype="intp")
88
+ tm.assert_numpy_array_equal(result, expected)
89
+
90
+ @pytest.mark.parametrize(
91
+ "dtype, target_value, target_dtype",
92
+ [("int64", 2**63 + 1, "uint64"), ("uint64", -1, "int64")],
93
+ )
94
+ def test_get_indexer_non_unique_overflow(self, dtype, target_value, target_dtype):
95
+ left, right = np.array([0, 2], dtype=dtype), np.array([1, 3], dtype=dtype)
96
+ tree = IntervalTree(left, right)
97
+ target = np.array([target_value], dtype=target_dtype)
98
+
99
+ result_indexer, result_missing = tree.get_indexer_non_unique(target)
100
+ expected_indexer = np.array([-1], dtype="intp")
101
+ tm.assert_numpy_array_equal(result_indexer, expected_indexer)
102
+
103
+ expected_missing = np.array([0], dtype="intp")
104
+ tm.assert_numpy_array_equal(result_missing, expected_missing)
105
+
106
+ def test_duplicates(self, dtype):
107
+ left = np.array([0, 0, 0], dtype=dtype)
108
+ tree = IntervalTree(left, left + 1)
109
+
110
+ with pytest.raises(
111
+ KeyError, match="'indexer does not intersect a unique set of intervals'"
112
+ ):
113
+ tree.get_indexer(np.array([0.5]))
114
+
115
+ indexer, missing = tree.get_indexer_non_unique(np.array([0.5]))
116
+ result = np.sort(indexer)
117
+ expected = np.array([0, 1, 2], dtype="intp")
118
+ tm.assert_numpy_array_equal(result, expected)
119
+
120
+ result = missing
121
+ expected = np.array([], dtype="intp")
122
+ tm.assert_numpy_array_equal(result, expected)
123
+
124
+ @pytest.mark.parametrize(
125
+ "leaf_size", [skipif_32bit(1), skipif_32bit(10), skipif_32bit(100), 10000]
126
+ )
127
+ def test_get_indexer_closed(self, closed, leaf_size):
128
+ x = np.arange(1000, dtype="float64")
129
+ found = x.astype("intp")
130
+ not_found = (-1 * np.ones(1000)).astype("intp")
131
+
132
+ tree = IntervalTree(x, x + 0.5, closed=closed, leaf_size=leaf_size)
133
+ tm.assert_numpy_array_equal(found, tree.get_indexer(x + 0.25))
134
+
135
+ expected = found if tree.closed_left else not_found
136
+ tm.assert_numpy_array_equal(expected, tree.get_indexer(x + 0.0))
137
+
138
+ expected = found if tree.closed_right else not_found
139
+ tm.assert_numpy_array_equal(expected, tree.get_indexer(x + 0.5))
140
+
141
+ @pytest.mark.parametrize(
142
+ "left, right, expected",
143
+ [
144
+ (np.array([0, 1, 4], dtype="int64"), np.array([2, 3, 5]), True),
145
+ (np.array([0, 1, 2], dtype="int64"), np.array([5, 4, 3]), True),
146
+ (np.array([0, 1, np.nan]), np.array([5, 4, np.nan]), True),
147
+ (np.array([0, 2, 4], dtype="int64"), np.array([1, 3, 5]), False),
148
+ (np.array([0, 2, np.nan]), np.array([1, 3, np.nan]), False),
149
+ ],
150
+ )
151
+ @pytest.mark.parametrize("order", (list(x) for x in permutations(range(3))))
152
+ def test_is_overlapping(self, closed, order, left, right, expected):
153
+ # GH 23309
154
+ tree = IntervalTree(left[order], right[order], closed=closed)
155
+ result = tree.is_overlapping
156
+ assert result is expected
157
+
158
+ @pytest.mark.parametrize("order", (list(x) for x in permutations(range(3))))
159
+ def test_is_overlapping_endpoints(self, closed, order):
160
+ """shared endpoints are marked as overlapping"""
161
+ # GH 23309
162
+ left, right = np.arange(3, dtype="int64"), np.arange(1, 4)
163
+ tree = IntervalTree(left[order], right[order], closed=closed)
164
+ result = tree.is_overlapping
165
+ expected = closed == "both"
166
+ assert result is expected
167
+
168
+ @pytest.mark.parametrize(
169
+ "left, right",
170
+ [
171
+ (np.array([], dtype="int64"), np.array([], dtype="int64")),
172
+ (np.array([0], dtype="int64"), np.array([1], dtype="int64")),
173
+ (np.array([np.nan]), np.array([np.nan])),
174
+ (np.array([np.nan] * 3), np.array([np.nan] * 3)),
175
+ ],
176
+ )
177
+ def test_is_overlapping_trivial(self, closed, left, right):
178
+ # GH 23309
179
+ tree = IntervalTree(left, right, closed=closed)
180
+ assert tree.is_overlapping is False
181
+
182
+ @pytest.mark.skipif(not IS64, reason="GH 23440")
183
+ def test_construction_overflow(self):
184
+ # GH 25485
185
+ left, right = np.arange(101, dtype="int64"), [np.iinfo(np.int64).max] * 101
186
+ tree = IntervalTree(left, right)
187
+
188
+ # pivot should be average of left/right medians
189
+ result = tree.root.pivot
190
+ expected = (50 + np.iinfo(np.int64).max) / 2
191
+ assert result == expected
192
+
193
+ @pytest.mark.parametrize(
194
+ "left, right, expected",
195
+ [
196
+ ([-np.inf, 1.0], [1.0, 2.0], 0.0),
197
+ ([-np.inf, -2.0], [-2.0, -1.0], -2.0),
198
+ ([-2.0, -1.0], [-1.0, np.inf], 0.0),
199
+ ([1.0, 2.0], [2.0, np.inf], 2.0),
200
+ ],
201
+ )
202
+ def test_inf_bound_infinite_recursion(self, left, right, expected):
203
+ # GH 46658
204
+
205
+ tree = IntervalTree(left * 101, right * 101)
206
+
207
+ result = tree.root.pivot
208
+ assert result == expected