Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +4 -0
- falcon/lib/python3.10/site-packages/torch/lib/libcusparseLt-f80c68d1.so.0 +3 -0
- infer_4_30_0/bin/python3 +3 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/core/__pycache__/frame.cpython-310.pyc +3 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/core/__pycache__/generic.cpython-310.pyc +3 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/__init__.py +0 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/base_class/__init__.py +0 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/__init__.py +0 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/__pycache__/__init__.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/__pycache__/test_append.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/__pycache__/test_astype.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/__pycache__/test_category.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/__pycache__/test_constructors.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/__pycache__/test_equals.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/__pycache__/test_fillna.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/__pycache__/test_formats.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/__pycache__/test_indexing.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/__pycache__/test_map.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/__pycache__/test_reindex.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/__pycache__/test_setops.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_append.py +62 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_astype.py +90 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_category.py +394 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_constructors.py +142 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_equals.py +96 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_fillna.py +54 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_formats.py +120 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_indexing.py +420 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_map.py +144 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_reindex.py +78 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/test_setops.py +18 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__init__.py +0 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/__init__.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_drop_duplicates.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_equals.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_indexing.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_is_monotonic.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_nat.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_sort_values.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_value_counts.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_drop_duplicates.py +89 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_equals.py +181 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_indexing.py +45 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_is_monotonic.py +46 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_nat.py +53 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_sort_values.py +315 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/test_value_counts.py +103 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/test_any_index.py +172 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/test_common.py +512 -0
- infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/test_datetimelike.py +171 -0
.gitattributes
CHANGED
@@ -2185,3 +2185,7 @@ infer_4_30_0/lib/python3.10/site-packages/pandas/core/indexes/__pycache__/base.c
|
|
2185 |
infer_4_30_0/lib/python3.10/site-packages/pandas/core/indexes/__pycache__/multi.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
2186 |
infer_4_30_0/lib/python3.10/site-packages/pandas/core/groupby/__pycache__/groupby.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
2187 |
infer_4_30_0/lib/python3.10/site-packages/pandas/core/__pycache__/series.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
2185 |
infer_4_30_0/lib/python3.10/site-packages/pandas/core/indexes/__pycache__/multi.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
2186 |
infer_4_30_0/lib/python3.10/site-packages/pandas/core/groupby/__pycache__/groupby.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
2187 |
infer_4_30_0/lib/python3.10/site-packages/pandas/core/__pycache__/series.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
2188 |
+
infer_4_30_0/bin/python3 filter=lfs diff=lfs merge=lfs -text
|
2189 |
+
infer_4_30_0/lib/python3.10/site-packages/pandas/core/__pycache__/frame.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
2190 |
+
falcon/lib/python3.10/site-packages/torch/lib/libcusparseLt-f80c68d1.so.0 filter=lfs diff=lfs merge=lfs -text
|
2191 |
+
infer_4_30_0/lib/python3.10/site-packages/pandas/core/__pycache__/generic.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
falcon/lib/python3.10/site-packages/torch/lib/libcusparseLt-f80c68d1.so.0
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:be6f24534f1aa85998fb58a61b9e7124281ab539cbde11f0f40d9d25795c8728
|
3 |
+
size 43229425
|
infer_4_30_0/bin/python3
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5e0b275e6d9fdb324bd66d9b3a1442628850203bd126a700c4f3be9bd2a18e12
|
3 |
+
size 17225608
|
infer_4_30_0/lib/python3.10/site-packages/pandas/core/__pycache__/frame.cpython-310.pyc
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b51c1785c83ec8f7ed5f0e4d876a08fc707ecb7d56eb809029942ea5158d22f8
|
3 |
+
size 362638
|
infer_4_30_0/lib/python3.10/site-packages/pandas/core/__pycache__/generic.cpython-310.pyc
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:76a7604866bc62b788e91bdd33e41b25ae39d85644f7e6a0b7d94331d75c9399
|
3 |
+
size 385659
|
infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/__init__.py
ADDED
File without changes
|
infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/base_class/__init__.py
ADDED
File without changes
|
infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/__init__.py
ADDED
File without changes
|
infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (190 Bytes). View file
|
|
infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/__pycache__/test_append.cpython-310.pyc
ADDED
Binary file (2.75 kB). View file
|
|
infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/__pycache__/test_astype.cpython-310.pyc
ADDED
Binary file (2.35 kB). View file
|
|
infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/__pycache__/test_category.cpython-310.pyc
ADDED
Binary file (11.5 kB). View file
|
|
infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/__pycache__/test_constructors.cpython-310.pyc
ADDED
Binary file (3.9 kB). View file
|
|
infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/__pycache__/test_equals.cpython-310.pyc
ADDED
Binary file (3.06 kB). View file
|
|
infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/__pycache__/test_fillna.cpython-310.pyc
ADDED
Binary file (1.82 kB). View file
|
|
infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/__pycache__/test_formats.cpython-310.pyc
ADDED
Binary file (5.38 kB). View file
|
|
infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/__pycache__/test_indexing.cpython-310.pyc
ADDED
Binary file (13 kB). View file
|
|
infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/__pycache__/test_map.cpython-310.pyc
ADDED
Binary file (3.73 kB). View file
|
|
infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/__pycache__/test_reindex.cpython-310.pyc
ADDED
Binary file (3.19 kB). View file
|
|
infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/categorical/__pycache__/test_setops.cpython-310.pyc
ADDED
Binary file (721 Bytes). View file
|
|
infer_4_30_0/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)
|
infer_4_30_0/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
|
infer_4_30_0/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 |
+
)
|
infer_4_30_0/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)
|
infer_4_30_0/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)
|
infer_4_30_0/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)
|
infer_4_30_0/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
|
infer_4_30_0/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
|
infer_4_30_0/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)
|
infer_4_30_0/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)
|
infer_4_30_0/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)
|
infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__init__.py
ADDED
File without changes
|
infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (192 Bytes). View file
|
|
infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_drop_duplicates.cpython-310.pyc
ADDED
Binary file (2.95 kB). View file
|
|
infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_equals.cpython-310.pyc
ADDED
Binary file (6.06 kB). View file
|
|
infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_indexing.cpython-310.pyc
ADDED
Binary file (1.4 kB). View file
|
|
infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_is_monotonic.cpython-310.pyc
ADDED
Binary file (1.01 kB). View file
|
|
infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_nat.cpython-310.pyc
ADDED
Binary file (1.94 kB). View file
|
|
infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_sort_values.cpython-310.pyc
ADDED
Binary file (7.61 kB). View file
|
|
infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_value_counts.cpython-310.pyc
ADDED
Binary file (3.28 kB). View file
|
|
infer_4_30_0/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")
|
infer_4_30_0/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)
|
infer_4_30_0/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)
|
infer_4_30_0/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
|
infer_4_30_0/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")
|
infer_4_30_0/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)
|
infer_4_30_0/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)
|
infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/test_any_index.py
ADDED
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Tests that can be parametrized over _any_ Index object.
|
3 |
+
"""
|
4 |
+
import re
|
5 |
+
|
6 |
+
import numpy as np
|
7 |
+
import pytest
|
8 |
+
|
9 |
+
from pandas.errors import InvalidIndexError
|
10 |
+
|
11 |
+
import pandas._testing as tm
|
12 |
+
|
13 |
+
|
14 |
+
def test_boolean_context_compat(index):
|
15 |
+
# GH#7897
|
16 |
+
with pytest.raises(ValueError, match="The truth value of a"):
|
17 |
+
if index:
|
18 |
+
pass
|
19 |
+
|
20 |
+
with pytest.raises(ValueError, match="The truth value of a"):
|
21 |
+
bool(index)
|
22 |
+
|
23 |
+
|
24 |
+
def test_sort(index):
|
25 |
+
msg = "cannot sort an Index object in-place, use sort_values instead"
|
26 |
+
with pytest.raises(TypeError, match=msg):
|
27 |
+
index.sort()
|
28 |
+
|
29 |
+
|
30 |
+
def test_hash_error(index):
|
31 |
+
with pytest.raises(TypeError, match=f"unhashable type: '{type(index).__name__}'"):
|
32 |
+
hash(index)
|
33 |
+
|
34 |
+
|
35 |
+
def test_mutability(index):
|
36 |
+
if not len(index):
|
37 |
+
pytest.skip("Test doesn't make sense for empty index")
|
38 |
+
msg = "Index does not support mutable operations"
|
39 |
+
with pytest.raises(TypeError, match=msg):
|
40 |
+
index[0] = index[0]
|
41 |
+
|
42 |
+
|
43 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
44 |
+
def test_map_identity_mapping(index, request):
|
45 |
+
# GH#12766
|
46 |
+
|
47 |
+
result = index.map(lambda x: x)
|
48 |
+
if index.dtype == object and result.dtype == bool:
|
49 |
+
assert (index == result).all()
|
50 |
+
# TODO: could work that into the 'exact="equiv"'?
|
51 |
+
return # FIXME: doesn't belong in this file anymore!
|
52 |
+
tm.assert_index_equal(result, index, exact="equiv")
|
53 |
+
|
54 |
+
|
55 |
+
def test_wrong_number_names(index):
|
56 |
+
names = index.nlevels * ["apple", "banana", "carrot"]
|
57 |
+
with pytest.raises(ValueError, match="^Length"):
|
58 |
+
index.names = names
|
59 |
+
|
60 |
+
|
61 |
+
def test_view_preserves_name(index):
|
62 |
+
assert index.view().name == index.name
|
63 |
+
|
64 |
+
|
65 |
+
def test_ravel(index):
|
66 |
+
# GH#19956 ravel returning ndarray is deprecated, in 2.0 returns a view on self
|
67 |
+
res = index.ravel()
|
68 |
+
tm.assert_index_equal(res, index)
|
69 |
+
|
70 |
+
|
71 |
+
class TestConversion:
|
72 |
+
def test_to_series(self, index):
|
73 |
+
# assert that we are creating a copy of the index
|
74 |
+
|
75 |
+
ser = index.to_series()
|
76 |
+
assert ser.values is not index.values
|
77 |
+
assert ser.index is not index
|
78 |
+
assert ser.name == index.name
|
79 |
+
|
80 |
+
def test_to_series_with_arguments(self, index):
|
81 |
+
# GH#18699
|
82 |
+
|
83 |
+
# index kwarg
|
84 |
+
ser = index.to_series(index=index)
|
85 |
+
|
86 |
+
assert ser.values is not index.values
|
87 |
+
assert ser.index is index
|
88 |
+
assert ser.name == index.name
|
89 |
+
|
90 |
+
# name kwarg
|
91 |
+
ser = index.to_series(name="__test")
|
92 |
+
|
93 |
+
assert ser.values is not index.values
|
94 |
+
assert ser.index is not index
|
95 |
+
assert ser.name != index.name
|
96 |
+
|
97 |
+
def test_tolist_matches_list(self, index):
|
98 |
+
assert index.tolist() == list(index)
|
99 |
+
|
100 |
+
|
101 |
+
class TestRoundTrips:
|
102 |
+
def test_pickle_roundtrip(self, index):
|
103 |
+
result = tm.round_trip_pickle(index)
|
104 |
+
tm.assert_index_equal(result, index, exact=True)
|
105 |
+
if result.nlevels > 1:
|
106 |
+
# GH#8367 round-trip with timezone
|
107 |
+
assert index.equal_levels(result)
|
108 |
+
|
109 |
+
def test_pickle_preserves_name(self, index):
|
110 |
+
original_name, index.name = index.name, "foo"
|
111 |
+
unpickled = tm.round_trip_pickle(index)
|
112 |
+
assert index.equals(unpickled)
|
113 |
+
index.name = original_name
|
114 |
+
|
115 |
+
|
116 |
+
class TestIndexing:
|
117 |
+
def test_get_loc_listlike_raises_invalid_index_error(self, index):
|
118 |
+
# and never TypeError
|
119 |
+
key = np.array([0, 1], dtype=np.intp)
|
120 |
+
|
121 |
+
with pytest.raises(InvalidIndexError, match=r"\[0 1\]"):
|
122 |
+
index.get_loc(key)
|
123 |
+
|
124 |
+
with pytest.raises(InvalidIndexError, match=r"\[False True\]"):
|
125 |
+
index.get_loc(key.astype(bool))
|
126 |
+
|
127 |
+
def test_getitem_ellipsis(self, index):
|
128 |
+
# GH#21282
|
129 |
+
result = index[...]
|
130 |
+
assert result.equals(index)
|
131 |
+
assert result is not index
|
132 |
+
|
133 |
+
def test_slice_keeps_name(self, index):
|
134 |
+
assert index.name == index[1:].name
|
135 |
+
|
136 |
+
@pytest.mark.parametrize("item", [101, "no_int", 2.5])
|
137 |
+
def test_getitem_error(self, index, item):
|
138 |
+
msg = "|".join(
|
139 |
+
[
|
140 |
+
r"index 101 is out of bounds for axis 0 with size [\d]+",
|
141 |
+
re.escape(
|
142 |
+
"only integers, slices (`:`), ellipsis (`...`), "
|
143 |
+
"numpy.newaxis (`None`) and integer or boolean arrays "
|
144 |
+
"are valid indices"
|
145 |
+
),
|
146 |
+
"index out of bounds", # string[pyarrow]
|
147 |
+
]
|
148 |
+
)
|
149 |
+
with pytest.raises(IndexError, match=msg):
|
150 |
+
index[item]
|
151 |
+
|
152 |
+
|
153 |
+
class TestRendering:
|
154 |
+
def test_str(self, index):
|
155 |
+
# test the string repr
|
156 |
+
index.name = "foo"
|
157 |
+
assert "'foo'" in str(index)
|
158 |
+
assert type(index).__name__ in str(index)
|
159 |
+
|
160 |
+
|
161 |
+
class TestReductions:
|
162 |
+
def test_argmax_axis_invalid(self, index):
|
163 |
+
# GH#23081
|
164 |
+
msg = r"`axis` must be fewer than the number of dimensions \(1\)"
|
165 |
+
with pytest.raises(ValueError, match=msg):
|
166 |
+
index.argmax(axis=1)
|
167 |
+
with pytest.raises(ValueError, match=msg):
|
168 |
+
index.argmin(axis=2)
|
169 |
+
with pytest.raises(ValueError, match=msg):
|
170 |
+
index.min(axis=-2)
|
171 |
+
with pytest.raises(ValueError, match=msg):
|
172 |
+
index.max(axis=-3)
|
infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/test_common.py
ADDED
@@ -0,0 +1,512 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Collection of tests asserting things that should be true for
|
3 |
+
any index subclass except for MultiIndex. Makes use of the `index_flat`
|
4 |
+
fixture defined in pandas/conftest.py.
|
5 |
+
"""
|
6 |
+
from copy import (
|
7 |
+
copy,
|
8 |
+
deepcopy,
|
9 |
+
)
|
10 |
+
import re
|
11 |
+
|
12 |
+
import numpy as np
|
13 |
+
import pytest
|
14 |
+
|
15 |
+
from pandas.compat import IS64
|
16 |
+
from pandas.compat.numpy import np_version_gte1p25
|
17 |
+
|
18 |
+
from pandas.core.dtypes.common import (
|
19 |
+
is_integer_dtype,
|
20 |
+
is_numeric_dtype,
|
21 |
+
)
|
22 |
+
|
23 |
+
import pandas as pd
|
24 |
+
from pandas import (
|
25 |
+
CategoricalIndex,
|
26 |
+
MultiIndex,
|
27 |
+
PeriodIndex,
|
28 |
+
RangeIndex,
|
29 |
+
)
|
30 |
+
import pandas._testing as tm
|
31 |
+
|
32 |
+
|
33 |
+
class TestCommon:
|
34 |
+
@pytest.mark.parametrize("name", [None, "new_name"])
|
35 |
+
def test_to_frame(self, name, index_flat, using_copy_on_write):
|
36 |
+
# see GH#15230, GH#22580
|
37 |
+
idx = index_flat
|
38 |
+
|
39 |
+
if name:
|
40 |
+
idx_name = name
|
41 |
+
else:
|
42 |
+
idx_name = idx.name or 0
|
43 |
+
|
44 |
+
df = idx.to_frame(name=idx_name)
|
45 |
+
|
46 |
+
assert df.index is idx
|
47 |
+
assert len(df.columns) == 1
|
48 |
+
assert df.columns[0] == idx_name
|
49 |
+
if not using_copy_on_write:
|
50 |
+
assert df[idx_name].values is not idx.values
|
51 |
+
|
52 |
+
df = idx.to_frame(index=False, name=idx_name)
|
53 |
+
assert df.index is not idx
|
54 |
+
|
55 |
+
def test_droplevel(self, index_flat):
|
56 |
+
# GH 21115
|
57 |
+
# MultiIndex is tested separately in test_multi.py
|
58 |
+
index = index_flat
|
59 |
+
|
60 |
+
assert index.droplevel([]).equals(index)
|
61 |
+
|
62 |
+
for level in [index.name, [index.name]]:
|
63 |
+
if isinstance(index.name, tuple) and level is index.name:
|
64 |
+
# GH 21121 : droplevel with tuple name
|
65 |
+
continue
|
66 |
+
msg = (
|
67 |
+
"Cannot remove 1 levels from an index with 1 levels: at least one "
|
68 |
+
"level must be left."
|
69 |
+
)
|
70 |
+
with pytest.raises(ValueError, match=msg):
|
71 |
+
index.droplevel(level)
|
72 |
+
|
73 |
+
for level in "wrong", ["wrong"]:
|
74 |
+
with pytest.raises(
|
75 |
+
KeyError,
|
76 |
+
match=r"'Requested level \(wrong\) does not match index name \(None\)'",
|
77 |
+
):
|
78 |
+
index.droplevel(level)
|
79 |
+
|
80 |
+
def test_constructor_non_hashable_name(self, index_flat):
|
81 |
+
# GH 20527
|
82 |
+
index = index_flat
|
83 |
+
|
84 |
+
message = "Index.name must be a hashable type"
|
85 |
+
renamed = [["1"]]
|
86 |
+
|
87 |
+
# With .rename()
|
88 |
+
with pytest.raises(TypeError, match=message):
|
89 |
+
index.rename(name=renamed)
|
90 |
+
|
91 |
+
# With .set_names()
|
92 |
+
with pytest.raises(TypeError, match=message):
|
93 |
+
index.set_names(names=renamed)
|
94 |
+
|
95 |
+
def test_constructor_unwraps_index(self, index_flat):
|
96 |
+
a = index_flat
|
97 |
+
# Passing dtype is necessary for Index([True, False], dtype=object)
|
98 |
+
# case.
|
99 |
+
b = type(a)(a, dtype=a.dtype)
|
100 |
+
tm.assert_equal(a._data, b._data)
|
101 |
+
|
102 |
+
def test_to_flat_index(self, index_flat):
|
103 |
+
# 22866
|
104 |
+
index = index_flat
|
105 |
+
|
106 |
+
result = index.to_flat_index()
|
107 |
+
tm.assert_index_equal(result, index)
|
108 |
+
|
109 |
+
def test_set_name_methods(self, index_flat):
|
110 |
+
# MultiIndex tested separately
|
111 |
+
index = index_flat
|
112 |
+
new_name = "This is the new name for this index"
|
113 |
+
|
114 |
+
original_name = index.name
|
115 |
+
new_ind = index.set_names([new_name])
|
116 |
+
assert new_ind.name == new_name
|
117 |
+
assert index.name == original_name
|
118 |
+
res = index.rename(new_name, inplace=True)
|
119 |
+
|
120 |
+
# should return None
|
121 |
+
assert res is None
|
122 |
+
assert index.name == new_name
|
123 |
+
assert index.names == [new_name]
|
124 |
+
with pytest.raises(ValueError, match="Level must be None"):
|
125 |
+
index.set_names("a", level=0)
|
126 |
+
|
127 |
+
# rename in place just leaves tuples and other containers alone
|
128 |
+
name = ("A", "B")
|
129 |
+
index.rename(name, inplace=True)
|
130 |
+
assert index.name == name
|
131 |
+
assert index.names == [name]
|
132 |
+
|
133 |
+
@pytest.mark.xfail
|
134 |
+
def test_set_names_single_label_no_level(self, index_flat):
|
135 |
+
with pytest.raises(TypeError, match="list-like"):
|
136 |
+
# should still fail even if it would be the right length
|
137 |
+
index_flat.set_names("a")
|
138 |
+
|
139 |
+
def test_copy_and_deepcopy(self, index_flat):
|
140 |
+
index = index_flat
|
141 |
+
|
142 |
+
for func in (copy, deepcopy):
|
143 |
+
idx_copy = func(index)
|
144 |
+
assert idx_copy is not index
|
145 |
+
assert idx_copy.equals(index)
|
146 |
+
|
147 |
+
new_copy = index.copy(deep=True, name="banana")
|
148 |
+
assert new_copy.name == "banana"
|
149 |
+
|
150 |
+
def test_copy_name(self, index_flat):
|
151 |
+
# GH#12309: Check that the "name" argument
|
152 |
+
# passed at initialization is honored.
|
153 |
+
index = index_flat
|
154 |
+
|
155 |
+
first = type(index)(index, copy=True, name="mario")
|
156 |
+
second = type(first)(first, copy=False)
|
157 |
+
|
158 |
+
# Even though "copy=False", we want a new object.
|
159 |
+
assert first is not second
|
160 |
+
tm.assert_index_equal(first, second)
|
161 |
+
|
162 |
+
# Not using tm.assert_index_equal() since names differ.
|
163 |
+
assert index.equals(first)
|
164 |
+
|
165 |
+
assert first.name == "mario"
|
166 |
+
assert second.name == "mario"
|
167 |
+
|
168 |
+
# TODO: belongs in series arithmetic tests?
|
169 |
+
s1 = pd.Series(2, index=first)
|
170 |
+
s2 = pd.Series(3, index=second[:-1])
|
171 |
+
# See GH#13365
|
172 |
+
s3 = s1 * s2
|
173 |
+
assert s3.index.name == "mario"
|
174 |
+
|
175 |
+
def test_copy_name2(self, index_flat):
|
176 |
+
# GH#35592
|
177 |
+
index = index_flat
|
178 |
+
|
179 |
+
assert index.copy(name="mario").name == "mario"
|
180 |
+
|
181 |
+
with pytest.raises(ValueError, match="Length of new names must be 1, got 2"):
|
182 |
+
index.copy(name=["mario", "luigi"])
|
183 |
+
|
184 |
+
msg = f"{type(index).__name__}.name must be a hashable type"
|
185 |
+
with pytest.raises(TypeError, match=msg):
|
186 |
+
index.copy(name=[["mario"]])
|
187 |
+
|
188 |
+
def test_unique_level(self, index_flat):
|
189 |
+
# don't test a MultiIndex here (as its tested separated)
|
190 |
+
index = index_flat
|
191 |
+
|
192 |
+
# GH 17896
|
193 |
+
expected = index.drop_duplicates()
|
194 |
+
for level in [0, index.name, None]:
|
195 |
+
result = index.unique(level=level)
|
196 |
+
tm.assert_index_equal(result, expected)
|
197 |
+
|
198 |
+
msg = "Too many levels: Index has only 1 level, not 4"
|
199 |
+
with pytest.raises(IndexError, match=msg):
|
200 |
+
index.unique(level=3)
|
201 |
+
|
202 |
+
msg = (
|
203 |
+
rf"Requested level \(wrong\) does not match index name "
|
204 |
+
rf"\({re.escape(index.name.__repr__())}\)"
|
205 |
+
)
|
206 |
+
with pytest.raises(KeyError, match=msg):
|
207 |
+
index.unique(level="wrong")
|
208 |
+
|
209 |
+
def test_unique(self, index_flat):
|
210 |
+
# MultiIndex tested separately
|
211 |
+
index = index_flat
|
212 |
+
if not len(index):
|
213 |
+
pytest.skip("Skip check for empty Index and MultiIndex")
|
214 |
+
|
215 |
+
idx = index[[0] * 5]
|
216 |
+
idx_unique = index[[0]]
|
217 |
+
|
218 |
+
# We test against `idx_unique`, so first we make sure it's unique
|
219 |
+
# and doesn't contain nans.
|
220 |
+
assert idx_unique.is_unique is True
|
221 |
+
try:
|
222 |
+
assert idx_unique.hasnans is False
|
223 |
+
except NotImplementedError:
|
224 |
+
pass
|
225 |
+
|
226 |
+
result = idx.unique()
|
227 |
+
tm.assert_index_equal(result, idx_unique)
|
228 |
+
|
229 |
+
# nans:
|
230 |
+
if not index._can_hold_na:
|
231 |
+
pytest.skip("Skip na-check if index cannot hold na")
|
232 |
+
|
233 |
+
vals = index._values[[0] * 5]
|
234 |
+
vals[0] = np.nan
|
235 |
+
|
236 |
+
vals_unique = vals[:2]
|
237 |
+
idx_nan = index._shallow_copy(vals)
|
238 |
+
idx_unique_nan = index._shallow_copy(vals_unique)
|
239 |
+
assert idx_unique_nan.is_unique is True
|
240 |
+
|
241 |
+
assert idx_nan.dtype == index.dtype
|
242 |
+
assert idx_unique_nan.dtype == index.dtype
|
243 |
+
|
244 |
+
expected = idx_unique_nan
|
245 |
+
for pos, i in enumerate([idx_nan, idx_unique_nan]):
|
246 |
+
result = i.unique()
|
247 |
+
tm.assert_index_equal(result, expected)
|
248 |
+
|
249 |
+
@pytest.mark.filterwarnings("ignore:Period with BDay freq:FutureWarning")
|
250 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
251 |
+
def test_searchsorted_monotonic(self, index_flat, request):
|
252 |
+
# GH17271
|
253 |
+
index = index_flat
|
254 |
+
# not implemented for tuple searches in MultiIndex
|
255 |
+
# or Intervals searches in IntervalIndex
|
256 |
+
if isinstance(index, pd.IntervalIndex):
|
257 |
+
mark = pytest.mark.xfail(
|
258 |
+
reason="IntervalIndex.searchsorted does not support Interval arg",
|
259 |
+
raises=NotImplementedError,
|
260 |
+
)
|
261 |
+
request.applymarker(mark)
|
262 |
+
|
263 |
+
# nothing to test if the index is empty
|
264 |
+
if index.empty:
|
265 |
+
pytest.skip("Skip check for empty Index")
|
266 |
+
value = index[0]
|
267 |
+
|
268 |
+
# determine the expected results (handle dupes for 'right')
|
269 |
+
expected_left, expected_right = 0, (index == value).argmin()
|
270 |
+
if expected_right == 0:
|
271 |
+
# all values are the same, expected_right should be length
|
272 |
+
expected_right = len(index)
|
273 |
+
|
274 |
+
# test _searchsorted_monotonic in all cases
|
275 |
+
# test searchsorted only for increasing
|
276 |
+
if index.is_monotonic_increasing:
|
277 |
+
ssm_left = index._searchsorted_monotonic(value, side="left")
|
278 |
+
assert expected_left == ssm_left
|
279 |
+
|
280 |
+
ssm_right = index._searchsorted_monotonic(value, side="right")
|
281 |
+
assert expected_right == ssm_right
|
282 |
+
|
283 |
+
ss_left = index.searchsorted(value, side="left")
|
284 |
+
assert expected_left == ss_left
|
285 |
+
|
286 |
+
ss_right = index.searchsorted(value, side="right")
|
287 |
+
assert expected_right == ss_right
|
288 |
+
|
289 |
+
elif index.is_monotonic_decreasing:
|
290 |
+
ssm_left = index._searchsorted_monotonic(value, side="left")
|
291 |
+
assert expected_left == ssm_left
|
292 |
+
|
293 |
+
ssm_right = index._searchsorted_monotonic(value, side="right")
|
294 |
+
assert expected_right == ssm_right
|
295 |
+
else:
|
296 |
+
# non-monotonic should raise.
|
297 |
+
msg = "index must be monotonic increasing or decreasing"
|
298 |
+
with pytest.raises(ValueError, match=msg):
|
299 |
+
index._searchsorted_monotonic(value, side="left")
|
300 |
+
|
301 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
302 |
+
def test_drop_duplicates(self, index_flat, keep):
|
303 |
+
# MultiIndex is tested separately
|
304 |
+
index = index_flat
|
305 |
+
if isinstance(index, RangeIndex):
|
306 |
+
pytest.skip(
|
307 |
+
"RangeIndex is tested in test_drop_duplicates_no_duplicates "
|
308 |
+
"as it cannot hold duplicates"
|
309 |
+
)
|
310 |
+
if len(index) == 0:
|
311 |
+
pytest.skip(
|
312 |
+
"empty index is tested in test_drop_duplicates_no_duplicates "
|
313 |
+
"as it cannot hold duplicates"
|
314 |
+
)
|
315 |
+
|
316 |
+
# make unique index
|
317 |
+
holder = type(index)
|
318 |
+
unique_values = list(set(index))
|
319 |
+
dtype = index.dtype if is_numeric_dtype(index) else None
|
320 |
+
unique_idx = holder(unique_values, dtype=dtype)
|
321 |
+
|
322 |
+
# make duplicated index
|
323 |
+
n = len(unique_idx)
|
324 |
+
duplicated_selection = np.random.default_rng(2).choice(n, int(n * 1.5))
|
325 |
+
idx = holder(unique_idx.values[duplicated_selection])
|
326 |
+
|
327 |
+
# Series.duplicated is tested separately
|
328 |
+
expected_duplicated = (
|
329 |
+
pd.Series(duplicated_selection).duplicated(keep=keep).values
|
330 |
+
)
|
331 |
+
tm.assert_numpy_array_equal(idx.duplicated(keep=keep), expected_duplicated)
|
332 |
+
|
333 |
+
# Series.drop_duplicates is tested separately
|
334 |
+
expected_dropped = holder(pd.Series(idx).drop_duplicates(keep=keep))
|
335 |
+
tm.assert_index_equal(idx.drop_duplicates(keep=keep), expected_dropped)
|
336 |
+
|
337 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
338 |
+
def test_drop_duplicates_no_duplicates(self, index_flat):
|
339 |
+
# MultiIndex is tested separately
|
340 |
+
index = index_flat
|
341 |
+
|
342 |
+
# make unique index
|
343 |
+
if isinstance(index, RangeIndex):
|
344 |
+
# RangeIndex cannot have duplicates
|
345 |
+
unique_idx = index
|
346 |
+
else:
|
347 |
+
holder = type(index)
|
348 |
+
unique_values = list(set(index))
|
349 |
+
dtype = index.dtype if is_numeric_dtype(index) else None
|
350 |
+
unique_idx = holder(unique_values, dtype=dtype)
|
351 |
+
|
352 |
+
# check on unique index
|
353 |
+
expected_duplicated = np.array([False] * len(unique_idx), dtype="bool")
|
354 |
+
tm.assert_numpy_array_equal(unique_idx.duplicated(), expected_duplicated)
|
355 |
+
result_dropped = unique_idx.drop_duplicates()
|
356 |
+
tm.assert_index_equal(result_dropped, unique_idx)
|
357 |
+
# validate shallow copy
|
358 |
+
assert result_dropped is not unique_idx
|
359 |
+
|
360 |
+
def test_drop_duplicates_inplace(self, index):
|
361 |
+
msg = r"drop_duplicates\(\) got an unexpected keyword argument"
|
362 |
+
with pytest.raises(TypeError, match=msg):
|
363 |
+
index.drop_duplicates(inplace=True)
|
364 |
+
|
365 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
366 |
+
def test_has_duplicates(self, index_flat):
|
367 |
+
# MultiIndex tested separately in:
|
368 |
+
# tests/indexes/multi/test_unique_and_duplicates.
|
369 |
+
index = index_flat
|
370 |
+
holder = type(index)
|
371 |
+
if not len(index) or isinstance(index, RangeIndex):
|
372 |
+
# MultiIndex tested separately in:
|
373 |
+
# tests/indexes/multi/test_unique_and_duplicates.
|
374 |
+
# RangeIndex is unique by definition.
|
375 |
+
pytest.skip("Skip check for empty Index, MultiIndex, and RangeIndex")
|
376 |
+
|
377 |
+
idx = holder([index[0]] * 5)
|
378 |
+
assert idx.is_unique is False
|
379 |
+
assert idx.has_duplicates is True
|
380 |
+
|
381 |
+
@pytest.mark.parametrize(
|
382 |
+
"dtype",
|
383 |
+
["int64", "uint64", "float64", "category", "datetime64[ns]", "timedelta64[ns]"],
|
384 |
+
)
|
385 |
+
def test_astype_preserves_name(self, index, dtype):
|
386 |
+
# https://github.com/pandas-dev/pandas/issues/32013
|
387 |
+
if isinstance(index, MultiIndex):
|
388 |
+
index.names = ["idx" + str(i) for i in range(index.nlevels)]
|
389 |
+
else:
|
390 |
+
index.name = "idx"
|
391 |
+
|
392 |
+
warn = None
|
393 |
+
if index.dtype.kind == "c" and dtype in ["float64", "int64", "uint64"]:
|
394 |
+
# imaginary components discarded
|
395 |
+
if np_version_gte1p25:
|
396 |
+
warn = np.exceptions.ComplexWarning
|
397 |
+
else:
|
398 |
+
warn = np.ComplexWarning
|
399 |
+
|
400 |
+
is_pyarrow_str = str(index.dtype) == "string[pyarrow]" and dtype == "category"
|
401 |
+
try:
|
402 |
+
# Some of these conversions cannot succeed so we use a try / except
|
403 |
+
with tm.assert_produces_warning(
|
404 |
+
warn,
|
405 |
+
raise_on_extra_warnings=is_pyarrow_str,
|
406 |
+
check_stacklevel=False,
|
407 |
+
):
|
408 |
+
result = index.astype(dtype)
|
409 |
+
except (ValueError, TypeError, NotImplementedError, SystemError):
|
410 |
+
return
|
411 |
+
|
412 |
+
if isinstance(index, MultiIndex):
|
413 |
+
assert result.names == index.names
|
414 |
+
else:
|
415 |
+
assert result.name == index.name
|
416 |
+
|
417 |
+
def test_hasnans_isnans(self, index_flat):
|
418 |
+
# GH#11343, added tests for hasnans / isnans
|
419 |
+
index = index_flat
|
420 |
+
|
421 |
+
# cases in indices doesn't include NaN
|
422 |
+
idx = index.copy(deep=True)
|
423 |
+
expected = np.array([False] * len(idx), dtype=bool)
|
424 |
+
tm.assert_numpy_array_equal(idx._isnan, expected)
|
425 |
+
assert idx.hasnans is False
|
426 |
+
|
427 |
+
idx = index.copy(deep=True)
|
428 |
+
values = idx._values
|
429 |
+
|
430 |
+
if len(index) == 0:
|
431 |
+
return
|
432 |
+
elif is_integer_dtype(index.dtype):
|
433 |
+
return
|
434 |
+
elif index.dtype == bool:
|
435 |
+
# values[1] = np.nan below casts to True!
|
436 |
+
return
|
437 |
+
|
438 |
+
values[1] = np.nan
|
439 |
+
|
440 |
+
idx = type(index)(values)
|
441 |
+
|
442 |
+
expected = np.array([False] * len(idx), dtype=bool)
|
443 |
+
expected[1] = True
|
444 |
+
tm.assert_numpy_array_equal(idx._isnan, expected)
|
445 |
+
assert idx.hasnans is True
|
446 |
+
|
447 |
+
|
448 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
449 |
+
@pytest.mark.parametrize("na_position", [None, "middle"])
|
450 |
+
def test_sort_values_invalid_na_position(index_with_missing, na_position):
|
451 |
+
with pytest.raises(ValueError, match=f"invalid na_position: {na_position}"):
|
452 |
+
index_with_missing.sort_values(na_position=na_position)
|
453 |
+
|
454 |
+
|
455 |
+
@pytest.mark.fails_arm_wheels
|
456 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
457 |
+
@pytest.mark.parametrize("na_position", ["first", "last"])
|
458 |
+
def test_sort_values_with_missing(index_with_missing, na_position, request):
|
459 |
+
# GH 35584. Test that sort_values works with missing values,
|
460 |
+
# sort non-missing and place missing according to na_position
|
461 |
+
|
462 |
+
if isinstance(index_with_missing, CategoricalIndex):
|
463 |
+
request.applymarker(
|
464 |
+
pytest.mark.xfail(
|
465 |
+
reason="missing value sorting order not well-defined", strict=False
|
466 |
+
)
|
467 |
+
)
|
468 |
+
|
469 |
+
missing_count = np.sum(index_with_missing.isna())
|
470 |
+
not_na_vals = index_with_missing[index_with_missing.notna()].values
|
471 |
+
sorted_values = np.sort(not_na_vals)
|
472 |
+
if na_position == "first":
|
473 |
+
sorted_values = np.concatenate([[None] * missing_count, sorted_values])
|
474 |
+
else:
|
475 |
+
sorted_values = np.concatenate([sorted_values, [None] * missing_count])
|
476 |
+
|
477 |
+
# Explicitly pass dtype needed for Index backed by EA e.g. IntegerArray
|
478 |
+
expected = type(index_with_missing)(sorted_values, dtype=index_with_missing.dtype)
|
479 |
+
|
480 |
+
result = index_with_missing.sort_values(na_position=na_position)
|
481 |
+
tm.assert_index_equal(result, expected)
|
482 |
+
|
483 |
+
|
484 |
+
def test_ndarray_compat_properties(index):
|
485 |
+
if isinstance(index, PeriodIndex) and not IS64:
|
486 |
+
pytest.skip("Overflow")
|
487 |
+
idx = index
|
488 |
+
assert idx.T.equals(idx)
|
489 |
+
assert idx.transpose().equals(idx)
|
490 |
+
|
491 |
+
values = idx.values
|
492 |
+
|
493 |
+
assert idx.shape == values.shape
|
494 |
+
assert idx.ndim == values.ndim
|
495 |
+
assert idx.size == values.size
|
496 |
+
|
497 |
+
if not isinstance(index, (RangeIndex, MultiIndex)):
|
498 |
+
# These two are not backed by an ndarray
|
499 |
+
assert idx.nbytes == values.nbytes
|
500 |
+
|
501 |
+
# test for validity
|
502 |
+
idx.nbytes
|
503 |
+
idx.values.nbytes
|
504 |
+
|
505 |
+
|
506 |
+
def test_compare_read_only_array():
|
507 |
+
# GH#57130
|
508 |
+
arr = np.array([], dtype=object)
|
509 |
+
arr.flags.writeable = False
|
510 |
+
idx = pd.Index(arr)
|
511 |
+
result = idx > 69
|
512 |
+
assert result.dtype == bool
|
infer_4_30_0/lib/python3.10/site-packages/pandas/tests/indexes/test_datetimelike.py
ADDED
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" generic datetimelike tests """
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
import pytest
|
5 |
+
|
6 |
+
import pandas as pd
|
7 |
+
import pandas._testing as tm
|
8 |
+
|
9 |
+
|
10 |
+
class TestDatetimeLike:
|
11 |
+
@pytest.fixture(
|
12 |
+
params=[
|
13 |
+
pd.period_range("20130101", periods=5, freq="D"),
|
14 |
+
pd.TimedeltaIndex(
|
15 |
+
[
|
16 |
+
"0 days 01:00:00",
|
17 |
+
"1 days 01:00:00",
|
18 |
+
"2 days 01:00:00",
|
19 |
+
"3 days 01:00:00",
|
20 |
+
"4 days 01:00:00",
|
21 |
+
],
|
22 |
+
dtype="timedelta64[ns]",
|
23 |
+
freq="D",
|
24 |
+
),
|
25 |
+
pd.DatetimeIndex(
|
26 |
+
["2013-01-01", "2013-01-02", "2013-01-03", "2013-01-04", "2013-01-05"],
|
27 |
+
dtype="datetime64[ns]",
|
28 |
+
freq="D",
|
29 |
+
),
|
30 |
+
]
|
31 |
+
)
|
32 |
+
def simple_index(self, request):
|
33 |
+
return request.param
|
34 |
+
|
35 |
+
def test_isin(self, simple_index):
|
36 |
+
index = simple_index[:4]
|
37 |
+
result = index.isin(index)
|
38 |
+
assert result.all()
|
39 |
+
|
40 |
+
result = index.isin(list(index))
|
41 |
+
assert result.all()
|
42 |
+
|
43 |
+
result = index.isin([index[2], 5])
|
44 |
+
expected = np.array([False, False, True, False])
|
45 |
+
tm.assert_numpy_array_equal(result, expected)
|
46 |
+
|
47 |
+
def test_argsort_matches_array(self, simple_index):
|
48 |
+
idx = simple_index
|
49 |
+
idx = idx.insert(1, pd.NaT)
|
50 |
+
|
51 |
+
result = idx.argsort()
|
52 |
+
expected = idx._data.argsort()
|
53 |
+
tm.assert_numpy_array_equal(result, expected)
|
54 |
+
|
55 |
+
def test_can_hold_identifiers(self, simple_index):
|
56 |
+
idx = simple_index
|
57 |
+
key = idx[0]
|
58 |
+
assert idx._can_hold_identifiers_and_holds_name(key) is False
|
59 |
+
|
60 |
+
def test_shift_identity(self, simple_index):
|
61 |
+
idx = simple_index
|
62 |
+
tm.assert_index_equal(idx, idx.shift(0))
|
63 |
+
|
64 |
+
def test_shift_empty(self, simple_index):
|
65 |
+
# GH#14811
|
66 |
+
idx = simple_index[:0]
|
67 |
+
tm.assert_index_equal(idx, idx.shift(1))
|
68 |
+
|
69 |
+
def test_str(self, simple_index):
|
70 |
+
# test the string repr
|
71 |
+
idx = simple_index.copy()
|
72 |
+
idx.name = "foo"
|
73 |
+
assert f"length={len(idx)}" not in str(idx)
|
74 |
+
assert "'foo'" in str(idx)
|
75 |
+
assert type(idx).__name__ in str(idx)
|
76 |
+
|
77 |
+
if hasattr(idx, "tz"):
|
78 |
+
if idx.tz is not None:
|
79 |
+
assert idx.tz in str(idx)
|
80 |
+
if isinstance(idx, pd.PeriodIndex):
|
81 |
+
assert f"dtype='period[{idx.freqstr}]'" in str(idx)
|
82 |
+
else:
|
83 |
+
assert f"freq='{idx.freqstr}'" in str(idx)
|
84 |
+
|
85 |
+
def test_view(self, simple_index):
|
86 |
+
idx = simple_index
|
87 |
+
|
88 |
+
idx_view = idx.view("i8")
|
89 |
+
result = type(simple_index)(idx)
|
90 |
+
tm.assert_index_equal(result, idx)
|
91 |
+
|
92 |
+
msg = "Passing a type in .*Index.view is deprecated"
|
93 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
94 |
+
idx_view = idx.view(type(simple_index))
|
95 |
+
result = type(simple_index)(idx)
|
96 |
+
tm.assert_index_equal(result, idx_view)
|
97 |
+
|
98 |
+
def test_map_callable(self, simple_index):
|
99 |
+
index = simple_index
|
100 |
+
expected = index + index.freq
|
101 |
+
result = index.map(lambda x: x + index.freq)
|
102 |
+
tm.assert_index_equal(result, expected)
|
103 |
+
|
104 |
+
# map to NaT
|
105 |
+
result = index.map(lambda x: pd.NaT if x == index[0] else x)
|
106 |
+
expected = pd.Index([pd.NaT] + index[1:].tolist())
|
107 |
+
tm.assert_index_equal(result, expected)
|
108 |
+
|
109 |
+
@pytest.mark.parametrize(
|
110 |
+
"mapper",
|
111 |
+
[
|
112 |
+
lambda values, index: {i: e for e, i in zip(values, index)},
|
113 |
+
lambda values, index: pd.Series(values, index, dtype=object),
|
114 |
+
],
|
115 |
+
)
|
116 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
117 |
+
def test_map_dictlike(self, mapper, simple_index):
|
118 |
+
index = simple_index
|
119 |
+
expected = index + index.freq
|
120 |
+
|
121 |
+
# don't compare the freqs
|
122 |
+
if isinstance(expected, (pd.DatetimeIndex, pd.TimedeltaIndex)):
|
123 |
+
expected = expected._with_freq(None)
|
124 |
+
|
125 |
+
result = index.map(mapper(expected, index))
|
126 |
+
tm.assert_index_equal(result, expected)
|
127 |
+
|
128 |
+
expected = pd.Index([pd.NaT] + index[1:].tolist())
|
129 |
+
result = index.map(mapper(expected, index))
|
130 |
+
tm.assert_index_equal(result, expected)
|
131 |
+
|
132 |
+
# empty map; these map to np.nan because we cannot know
|
133 |
+
# to re-infer things
|
134 |
+
expected = pd.Index([np.nan] * len(index))
|
135 |
+
result = index.map(mapper([], []))
|
136 |
+
tm.assert_index_equal(result, expected)
|
137 |
+
|
138 |
+
def test_getitem_preserves_freq(self, simple_index):
|
139 |
+
index = simple_index
|
140 |
+
assert index.freq is not None
|
141 |
+
|
142 |
+
result = index[:]
|
143 |
+
assert result.freq == index.freq
|
144 |
+
|
145 |
+
def test_where_cast_str(self, simple_index):
|
146 |
+
index = simple_index
|
147 |
+
|
148 |
+
mask = np.ones(len(index), dtype=bool)
|
149 |
+
mask[-1] = False
|
150 |
+
|
151 |
+
result = index.where(mask, str(index[0]))
|
152 |
+
expected = index.where(mask, index[0])
|
153 |
+
tm.assert_index_equal(result, expected)
|
154 |
+
|
155 |
+
result = index.where(mask, [str(index[0])])
|
156 |
+
tm.assert_index_equal(result, expected)
|
157 |
+
|
158 |
+
expected = index.astype(object).where(mask, "foo")
|
159 |
+
result = index.where(mask, "foo")
|
160 |
+
tm.assert_index_equal(result, expected)
|
161 |
+
|
162 |
+
result = index.where(mask, ["foo"])
|
163 |
+
tm.assert_index_equal(result, expected)
|
164 |
+
|
165 |
+
@pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
|
166 |
+
def test_diff(self, unit):
|
167 |
+
# GH 55080
|
168 |
+
dti = pd.to_datetime([10, 20, 30], unit=unit).as_unit(unit)
|
169 |
+
result = dti.diff(1)
|
170 |
+
expected = pd.to_timedelta([pd.NaT, 10, 10], unit=unit).as_unit(unit)
|
171 |
+
tm.assert_index_equal(result, expected)
|