applied-ai-018 commited on
Commit
6c06f83
·
verified ·
1 Parent(s): e8cb1e5

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +3 -0
  2. env-llmeval/lib/python3.10/site-packages/pandas/_libs/hashtable.cpython-310-x86_64-linux-gnu.so +3 -0
  3. env-llmeval/lib/python3.10/site-packages/pandas/_libs/interval.cpython-310-x86_64-linux-gnu.so +3 -0
  4. env-llmeval/lib/python3.10/site-packages/pandas/_libs/tslibs/offsets.cpython-310-x86_64-linux-gnu.so +3 -0
  5. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/__init__.cpython-310.pyc +0 -0
  6. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/masked_shared.cpython-310.pyc +0 -0
  7. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/test_array.cpython-310.pyc +0 -0
  8. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/test_datetimelike.cpython-310.pyc +0 -0
  9. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/test_datetimes.cpython-310.pyc +0 -0
  10. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/test_ndarray_backed.cpython-310.pyc +0 -0
  11. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/test_period.cpython-310.pyc +0 -0
  12. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/test_timedeltas.cpython-310.pyc +0 -0
  13. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__init__.py +0 -0
  14. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/__init__.cpython-310.pyc +0 -0
  15. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_algos.cpython-310.pyc +0 -0
  16. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_analytics.cpython-310.pyc +0 -0
  17. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_api.cpython-310.pyc +0 -0
  18. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_astype.cpython-310.pyc +0 -0
  19. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_constructors.cpython-310.pyc +0 -0
  20. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_dtypes.cpython-310.pyc +0 -0
  21. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_indexing.cpython-310.pyc +0 -0
  22. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_map.cpython-310.pyc +0 -0
  23. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_missing.cpython-310.pyc +0 -0
  24. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_operators.cpython-310.pyc +0 -0
  25. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_replace.cpython-310.pyc +0 -0
  26. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_repr.cpython-310.pyc +0 -0
  27. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_sorting.cpython-310.pyc +0 -0
  28. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_subclass.cpython-310.pyc +0 -0
  29. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_take.cpython-310.pyc +0 -0
  30. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_warnings.cpython-310.pyc +0 -0
  31. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_api.py +501 -0
  32. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_astype.py +155 -0
  33. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_constructors.py +783 -0
  34. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_dtypes.py +139 -0
  35. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_indexing.py +388 -0
  36. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_map.py +154 -0
  37. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_operators.py +414 -0
  38. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_sorting.py +128 -0
  39. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_subclass.py +26 -0
  40. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_take.py +89 -0
  41. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_warnings.py +19 -0
  42. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/datetimes/__init__.py +0 -0
  43. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/datetimes/__pycache__/test_constructors.cpython-310.pyc +0 -0
  44. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/datetimes/__pycache__/test_cumulative.cpython-310.pyc +0 -0
  45. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/datetimes/__pycache__/test_reductions.cpython-310.pyc +0 -0
  46. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/datetimes/test_constructors.py +284 -0
  47. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/datetimes/test_cumulative.py +44 -0
  48. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/datetimes/test_reductions.py +183 -0
  49. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/floating/__init__.py +0 -0
  50. env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/__init__.cpython-310.pyc +0 -0
.gitattributes CHANGED
@@ -170,3 +170,6 @@ env-llmeval/lib/python3.10/site-packages/scipy/fft/_pocketfft/pypocketfft.cpytho
170
  env-llmeval/lib/python3.10/site-packages/scipy/optimize/_highs/_highs_wrapper.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
171
  env-llmeval/lib/python3.10/site-packages/scipy/io/_fast_matrix_market/_fmm_core.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
172
  env-llmeval/lib/python3.10/site-packages/pandas/_libs/join.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
 
 
170
  env-llmeval/lib/python3.10/site-packages/scipy/optimize/_highs/_highs_wrapper.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
171
  env-llmeval/lib/python3.10/site-packages/scipy/io/_fast_matrix_market/_fmm_core.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
172
  env-llmeval/lib/python3.10/site-packages/pandas/_libs/join.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
173
+ env-llmeval/lib/python3.10/site-packages/pandas/_libs/hashtable.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
174
+ env-llmeval/lib/python3.10/site-packages/pandas/_libs/interval.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
175
+ env-llmeval/lib/python3.10/site-packages/pandas/_libs/tslibs/offsets.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
env-llmeval/lib/python3.10/site-packages/pandas/_libs/hashtable.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:79448a63961f04db84af9d3bf6e808c52d8dc8515b59517ddeb2915dcfd2fefb
3
+ size 2162216
env-llmeval/lib/python3.10/site-packages/pandas/_libs/interval.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7e13e757cc911f2818ebea4f5cfaf5197639154cf160d8be4d0e0c27451997f4
3
+ size 1532904
env-llmeval/lib/python3.10/site-packages/pandas/_libs/tslibs/offsets.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2308b178030a6881fbe3c6ada5afd178c04270fabb04a6cd4c58e36bf322e466
3
+ size 1175424
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (184 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/masked_shared.cpython-310.pyc ADDED
Binary file (4.33 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/test_array.cpython-310.pyc ADDED
Binary file (9.32 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/test_datetimelike.cpython-310.pyc ADDED
Binary file (35.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/test_datetimes.cpython-310.pyc ADDED
Binary file (24.8 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/test_ndarray_backed.cpython-310.pyc ADDED
Binary file (2.3 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/test_period.cpython-310.pyc ADDED
Binary file (5.71 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/__pycache__/test_timedeltas.cpython-310.pyc ADDED
Binary file (10.3 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (196 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_algos.cpython-310.pyc ADDED
Binary file (2.84 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_analytics.cpython-310.pyc ADDED
Binary file (11.3 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_api.cpython-310.pyc ADDED
Binary file (14.7 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_astype.cpython-310.pyc ADDED
Binary file (5.47 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_constructors.cpython-310.pyc ADDED
Binary file (28 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_dtypes.cpython-310.pyc ADDED
Binary file (4.95 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_indexing.cpython-310.pyc ADDED
Binary file (12.3 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_map.cpython-310.pyc ADDED
Binary file (4.33 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_missing.cpython-310.pyc ADDED
Binary file (6.72 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_operators.cpython-310.pyc ADDED
Binary file (12.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_replace.cpython-310.pyc ADDED
Binary file (3.33 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_repr.cpython-310.pyc ADDED
Binary file (24.4 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_sorting.cpython-310.pyc ADDED
Binary file (3.49 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_subclass.cpython-310.pyc ADDED
Binary file (1.6 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_take.cpython-310.pyc ADDED
Binary file (3.89 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_warnings.cpython-310.pyc ADDED
Binary file (1.06 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_api.py ADDED
@@ -0,0 +1,501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ from pandas.compat import PY311
7
+
8
+ from pandas import (
9
+ Categorical,
10
+ CategoricalIndex,
11
+ DataFrame,
12
+ Index,
13
+ Series,
14
+ StringDtype,
15
+ )
16
+ import pandas._testing as tm
17
+ from pandas.core.arrays.categorical import recode_for_categories
18
+
19
+
20
+ class TestCategoricalAPI:
21
+ def test_to_list_deprecated(self):
22
+ # GH#51254
23
+ cat1 = Categorical(list("acb"), ordered=False)
24
+ msg = "Categorical.to_list is deprecated and will be removed"
25
+ with tm.assert_produces_warning(FutureWarning, match=msg):
26
+ cat1.to_list()
27
+
28
+ def test_ordered_api(self):
29
+ # GH 9347
30
+ cat1 = Categorical(list("acb"), ordered=False)
31
+ tm.assert_index_equal(cat1.categories, Index(["a", "b", "c"]))
32
+ assert not cat1.ordered
33
+
34
+ cat2 = Categorical(list("acb"), categories=list("bca"), ordered=False)
35
+ tm.assert_index_equal(cat2.categories, Index(["b", "c", "a"]))
36
+ assert not cat2.ordered
37
+
38
+ cat3 = Categorical(list("acb"), ordered=True)
39
+ tm.assert_index_equal(cat3.categories, Index(["a", "b", "c"]))
40
+ assert cat3.ordered
41
+
42
+ cat4 = Categorical(list("acb"), categories=list("bca"), ordered=True)
43
+ tm.assert_index_equal(cat4.categories, Index(["b", "c", "a"]))
44
+ assert cat4.ordered
45
+
46
+ def test_set_ordered(self):
47
+ cat = Categorical(["a", "b", "c", "a"], ordered=True)
48
+ cat2 = cat.as_unordered()
49
+ assert not cat2.ordered
50
+ cat2 = cat.as_ordered()
51
+ assert cat2.ordered
52
+
53
+ assert cat2.set_ordered(True).ordered
54
+ assert not cat2.set_ordered(False).ordered
55
+
56
+ # removed in 0.19.0
57
+ msg = (
58
+ "property 'ordered' of 'Categorical' object has no setter"
59
+ if PY311
60
+ else "can't set attribute"
61
+ )
62
+ with pytest.raises(AttributeError, match=msg):
63
+ cat.ordered = True
64
+ with pytest.raises(AttributeError, match=msg):
65
+ cat.ordered = False
66
+
67
+ def test_rename_categories(self):
68
+ cat = Categorical(["a", "b", "c", "a"])
69
+
70
+ # inplace=False: the old one must not be changed
71
+ res = cat.rename_categories([1, 2, 3])
72
+ tm.assert_numpy_array_equal(
73
+ res.__array__(), np.array([1, 2, 3, 1], dtype=np.int64)
74
+ )
75
+ tm.assert_index_equal(res.categories, Index([1, 2, 3]))
76
+
77
+ exp_cat = np.array(["a", "b", "c", "a"], dtype=np.object_)
78
+ tm.assert_numpy_array_equal(cat.__array__(), exp_cat)
79
+
80
+ exp_cat = Index(["a", "b", "c"])
81
+ tm.assert_index_equal(cat.categories, exp_cat)
82
+
83
+ # GH18862 (let rename_categories take callables)
84
+ result = cat.rename_categories(lambda x: x.upper())
85
+ expected = Categorical(["A", "B", "C", "A"])
86
+ tm.assert_categorical_equal(result, expected)
87
+
88
+ @pytest.mark.parametrize("new_categories", [[1, 2, 3, 4], [1, 2]])
89
+ def test_rename_categories_wrong_length_raises(self, new_categories):
90
+ cat = Categorical(["a", "b", "c", "a"])
91
+ msg = (
92
+ "new categories need to have the same number of items as the "
93
+ "old categories!"
94
+ )
95
+ with pytest.raises(ValueError, match=msg):
96
+ cat.rename_categories(new_categories)
97
+
98
+ def test_rename_categories_series(self):
99
+ # https://github.com/pandas-dev/pandas/issues/17981
100
+ c = Categorical(["a", "b"])
101
+ result = c.rename_categories(Series([0, 1], index=["a", "b"]))
102
+ expected = Categorical([0, 1])
103
+ tm.assert_categorical_equal(result, expected)
104
+
105
+ def test_rename_categories_dict(self):
106
+ # GH 17336
107
+ cat = Categorical(["a", "b", "c", "d"])
108
+ res = cat.rename_categories({"a": 4, "b": 3, "c": 2, "d": 1})
109
+ expected = Index([4, 3, 2, 1])
110
+ tm.assert_index_equal(res.categories, expected)
111
+
112
+ # Test for dicts of smaller length
113
+ cat = Categorical(["a", "b", "c", "d"])
114
+ res = cat.rename_categories({"a": 1, "c": 3})
115
+
116
+ expected = Index([1, "b", 3, "d"])
117
+ tm.assert_index_equal(res.categories, expected)
118
+
119
+ # Test for dicts with bigger length
120
+ cat = Categorical(["a", "b", "c", "d"])
121
+ res = cat.rename_categories({"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6})
122
+ expected = Index([1, 2, 3, 4])
123
+ tm.assert_index_equal(res.categories, expected)
124
+
125
+ # Test for dicts with no items from old categories
126
+ cat = Categorical(["a", "b", "c", "d"])
127
+ res = cat.rename_categories({"f": 1, "g": 3})
128
+
129
+ expected = Index(["a", "b", "c", "d"])
130
+ tm.assert_index_equal(res.categories, expected)
131
+
132
+ def test_reorder_categories(self):
133
+ cat = Categorical(["a", "b", "c", "a"], ordered=True)
134
+ old = cat.copy()
135
+ new = Categorical(
136
+ ["a", "b", "c", "a"], categories=["c", "b", "a"], ordered=True
137
+ )
138
+
139
+ res = cat.reorder_categories(["c", "b", "a"])
140
+ # cat must be the same as before
141
+ tm.assert_categorical_equal(cat, old)
142
+ # only res is changed
143
+ tm.assert_categorical_equal(res, new)
144
+
145
+ @pytest.mark.parametrize(
146
+ "new_categories",
147
+ [
148
+ ["a"], # not all "old" included in "new"
149
+ ["a", "b", "d"], # still not all "old" in "new"
150
+ ["a", "b", "c", "d"], # all "old" included in "new", but too long
151
+ ],
152
+ )
153
+ def test_reorder_categories_raises(self, new_categories):
154
+ cat = Categorical(["a", "b", "c", "a"], ordered=True)
155
+ msg = "items in new_categories are not the same as in old categories"
156
+ with pytest.raises(ValueError, match=msg):
157
+ cat.reorder_categories(new_categories)
158
+
159
+ def test_add_categories(self):
160
+ cat = Categorical(["a", "b", "c", "a"], ordered=True)
161
+ old = cat.copy()
162
+ new = Categorical(
163
+ ["a", "b", "c", "a"], categories=["a", "b", "c", "d"], ordered=True
164
+ )
165
+
166
+ res = cat.add_categories("d")
167
+ tm.assert_categorical_equal(cat, old)
168
+ tm.assert_categorical_equal(res, new)
169
+
170
+ res = cat.add_categories(["d"])
171
+ tm.assert_categorical_equal(cat, old)
172
+ tm.assert_categorical_equal(res, new)
173
+
174
+ # GH 9927
175
+ cat = Categorical(list("abc"), ordered=True)
176
+ expected = Categorical(list("abc"), categories=list("abcde"), ordered=True)
177
+ # test with Series, np.array, index, list
178
+ res = cat.add_categories(Series(["d", "e"]))
179
+ tm.assert_categorical_equal(res, expected)
180
+ res = cat.add_categories(np.array(["d", "e"]))
181
+ tm.assert_categorical_equal(res, expected)
182
+ res = cat.add_categories(Index(["d", "e"]))
183
+ tm.assert_categorical_equal(res, expected)
184
+ res = cat.add_categories(["d", "e"])
185
+ tm.assert_categorical_equal(res, expected)
186
+
187
+ def test_add_categories_existing_raises(self):
188
+ # new is in old categories
189
+ cat = Categorical(["a", "b", "c", "d"], ordered=True)
190
+ msg = re.escape("new categories must not include old categories: {'d'}")
191
+ with pytest.raises(ValueError, match=msg):
192
+ cat.add_categories(["d"])
193
+
194
+ def test_add_categories_losing_dtype_information(self):
195
+ # GH#48812
196
+ cat = Categorical(Series([1, 2], dtype="Int64"))
197
+ ser = Series([4], dtype="Int64")
198
+ result = cat.add_categories(ser)
199
+ expected = Categorical(
200
+ Series([1, 2], dtype="Int64"), categories=Series([1, 2, 4], dtype="Int64")
201
+ )
202
+ tm.assert_categorical_equal(result, expected)
203
+
204
+ cat = Categorical(Series(["a", "b", "a"], dtype=StringDtype()))
205
+ ser = Series(["d"], dtype=StringDtype())
206
+ result = cat.add_categories(ser)
207
+ expected = Categorical(
208
+ Series(["a", "b", "a"], dtype=StringDtype()),
209
+ categories=Series(["a", "b", "d"], dtype=StringDtype()),
210
+ )
211
+ tm.assert_categorical_equal(result, expected)
212
+
213
+ def test_set_categories(self):
214
+ cat = Categorical(["a", "b", "c", "a"], ordered=True)
215
+ exp_categories = Index(["c", "b", "a"])
216
+ exp_values = np.array(["a", "b", "c", "a"], dtype=np.object_)
217
+
218
+ cat = cat.set_categories(["c", "b", "a"])
219
+ res = cat.set_categories(["a", "b", "c"])
220
+ # cat must be the same as before
221
+ tm.assert_index_equal(cat.categories, exp_categories)
222
+ tm.assert_numpy_array_equal(cat.__array__(), exp_values)
223
+ # only res is changed
224
+ exp_categories_back = Index(["a", "b", "c"])
225
+ tm.assert_index_equal(res.categories, exp_categories_back)
226
+ tm.assert_numpy_array_equal(res.__array__(), exp_values)
227
+
228
+ # not all "old" included in "new" -> all not included ones are now
229
+ # np.nan
230
+ cat = Categorical(["a", "b", "c", "a"], ordered=True)
231
+ res = cat.set_categories(["a"])
232
+ tm.assert_numpy_array_equal(res.codes, np.array([0, -1, -1, 0], dtype=np.int8))
233
+
234
+ # still not all "old" in "new"
235
+ res = cat.set_categories(["a", "b", "d"])
236
+ tm.assert_numpy_array_equal(res.codes, np.array([0, 1, -1, 0], dtype=np.int8))
237
+ tm.assert_index_equal(res.categories, Index(["a", "b", "d"]))
238
+
239
+ # all "old" included in "new"
240
+ cat = cat.set_categories(["a", "b", "c", "d"])
241
+ exp_categories = Index(["a", "b", "c", "d"])
242
+ tm.assert_index_equal(cat.categories, exp_categories)
243
+
244
+ # internals...
245
+ c = Categorical([1, 2, 3, 4, 1], categories=[1, 2, 3, 4], ordered=True)
246
+ tm.assert_numpy_array_equal(c._codes, np.array([0, 1, 2, 3, 0], dtype=np.int8))
247
+ tm.assert_index_equal(c.categories, Index([1, 2, 3, 4]))
248
+
249
+ exp = np.array([1, 2, 3, 4, 1], dtype=np.int64)
250
+ tm.assert_numpy_array_equal(np.asarray(c), exp)
251
+
252
+ # all "pointers" to '4' must be changed from 3 to 0,...
253
+ c = c.set_categories([4, 3, 2, 1])
254
+
255
+ # positions are changed
256
+ tm.assert_numpy_array_equal(c._codes, np.array([3, 2, 1, 0, 3], dtype=np.int8))
257
+
258
+ # categories are now in new order
259
+ tm.assert_index_equal(c.categories, Index([4, 3, 2, 1]))
260
+
261
+ # output is the same
262
+ exp = np.array([1, 2, 3, 4, 1], dtype=np.int64)
263
+ tm.assert_numpy_array_equal(np.asarray(c), exp)
264
+ assert c.min() == 4
265
+ assert c.max() == 1
266
+
267
+ # set_categories should set the ordering if specified
268
+ c2 = c.set_categories([4, 3, 2, 1], ordered=False)
269
+ assert not c2.ordered
270
+
271
+ tm.assert_numpy_array_equal(np.asarray(c), np.asarray(c2))
272
+
273
+ # set_categories should pass thru the ordering
274
+ c2 = c.set_ordered(False).set_categories([4, 3, 2, 1])
275
+ assert not c2.ordered
276
+
277
+ tm.assert_numpy_array_equal(np.asarray(c), np.asarray(c2))
278
+
279
+ @pytest.mark.parametrize(
280
+ "values, categories, new_categories",
281
+ [
282
+ # No NaNs, same cats, same order
283
+ (["a", "b", "a"], ["a", "b"], ["a", "b"]),
284
+ # No NaNs, same cats, different order
285
+ (["a", "b", "a"], ["a", "b"], ["b", "a"]),
286
+ # Same, unsorted
287
+ (["b", "a", "a"], ["a", "b"], ["a", "b"]),
288
+ # No NaNs, same cats, different order
289
+ (["b", "a", "a"], ["a", "b"], ["b", "a"]),
290
+ # NaNs
291
+ (["a", "b", "c"], ["a", "b"], ["a", "b"]),
292
+ (["a", "b", "c"], ["a", "b"], ["b", "a"]),
293
+ (["b", "a", "c"], ["a", "b"], ["a", "b"]),
294
+ (["b", "a", "c"], ["a", "b"], ["a", "b"]),
295
+ # Introduce NaNs
296
+ (["a", "b", "c"], ["a", "b"], ["a"]),
297
+ (["a", "b", "c"], ["a", "b"], ["b"]),
298
+ (["b", "a", "c"], ["a", "b"], ["a"]),
299
+ (["b", "a", "c"], ["a", "b"], ["a"]),
300
+ # No overlap
301
+ (["a", "b", "c"], ["a", "b"], ["d", "e"]),
302
+ ],
303
+ )
304
+ @pytest.mark.parametrize("ordered", [True, False])
305
+ def test_set_categories_many(self, values, categories, new_categories, ordered):
306
+ c = Categorical(values, categories)
307
+ expected = Categorical(values, new_categories, ordered)
308
+ result = c.set_categories(new_categories, ordered=ordered)
309
+ tm.assert_categorical_equal(result, expected)
310
+
311
+ def test_set_categories_rename_less(self):
312
+ # GH 24675
313
+ cat = Categorical(["A", "B"])
314
+ result = cat.set_categories(["A"], rename=True)
315
+ expected = Categorical(["A", np.nan])
316
+ tm.assert_categorical_equal(result, expected)
317
+
318
+ def test_set_categories_private(self):
319
+ cat = Categorical(["a", "b", "c"], categories=["a", "b", "c", "d"])
320
+ cat._set_categories(["a", "c", "d", "e"])
321
+ expected = Categorical(["a", "c", "d"], categories=list("acde"))
322
+ tm.assert_categorical_equal(cat, expected)
323
+
324
+ # fastpath
325
+ cat = Categorical(["a", "b", "c"], categories=["a", "b", "c", "d"])
326
+ cat._set_categories(["a", "c", "d", "e"], fastpath=True)
327
+ expected = Categorical(["a", "c", "d"], categories=list("acde"))
328
+ tm.assert_categorical_equal(cat, expected)
329
+
330
+ def test_remove_categories(self):
331
+ cat = Categorical(["a", "b", "c", "a"], ordered=True)
332
+ old = cat.copy()
333
+ new = Categorical(["a", "b", np.nan, "a"], categories=["a", "b"], ordered=True)
334
+
335
+ res = cat.remove_categories("c")
336
+ tm.assert_categorical_equal(cat, old)
337
+ tm.assert_categorical_equal(res, new)
338
+
339
+ res = cat.remove_categories(["c"])
340
+ tm.assert_categorical_equal(cat, old)
341
+ tm.assert_categorical_equal(res, new)
342
+
343
+ @pytest.mark.parametrize("removals", [["c"], ["c", np.nan], "c", ["c", "c"]])
344
+ def test_remove_categories_raises(self, removals):
345
+ cat = Categorical(["a", "b", "a"])
346
+ message = re.escape("removals must all be in old categories: {'c'}")
347
+
348
+ with pytest.raises(ValueError, match=message):
349
+ cat.remove_categories(removals)
350
+
351
+ def test_remove_unused_categories(self):
352
+ c = Categorical(["a", "b", "c", "d", "a"], categories=["a", "b", "c", "d", "e"])
353
+ exp_categories_all = Index(["a", "b", "c", "d", "e"])
354
+ exp_categories_dropped = Index(["a", "b", "c", "d"])
355
+
356
+ tm.assert_index_equal(c.categories, exp_categories_all)
357
+
358
+ res = c.remove_unused_categories()
359
+ tm.assert_index_equal(res.categories, exp_categories_dropped)
360
+ tm.assert_index_equal(c.categories, exp_categories_all)
361
+
362
+ # with NaN values (GH11599)
363
+ c = Categorical(["a", "b", "c", np.nan], categories=["a", "b", "c", "d", "e"])
364
+ res = c.remove_unused_categories()
365
+ tm.assert_index_equal(res.categories, Index(np.array(["a", "b", "c"])))
366
+ exp_codes = np.array([0, 1, 2, -1], dtype=np.int8)
367
+ tm.assert_numpy_array_equal(res.codes, exp_codes)
368
+ tm.assert_index_equal(c.categories, exp_categories_all)
369
+
370
+ val = ["F", np.nan, "D", "B", "D", "F", np.nan]
371
+ cat = Categorical(values=val, categories=list("ABCDEFG"))
372
+ out = cat.remove_unused_categories()
373
+ tm.assert_index_equal(out.categories, Index(["B", "D", "F"]))
374
+ exp_codes = np.array([2, -1, 1, 0, 1, 2, -1], dtype=np.int8)
375
+ tm.assert_numpy_array_equal(out.codes, exp_codes)
376
+ assert out.tolist() == val
377
+
378
+ alpha = list("abcdefghijklmnopqrstuvwxyz")
379
+ val = np.random.default_rng(2).choice(alpha[::2], 10000).astype("object")
380
+ val[np.random.default_rng(2).choice(len(val), 100)] = np.nan
381
+
382
+ cat = Categorical(values=val, categories=alpha)
383
+ out = cat.remove_unused_categories()
384
+ assert out.tolist() == val.tolist()
385
+
386
+
387
+ class TestCategoricalAPIWithFactor:
388
+ def test_describe(self):
389
+ factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)
390
+ # string type
391
+ desc = factor.describe()
392
+ assert factor.ordered
393
+ exp_index = CategoricalIndex(
394
+ ["a", "b", "c"], name="categories", ordered=factor.ordered
395
+ )
396
+ expected = DataFrame(
397
+ {"counts": [3, 2, 3], "freqs": [3 / 8.0, 2 / 8.0, 3 / 8.0]}, index=exp_index
398
+ )
399
+ tm.assert_frame_equal(desc, expected)
400
+
401
+ # check unused categories
402
+ cat = factor.copy()
403
+ cat = cat.set_categories(["a", "b", "c", "d"])
404
+ desc = cat.describe()
405
+
406
+ exp_index = CategoricalIndex(
407
+ list("abcd"), ordered=factor.ordered, name="categories"
408
+ )
409
+ expected = DataFrame(
410
+ {"counts": [3, 2, 3, 0], "freqs": [3 / 8.0, 2 / 8.0, 3 / 8.0, 0]},
411
+ index=exp_index,
412
+ )
413
+ tm.assert_frame_equal(desc, expected)
414
+
415
+ # check an integer one
416
+ cat = Categorical([1, 2, 3, 1, 2, 3, 3, 2, 1, 1, 1])
417
+ desc = cat.describe()
418
+ exp_index = CategoricalIndex([1, 2, 3], ordered=cat.ordered, name="categories")
419
+ expected = DataFrame(
420
+ {"counts": [5, 3, 3], "freqs": [5 / 11.0, 3 / 11.0, 3 / 11.0]},
421
+ index=exp_index,
422
+ )
423
+ tm.assert_frame_equal(desc, expected)
424
+
425
+ # https://github.com/pandas-dev/pandas/issues/3678
426
+ # describe should work with NaN
427
+ cat = Categorical([np.nan, 1, 2, 2])
428
+ desc = cat.describe()
429
+ expected = DataFrame(
430
+ {"counts": [1, 2, 1], "freqs": [1 / 4.0, 2 / 4.0, 1 / 4.0]},
431
+ index=CategoricalIndex(
432
+ [1, 2, np.nan], categories=[1, 2], name="categories"
433
+ ),
434
+ )
435
+ tm.assert_frame_equal(desc, expected)
436
+
437
+
438
+ class TestPrivateCategoricalAPI:
439
+ def test_codes_immutable(self):
440
+ # Codes should be read only
441
+ c = Categorical(["a", "b", "c", "a", np.nan])
442
+ exp = np.array([0, 1, 2, 0, -1], dtype="int8")
443
+ tm.assert_numpy_array_equal(c.codes, exp)
444
+
445
+ # Assignments to codes should raise
446
+ msg = (
447
+ "property 'codes' of 'Categorical' object has no setter"
448
+ if PY311
449
+ else "can't set attribute"
450
+ )
451
+ with pytest.raises(AttributeError, match=msg):
452
+ c.codes = np.array([0, 1, 2, 0, 1], dtype="int8")
453
+
454
+ # changes in the codes array should raise
455
+ codes = c.codes
456
+
457
+ with pytest.raises(ValueError, match="assignment destination is read-only"):
458
+ codes[4] = 1
459
+
460
+ # But even after getting the codes, the original array should still be
461
+ # writeable!
462
+ c[4] = "a"
463
+ exp = np.array([0, 1, 2, 0, 0], dtype="int8")
464
+ tm.assert_numpy_array_equal(c.codes, exp)
465
+ c._codes[4] = 2
466
+ exp = np.array([0, 1, 2, 0, 2], dtype="int8")
467
+ tm.assert_numpy_array_equal(c.codes, exp)
468
+
469
+ @pytest.mark.parametrize(
470
+ "codes, old, new, expected",
471
+ [
472
+ ([0, 1], ["a", "b"], ["a", "b"], [0, 1]),
473
+ ([0, 1], ["b", "a"], ["b", "a"], [0, 1]),
474
+ ([0, 1], ["a", "b"], ["b", "a"], [1, 0]),
475
+ ([0, 1], ["b", "a"], ["a", "b"], [1, 0]),
476
+ ([0, 1, 0, 1], ["a", "b"], ["a", "b", "c"], [0, 1, 0, 1]),
477
+ ([0, 1, 2, 2], ["a", "b", "c"], ["a", "b"], [0, 1, -1, -1]),
478
+ ([0, 1, -1], ["a", "b", "c"], ["a", "b", "c"], [0, 1, -1]),
479
+ ([0, 1, -1], ["a", "b", "c"], ["b"], [-1, 0, -1]),
480
+ ([0, 1, -1], ["a", "b", "c"], ["d"], [-1, -1, -1]),
481
+ ([0, 1, -1], ["a", "b", "c"], [], [-1, -1, -1]),
482
+ ([-1, -1], [], ["a", "b"], [-1, -1]),
483
+ ([1, 0], ["b", "a"], ["a", "b"], [0, 1]),
484
+ ],
485
+ )
486
+ def test_recode_to_categories(self, codes, old, new, expected):
487
+ codes = np.asanyarray(codes, dtype=np.int8)
488
+ expected = np.asanyarray(expected, dtype=np.int8)
489
+ old = Index(old)
490
+ new = Index(new)
491
+ result = recode_for_categories(codes, old, new)
492
+ tm.assert_numpy_array_equal(result, expected)
493
+
494
+ def test_recode_to_categories_large(self):
495
+ N = 1000
496
+ codes = np.arange(N)
497
+ old = Index(codes)
498
+ expected = np.arange(N - 1, -1, -1, dtype=np.int16)
499
+ new = Index(expected)
500
+ result = recode_for_categories(codes, old, new)
501
+ tm.assert_numpy_array_equal(result, expected)
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_astype.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas import (
5
+ Categorical,
6
+ CategoricalDtype,
7
+ CategoricalIndex,
8
+ DatetimeIndex,
9
+ Interval,
10
+ NaT,
11
+ Period,
12
+ Timestamp,
13
+ array,
14
+ to_datetime,
15
+ )
16
+ import pandas._testing as tm
17
+
18
+
19
+ class TestAstype:
20
+ @pytest.mark.parametrize("cls", [Categorical, CategoricalIndex])
21
+ @pytest.mark.parametrize("values", [[1, np.nan], [Timestamp("2000"), NaT]])
22
+ def test_astype_nan_to_int(self, cls, values):
23
+ # GH#28406
24
+ obj = cls(values)
25
+
26
+ msg = "Cannot (cast|convert)"
27
+ with pytest.raises((ValueError, TypeError), match=msg):
28
+ obj.astype(int)
29
+
30
+ @pytest.mark.parametrize(
31
+ "expected",
32
+ [
33
+ array(["2019", "2020"], dtype="datetime64[ns, UTC]"),
34
+ array([0, 0], dtype="timedelta64[ns]"),
35
+ array([Period("2019"), Period("2020")], dtype="period[Y-DEC]"),
36
+ array([Interval(0, 1), Interval(1, 2)], dtype="interval"),
37
+ array([1, np.nan], dtype="Int64"),
38
+ ],
39
+ )
40
+ def test_astype_category_to_extension_dtype(self, expected):
41
+ # GH#28668
42
+ result = expected.astype("category").astype(expected.dtype)
43
+
44
+ tm.assert_extension_array_equal(result, expected)
45
+
46
+ @pytest.mark.parametrize(
47
+ "dtype, expected",
48
+ [
49
+ (
50
+ "datetime64[ns]",
51
+ np.array(["2015-01-01T00:00:00.000000000"], dtype="datetime64[ns]"),
52
+ ),
53
+ (
54
+ "datetime64[ns, MET]",
55
+ DatetimeIndex([Timestamp("2015-01-01 00:00:00+0100", tz="MET")]).array,
56
+ ),
57
+ ],
58
+ )
59
+ def test_astype_to_datetime64(self, dtype, expected):
60
+ # GH#28448
61
+ result = Categorical(["2015-01-01"]).astype(dtype)
62
+ assert result == expected
63
+
64
+ def test_astype_str_int_categories_to_nullable_int(self):
65
+ # GH#39616
66
+ dtype = CategoricalDtype([str(i) for i in range(5)])
67
+ codes = np.random.default_rng(2).integers(5, size=20)
68
+ arr = Categorical.from_codes(codes, dtype=dtype)
69
+
70
+ res = arr.astype("Int64")
71
+ expected = array(codes, dtype="Int64")
72
+ tm.assert_extension_array_equal(res, expected)
73
+
74
+ def test_astype_str_int_categories_to_nullable_float(self):
75
+ # GH#39616
76
+ dtype = CategoricalDtype([str(i / 2) for i in range(5)])
77
+ codes = np.random.default_rng(2).integers(5, size=20)
78
+ arr = Categorical.from_codes(codes, dtype=dtype)
79
+
80
+ res = arr.astype("Float64")
81
+ expected = array(codes, dtype="Float64") / 2
82
+ tm.assert_extension_array_equal(res, expected)
83
+
84
+ @pytest.mark.parametrize("ordered", [True, False])
85
+ def test_astype(self, ordered):
86
+ # string
87
+ cat = Categorical(list("abbaaccc"), ordered=ordered)
88
+ result = cat.astype(object)
89
+ expected = np.array(cat)
90
+ tm.assert_numpy_array_equal(result, expected)
91
+
92
+ msg = r"Cannot cast object|string dtype to float64"
93
+ with pytest.raises(ValueError, match=msg):
94
+ cat.astype(float)
95
+
96
+ # numeric
97
+ cat = Categorical([0, 1, 2, 2, 1, 0, 1, 0, 2], ordered=ordered)
98
+ result = cat.astype(object)
99
+ expected = np.array(cat, dtype=object)
100
+ tm.assert_numpy_array_equal(result, expected)
101
+
102
+ result = cat.astype(int)
103
+ expected = np.array(cat, dtype="int")
104
+ tm.assert_numpy_array_equal(result, expected)
105
+
106
+ result = cat.astype(float)
107
+ expected = np.array(cat, dtype=float)
108
+ tm.assert_numpy_array_equal(result, expected)
109
+
110
+ @pytest.mark.parametrize("dtype_ordered", [True, False])
111
+ @pytest.mark.parametrize("cat_ordered", [True, False])
112
+ def test_astype_category(self, dtype_ordered, cat_ordered):
113
+ # GH#10696/GH#18593
114
+ data = list("abcaacbab")
115
+ cat = Categorical(data, categories=list("bac"), ordered=cat_ordered)
116
+
117
+ # standard categories
118
+ dtype = CategoricalDtype(ordered=dtype_ordered)
119
+ result = cat.astype(dtype)
120
+ expected = Categorical(data, categories=cat.categories, ordered=dtype_ordered)
121
+ tm.assert_categorical_equal(result, expected)
122
+
123
+ # non-standard categories
124
+ dtype = CategoricalDtype(list("adc"), dtype_ordered)
125
+ result = cat.astype(dtype)
126
+ expected = Categorical(data, dtype=dtype)
127
+ tm.assert_categorical_equal(result, expected)
128
+
129
+ if dtype_ordered is False:
130
+ # dtype='category' can't specify ordered, so only test once
131
+ result = cat.astype("category")
132
+ expected = cat
133
+ tm.assert_categorical_equal(result, expected)
134
+
135
+ def test_astype_object_datetime_categories(self):
136
+ # GH#40754
137
+ cat = Categorical(to_datetime(["2021-03-27", NaT]))
138
+ result = cat.astype(object)
139
+ expected = np.array([Timestamp("2021-03-27 00:00:00"), NaT], dtype="object")
140
+ tm.assert_numpy_array_equal(result, expected)
141
+
142
+ def test_astype_object_timestamp_categories(self):
143
+ # GH#18024
144
+ cat = Categorical([Timestamp("2014-01-01")])
145
+ result = cat.astype(object)
146
+ expected = np.array([Timestamp("2014-01-01 00:00:00")], dtype="object")
147
+ tm.assert_numpy_array_equal(result, expected)
148
+
149
+ def test_astype_category_readonly_mask_values(self):
150
+ # GH#53658
151
+ arr = array([0, 1, 2], dtype="Int64")
152
+ arr._mask.flags["WRITEABLE"] = False
153
+ result = arr.astype("category")
154
+ expected = array([0, 1, 2], dtype="Int64").astype("category")
155
+ tm.assert_extension_array_equal(result, expected)
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_constructors.py ADDED
@@ -0,0 +1,783 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import (
2
+ date,
3
+ datetime,
4
+ )
5
+
6
+ import numpy as np
7
+ import pytest
8
+
9
+ from pandas._config import using_pyarrow_string_dtype
10
+
11
+ from pandas.core.dtypes.common import (
12
+ is_float_dtype,
13
+ is_integer_dtype,
14
+ )
15
+ from pandas.core.dtypes.dtypes import CategoricalDtype
16
+
17
+ import pandas as pd
18
+ from pandas import (
19
+ Categorical,
20
+ CategoricalIndex,
21
+ DatetimeIndex,
22
+ Index,
23
+ Interval,
24
+ IntervalIndex,
25
+ MultiIndex,
26
+ NaT,
27
+ Series,
28
+ Timestamp,
29
+ date_range,
30
+ period_range,
31
+ timedelta_range,
32
+ )
33
+ import pandas._testing as tm
34
+
35
+
36
+ class TestCategoricalConstructors:
37
+ def test_fastpath_deprecated(self):
38
+ codes = np.array([1, 2, 3])
39
+ dtype = CategoricalDtype(categories=["a", "b", "c", "d"], ordered=False)
40
+ msg = "The 'fastpath' keyword in Categorical is deprecated"
41
+ with tm.assert_produces_warning(DeprecationWarning, match=msg):
42
+ Categorical(codes, dtype=dtype, fastpath=True)
43
+
44
+ def test_categorical_from_cat_and_dtype_str_preserve_ordered(self):
45
+ # GH#49309 we should preserve orderedness in `res`
46
+ cat = Categorical([3, 1], categories=[3, 2, 1], ordered=True)
47
+
48
+ res = Categorical(cat, dtype="category")
49
+ assert res.dtype.ordered
50
+
51
+ def test_categorical_disallows_scalar(self):
52
+ # GH#38433
53
+ with pytest.raises(TypeError, match="Categorical input must be list-like"):
54
+ Categorical("A", categories=["A", "B"])
55
+
56
+ def test_categorical_1d_only(self):
57
+ # ndim > 1
58
+ msg = "> 1 ndim Categorical are not supported at this time"
59
+ with pytest.raises(NotImplementedError, match=msg):
60
+ Categorical(np.array([list("abcd")]))
61
+
62
+ def test_validate_ordered(self):
63
+ # see gh-14058
64
+ exp_msg = "'ordered' must either be 'True' or 'False'"
65
+ exp_err = TypeError
66
+
67
+ # This should be a boolean.
68
+ ordered = np.array([0, 1, 2])
69
+
70
+ with pytest.raises(exp_err, match=exp_msg):
71
+ Categorical([1, 2, 3], ordered=ordered)
72
+
73
+ with pytest.raises(exp_err, match=exp_msg):
74
+ Categorical.from_codes(
75
+ [0, 0, 1], categories=["a", "b", "c"], ordered=ordered
76
+ )
77
+
78
+ def test_constructor_empty(self):
79
+ # GH 17248
80
+ c = Categorical([])
81
+ expected = Index([])
82
+ tm.assert_index_equal(c.categories, expected)
83
+
84
+ c = Categorical([], categories=[1, 2, 3])
85
+ expected = Index([1, 2, 3], dtype=np.int64)
86
+ tm.assert_index_equal(c.categories, expected)
87
+
88
+ def test_constructor_empty_boolean(self):
89
+ # see gh-22702
90
+ cat = Categorical([], categories=[True, False])
91
+ categories = sorted(cat.categories.tolist())
92
+ assert categories == [False, True]
93
+
94
+ def test_constructor_tuples(self):
95
+ values = np.array([(1,), (1, 2), (1,), (1, 2)], dtype=object)
96
+ result = Categorical(values)
97
+ expected = Index([(1,), (1, 2)], tupleize_cols=False)
98
+ tm.assert_index_equal(result.categories, expected)
99
+ assert result.ordered is False
100
+
101
+ def test_constructor_tuples_datetimes(self):
102
+ # numpy will auto reshape when all of the tuples are the
103
+ # same len, so add an extra one with 2 items and slice it off
104
+ values = np.array(
105
+ [
106
+ (Timestamp("2010-01-01"),),
107
+ (Timestamp("2010-01-02"),),
108
+ (Timestamp("2010-01-01"),),
109
+ (Timestamp("2010-01-02"),),
110
+ ("a", "b"),
111
+ ],
112
+ dtype=object,
113
+ )[:-1]
114
+ result = Categorical(values)
115
+ expected = Index(
116
+ [(Timestamp("2010-01-01"),), (Timestamp("2010-01-02"),)],
117
+ tupleize_cols=False,
118
+ )
119
+ tm.assert_index_equal(result.categories, expected)
120
+
121
+ def test_constructor_unsortable(self):
122
+ # it works!
123
+ arr = np.array([1, 2, 3, datetime.now()], dtype="O")
124
+ factor = Categorical(arr, ordered=False)
125
+ assert not factor.ordered
126
+
127
+ # this however will raise as cannot be sorted
128
+ msg = (
129
+ "'values' is not ordered, please explicitly specify the "
130
+ "categories order by passing in a categories argument."
131
+ )
132
+ with pytest.raises(TypeError, match=msg):
133
+ Categorical(arr, ordered=True)
134
+
135
+ def test_constructor_interval(self):
136
+ result = Categorical(
137
+ [Interval(1, 2), Interval(2, 3), Interval(3, 6)], ordered=True
138
+ )
139
+ ii = IntervalIndex([Interval(1, 2), Interval(2, 3), Interval(3, 6)])
140
+ exp = Categorical(ii, ordered=True)
141
+ tm.assert_categorical_equal(result, exp)
142
+ tm.assert_index_equal(result.categories, ii)
143
+
144
+ def test_constructor(self):
145
+ exp_arr = np.array(["a", "b", "c", "a", "b", "c"], dtype=np.object_)
146
+ c1 = Categorical(exp_arr)
147
+ tm.assert_numpy_array_equal(c1.__array__(), exp_arr)
148
+ c2 = Categorical(exp_arr, categories=["a", "b", "c"])
149
+ tm.assert_numpy_array_equal(c2.__array__(), exp_arr)
150
+ c2 = Categorical(exp_arr, categories=["c", "b", "a"])
151
+ tm.assert_numpy_array_equal(c2.__array__(), exp_arr)
152
+
153
+ # categories must be unique
154
+ msg = "Categorical categories must be unique"
155
+ with pytest.raises(ValueError, match=msg):
156
+ Categorical([1, 2], [1, 2, 2])
157
+
158
+ with pytest.raises(ValueError, match=msg):
159
+ Categorical(["a", "b"], ["a", "b", "b"])
160
+
161
+ # The default should be unordered
162
+ c1 = Categorical(["a", "b", "c", "a"])
163
+ assert not c1.ordered
164
+
165
+ # Categorical as input
166
+ c1 = Categorical(["a", "b", "c", "a"])
167
+ c2 = Categorical(c1)
168
+ tm.assert_categorical_equal(c1, c2)
169
+
170
+ c1 = Categorical(["a", "b", "c", "a"], categories=["a", "b", "c", "d"])
171
+ c2 = Categorical(c1)
172
+ tm.assert_categorical_equal(c1, c2)
173
+
174
+ c1 = Categorical(["a", "b", "c", "a"], categories=["a", "c", "b"])
175
+ c2 = Categorical(c1)
176
+ tm.assert_categorical_equal(c1, c2)
177
+
178
+ c1 = Categorical(["a", "b", "c", "a"], categories=["a", "c", "b"])
179
+ c2 = Categorical(c1, categories=["a", "b", "c"])
180
+ tm.assert_numpy_array_equal(c1.__array__(), c2.__array__())
181
+ tm.assert_index_equal(c2.categories, Index(["a", "b", "c"]))
182
+
183
+ # Series of dtype category
184
+ c1 = Categorical(["a", "b", "c", "a"], categories=["a", "b", "c", "d"])
185
+ c2 = Categorical(Series(c1))
186
+ tm.assert_categorical_equal(c1, c2)
187
+
188
+ c1 = Categorical(["a", "b", "c", "a"], categories=["a", "c", "b"])
189
+ c2 = Categorical(Series(c1))
190
+ tm.assert_categorical_equal(c1, c2)
191
+
192
+ # Series
193
+ c1 = Categorical(["a", "b", "c", "a"])
194
+ c2 = Categorical(Series(["a", "b", "c", "a"]))
195
+ tm.assert_categorical_equal(c1, c2)
196
+
197
+ c1 = Categorical(["a", "b", "c", "a"], categories=["a", "b", "c", "d"])
198
+ c2 = Categorical(Series(["a", "b", "c", "a"]), categories=["a", "b", "c", "d"])
199
+ tm.assert_categorical_equal(c1, c2)
200
+
201
+ # This should result in integer categories, not float!
202
+ cat = Categorical([1, 2, 3, np.nan], categories=[1, 2, 3])
203
+ assert is_integer_dtype(cat.categories)
204
+
205
+ # https://github.com/pandas-dev/pandas/issues/3678
206
+ cat = Categorical([np.nan, 1, 2, 3])
207
+ assert is_integer_dtype(cat.categories)
208
+
209
+ # this should result in floats
210
+ cat = Categorical([np.nan, 1, 2.0, 3])
211
+ assert is_float_dtype(cat.categories)
212
+
213
+ cat = Categorical([np.nan, 1.0, 2.0, 3.0])
214
+ assert is_float_dtype(cat.categories)
215
+
216
+ # This doesn't work -> this would probably need some kind of "remember
217
+ # the original type" feature to try to cast the array interface result
218
+ # to...
219
+
220
+ # vals = np.asarray(cat[cat.notna()])
221
+ # assert is_integer_dtype(vals)
222
+
223
+ # corner cases
224
+ cat = Categorical([1])
225
+ assert len(cat.categories) == 1
226
+ assert cat.categories[0] == 1
227
+ assert len(cat.codes) == 1
228
+ assert cat.codes[0] == 0
229
+
230
+ cat = Categorical(["a"])
231
+ assert len(cat.categories) == 1
232
+ assert cat.categories[0] == "a"
233
+ assert len(cat.codes) == 1
234
+ assert cat.codes[0] == 0
235
+
236
+ # two arrays
237
+ # - when the first is an integer dtype and the second is not
238
+ # - when the resulting codes are all -1/NaN
239
+ with tm.assert_produces_warning(None):
240
+ Categorical([0, 1, 2, 0, 1, 2], categories=["a", "b", "c"])
241
+
242
+ with tm.assert_produces_warning(None):
243
+ Categorical([0, 1, 2, 0, 1, 2], categories=[3, 4, 5])
244
+
245
+ # the next one are from the old docs
246
+ with tm.assert_produces_warning(None):
247
+ Categorical([0, 1, 2, 0, 1, 2], [1, 2, 3])
248
+ cat = Categorical([1, 2], categories=[1, 2, 3])
249
+
250
+ # this is a legitimate constructor
251
+ with tm.assert_produces_warning(None):
252
+ Categorical(np.array([], dtype="int64"), categories=[3, 2, 1], ordered=True)
253
+
254
+ def test_constructor_with_existing_categories(self):
255
+ # GH25318: constructing with pd.Series used to bogusly skip recoding
256
+ # categories
257
+ c0 = Categorical(["a", "b", "c", "a"])
258
+ c1 = Categorical(["a", "b", "c", "a"], categories=["b", "c"])
259
+
260
+ c2 = Categorical(c0, categories=c1.categories)
261
+ tm.assert_categorical_equal(c1, c2)
262
+
263
+ c3 = Categorical(Series(c0), categories=c1.categories)
264
+ tm.assert_categorical_equal(c1, c3)
265
+
266
+ def test_constructor_not_sequence(self):
267
+ # https://github.com/pandas-dev/pandas/issues/16022
268
+ msg = r"^Parameter 'categories' must be list-like, was"
269
+ with pytest.raises(TypeError, match=msg):
270
+ Categorical(["a", "b"], categories="a")
271
+
272
+ def test_constructor_with_null(self):
273
+ # Cannot have NaN in categories
274
+ msg = "Categorical categories cannot be null"
275
+ with pytest.raises(ValueError, match=msg):
276
+ Categorical([np.nan, "a", "b", "c"], categories=[np.nan, "a", "b", "c"])
277
+
278
+ with pytest.raises(ValueError, match=msg):
279
+ Categorical([None, "a", "b", "c"], categories=[None, "a", "b", "c"])
280
+
281
+ with pytest.raises(ValueError, match=msg):
282
+ Categorical(
283
+ DatetimeIndex(["nat", "20160101"]),
284
+ categories=[NaT, Timestamp("20160101")],
285
+ )
286
+
287
+ def test_constructor_with_index(self):
288
+ ci = CategoricalIndex(list("aabbca"), categories=list("cab"))
289
+ tm.assert_categorical_equal(ci.values, Categorical(ci))
290
+
291
+ ci = CategoricalIndex(list("aabbca"), categories=list("cab"))
292
+ tm.assert_categorical_equal(
293
+ ci.values, Categorical(ci.astype(object), categories=ci.categories)
294
+ )
295
+
296
+ def test_constructor_with_generator(self):
297
+ # This was raising an Error in isna(single_val).any() because isna
298
+ # returned a scalar for a generator
299
+
300
+ exp = Categorical([0, 1, 2])
301
+ cat = Categorical(x for x in [0, 1, 2])
302
+ tm.assert_categorical_equal(cat, exp)
303
+ cat = Categorical(range(3))
304
+ tm.assert_categorical_equal(cat, exp)
305
+
306
+ MultiIndex.from_product([range(5), ["a", "b", "c"]])
307
+
308
+ # check that categories accept generators and sequences
309
+ cat = Categorical([0, 1, 2], categories=(x for x in [0, 1, 2]))
310
+ tm.assert_categorical_equal(cat, exp)
311
+ cat = Categorical([0, 1, 2], categories=range(3))
312
+ tm.assert_categorical_equal(cat, exp)
313
+
314
+ def test_constructor_with_rangeindex(self):
315
+ # RangeIndex is preserved in Categories
316
+ rng = Index(range(3))
317
+
318
+ cat = Categorical(rng)
319
+ tm.assert_index_equal(cat.categories, rng, exact=True)
320
+
321
+ cat = Categorical([1, 2, 0], categories=rng)
322
+ tm.assert_index_equal(cat.categories, rng, exact=True)
323
+
324
+ @pytest.mark.parametrize(
325
+ "dtl",
326
+ [
327
+ date_range("1995-01-01 00:00:00", periods=5, freq="s"),
328
+ date_range("1995-01-01 00:00:00", periods=5, freq="s", tz="US/Eastern"),
329
+ timedelta_range("1 day", periods=5, freq="s"),
330
+ ],
331
+ )
332
+ def test_constructor_with_datetimelike(self, dtl):
333
+ # see gh-12077
334
+ # constructor with a datetimelike and NaT
335
+
336
+ s = Series(dtl)
337
+ c = Categorical(s)
338
+
339
+ expected = type(dtl)(s)
340
+ expected._data.freq = None
341
+
342
+ tm.assert_index_equal(c.categories, expected)
343
+ tm.assert_numpy_array_equal(c.codes, np.arange(5, dtype="int8"))
344
+
345
+ # with NaT
346
+ s2 = s.copy()
347
+ s2.iloc[-1] = NaT
348
+ c = Categorical(s2)
349
+
350
+ expected = type(dtl)(s2.dropna())
351
+ expected._data.freq = None
352
+
353
+ tm.assert_index_equal(c.categories, expected)
354
+
355
+ exp = np.array([0, 1, 2, 3, -1], dtype=np.int8)
356
+ tm.assert_numpy_array_equal(c.codes, exp)
357
+
358
+ result = repr(c)
359
+ assert "NaT" in result
360
+
361
+ def test_constructor_from_index_series_datetimetz(self):
362
+ idx = date_range("2015-01-01 10:00", freq="D", periods=3, tz="US/Eastern")
363
+ idx = idx._with_freq(None) # freq not preserved in result.categories
364
+ result = Categorical(idx)
365
+ tm.assert_index_equal(result.categories, idx)
366
+
367
+ result = Categorical(Series(idx))
368
+ tm.assert_index_equal(result.categories, idx)
369
+
370
+ def test_constructor_date_objects(self):
371
+ # we dont cast date objects to timestamps, matching Index constructor
372
+ v = date.today()
373
+
374
+ cat = Categorical([v, v])
375
+ assert cat.categories.dtype == object
376
+ assert type(cat.categories[0]) is date
377
+
378
+ def test_constructor_from_index_series_timedelta(self):
379
+ idx = timedelta_range("1 days", freq="D", periods=3)
380
+ idx = idx._with_freq(None) # freq not preserved in result.categories
381
+ result = Categorical(idx)
382
+ tm.assert_index_equal(result.categories, idx)
383
+
384
+ result = Categorical(Series(idx))
385
+ tm.assert_index_equal(result.categories, idx)
386
+
387
+ def test_constructor_from_index_series_period(self):
388
+ idx = period_range("2015-01-01", freq="D", periods=3)
389
+ result = Categorical(idx)
390
+ tm.assert_index_equal(result.categories, idx)
391
+
392
+ result = Categorical(Series(idx))
393
+ tm.assert_index_equal(result.categories, idx)
394
+
395
+ @pytest.mark.parametrize(
396
+ "values",
397
+ [
398
+ np.array([1.0, 1.2, 1.8, np.nan]),
399
+ np.array([1, 2, 3], dtype="int64"),
400
+ ["a", "b", "c", np.nan],
401
+ [pd.Period("2014-01"), pd.Period("2014-02"), NaT],
402
+ [Timestamp("2014-01-01"), Timestamp("2014-01-02"), NaT],
403
+ [
404
+ Timestamp("2014-01-01", tz="US/Eastern"),
405
+ Timestamp("2014-01-02", tz="US/Eastern"),
406
+ NaT,
407
+ ],
408
+ ],
409
+ )
410
+ def test_constructor_invariant(self, values):
411
+ # GH 14190
412
+ c = Categorical(values)
413
+ c2 = Categorical(c)
414
+ tm.assert_categorical_equal(c, c2)
415
+
416
+ @pytest.mark.parametrize("ordered", [True, False])
417
+ def test_constructor_with_dtype(self, ordered):
418
+ categories = ["b", "a", "c"]
419
+ dtype = CategoricalDtype(categories, ordered=ordered)
420
+ result = Categorical(["a", "b", "a", "c"], dtype=dtype)
421
+ expected = Categorical(
422
+ ["a", "b", "a", "c"], categories=categories, ordered=ordered
423
+ )
424
+ tm.assert_categorical_equal(result, expected)
425
+ assert result.ordered is ordered
426
+
427
+ def test_constructor_dtype_and_others_raises(self):
428
+ dtype = CategoricalDtype(["a", "b"], ordered=True)
429
+ msg = "Cannot specify `categories` or `ordered` together with `dtype`."
430
+ with pytest.raises(ValueError, match=msg):
431
+ Categorical(["a", "b"], categories=["a", "b"], dtype=dtype)
432
+
433
+ with pytest.raises(ValueError, match=msg):
434
+ Categorical(["a", "b"], ordered=True, dtype=dtype)
435
+
436
+ with pytest.raises(ValueError, match=msg):
437
+ Categorical(["a", "b"], ordered=False, dtype=dtype)
438
+
439
+ @pytest.mark.parametrize("categories", [None, ["a", "b"], ["a", "c"]])
440
+ @pytest.mark.parametrize("ordered", [True, False])
441
+ def test_constructor_str_category(self, categories, ordered):
442
+ result = Categorical(
443
+ ["a", "b"], categories=categories, ordered=ordered, dtype="category"
444
+ )
445
+ expected = Categorical(["a", "b"], categories=categories, ordered=ordered)
446
+ tm.assert_categorical_equal(result, expected)
447
+
448
+ def test_constructor_str_unknown(self):
449
+ with pytest.raises(ValueError, match="Unknown dtype"):
450
+ Categorical([1, 2], dtype="foo")
451
+
452
+ @pytest.mark.xfail(using_pyarrow_string_dtype(), reason="Can't be NumPy strings")
453
+ def test_constructor_np_strs(self):
454
+ # GH#31499 Hashtable.map_locations needs to work on np.str_ objects
455
+ cat = Categorical(["1", "0", "1"], [np.str_("0"), np.str_("1")])
456
+ assert all(isinstance(x, np.str_) for x in cat.categories)
457
+
458
+ def test_constructor_from_categorical_with_dtype(self):
459
+ dtype = CategoricalDtype(["a", "b", "c"], ordered=True)
460
+ values = Categorical(["a", "b", "d"])
461
+ result = Categorical(values, dtype=dtype)
462
+ # We use dtype.categories, not values.categories
463
+ expected = Categorical(
464
+ ["a", "b", "d"], categories=["a", "b", "c"], ordered=True
465
+ )
466
+ tm.assert_categorical_equal(result, expected)
467
+
468
+ def test_constructor_from_categorical_with_unknown_dtype(self):
469
+ dtype = CategoricalDtype(None, ordered=True)
470
+ values = Categorical(["a", "b", "d"])
471
+ result = Categorical(values, dtype=dtype)
472
+ # We use values.categories, not dtype.categories
473
+ expected = Categorical(
474
+ ["a", "b", "d"], categories=["a", "b", "d"], ordered=True
475
+ )
476
+ tm.assert_categorical_equal(result, expected)
477
+
478
+ def test_constructor_from_categorical_string(self):
479
+ values = Categorical(["a", "b", "d"])
480
+ # use categories, ordered
481
+ result = Categorical(
482
+ values, categories=["a", "b", "c"], ordered=True, dtype="category"
483
+ )
484
+ expected = Categorical(
485
+ ["a", "b", "d"], categories=["a", "b", "c"], ordered=True
486
+ )
487
+ tm.assert_categorical_equal(result, expected)
488
+
489
+ # No string
490
+ result = Categorical(values, categories=["a", "b", "c"], ordered=True)
491
+ tm.assert_categorical_equal(result, expected)
492
+
493
+ def test_constructor_with_categorical_categories(self):
494
+ # GH17884
495
+ expected = Categorical(["a", "b"], categories=["a", "b", "c"])
496
+
497
+ result = Categorical(["a", "b"], categories=Categorical(["a", "b", "c"]))
498
+ tm.assert_categorical_equal(result, expected)
499
+
500
+ result = Categorical(["a", "b"], categories=CategoricalIndex(["a", "b", "c"]))
501
+ tm.assert_categorical_equal(result, expected)
502
+
503
+ @pytest.mark.parametrize("klass", [lambda x: np.array(x, dtype=object), list])
504
+ def test_construction_with_null(self, klass, nulls_fixture):
505
+ # https://github.com/pandas-dev/pandas/issues/31927
506
+ values = klass(["a", nulls_fixture, "b"])
507
+ result = Categorical(values)
508
+
509
+ dtype = CategoricalDtype(["a", "b"])
510
+ codes = [0, -1, 1]
511
+ expected = Categorical.from_codes(codes=codes, dtype=dtype)
512
+
513
+ tm.assert_categorical_equal(result, expected)
514
+
515
+ @pytest.mark.parametrize("validate", [True, False])
516
+ def test_from_codes_nullable_int_categories(self, any_numeric_ea_dtype, validate):
517
+ # GH#39649
518
+ cats = pd.array(range(5), dtype=any_numeric_ea_dtype)
519
+ codes = np.random.default_rng(2).integers(5, size=3)
520
+ dtype = CategoricalDtype(cats)
521
+ arr = Categorical.from_codes(codes, dtype=dtype, validate=validate)
522
+ assert arr.categories.dtype == cats.dtype
523
+ tm.assert_index_equal(arr.categories, Index(cats))
524
+
525
+ def test_from_codes_empty(self):
526
+ cat = ["a", "b", "c"]
527
+ result = Categorical.from_codes([], categories=cat)
528
+ expected = Categorical([], categories=cat)
529
+
530
+ tm.assert_categorical_equal(result, expected)
531
+
532
+ @pytest.mark.parametrize("validate", [True, False])
533
+ def test_from_codes_validate(self, validate):
534
+ # GH53122
535
+ dtype = CategoricalDtype(["a", "b"])
536
+ if validate:
537
+ with pytest.raises(ValueError, match="codes need to be between "):
538
+ Categorical.from_codes([4, 5], dtype=dtype, validate=validate)
539
+ else:
540
+ # passes, though has incorrect codes, but that's the user responsibility
541
+ Categorical.from_codes([4, 5], dtype=dtype, validate=validate)
542
+
543
+ def test_from_codes_too_few_categories(self):
544
+ dtype = CategoricalDtype(categories=[1, 2])
545
+ msg = "codes need to be between "
546
+ with pytest.raises(ValueError, match=msg):
547
+ Categorical.from_codes([1, 2], categories=dtype.categories)
548
+ with pytest.raises(ValueError, match=msg):
549
+ Categorical.from_codes([1, 2], dtype=dtype)
550
+
551
+ def test_from_codes_non_int_codes(self):
552
+ dtype = CategoricalDtype(categories=[1, 2])
553
+ msg = "codes need to be array-like integers"
554
+ with pytest.raises(ValueError, match=msg):
555
+ Categorical.from_codes(["a"], categories=dtype.categories)
556
+ with pytest.raises(ValueError, match=msg):
557
+ Categorical.from_codes(["a"], dtype=dtype)
558
+
559
+ def test_from_codes_non_unique_categories(self):
560
+ with pytest.raises(ValueError, match="Categorical categories must be unique"):
561
+ Categorical.from_codes([0, 1, 2], categories=["a", "a", "b"])
562
+
563
+ def test_from_codes_nan_cat_included(self):
564
+ with pytest.raises(ValueError, match="Categorical categories cannot be null"):
565
+ Categorical.from_codes([0, 1, 2], categories=["a", "b", np.nan])
566
+
567
+ def test_from_codes_too_negative(self):
568
+ dtype = CategoricalDtype(categories=["a", "b", "c"])
569
+ msg = r"codes need to be between -1 and len\(categories\)-1"
570
+ with pytest.raises(ValueError, match=msg):
571
+ Categorical.from_codes([-2, 1, 2], categories=dtype.categories)
572
+ with pytest.raises(ValueError, match=msg):
573
+ Categorical.from_codes([-2, 1, 2], dtype=dtype)
574
+
575
+ def test_from_codes(self):
576
+ dtype = CategoricalDtype(categories=["a", "b", "c"])
577
+ exp = Categorical(["a", "b", "c"], ordered=False)
578
+ res = Categorical.from_codes([0, 1, 2], categories=dtype.categories)
579
+ tm.assert_categorical_equal(exp, res)
580
+
581
+ res = Categorical.from_codes([0, 1, 2], dtype=dtype)
582
+ tm.assert_categorical_equal(exp, res)
583
+
584
+ @pytest.mark.parametrize("klass", [Categorical, CategoricalIndex])
585
+ def test_from_codes_with_categorical_categories(self, klass):
586
+ # GH17884
587
+ expected = Categorical(["a", "b"], categories=["a", "b", "c"])
588
+
589
+ result = Categorical.from_codes([0, 1], categories=klass(["a", "b", "c"]))
590
+ tm.assert_categorical_equal(result, expected)
591
+
592
+ @pytest.mark.parametrize("klass", [Categorical, CategoricalIndex])
593
+ def test_from_codes_with_non_unique_categorical_categories(self, klass):
594
+ with pytest.raises(ValueError, match="Categorical categories must be unique"):
595
+ Categorical.from_codes([0, 1], klass(["a", "b", "a"]))
596
+
597
+ def test_from_codes_with_nan_code(self):
598
+ # GH21767
599
+ codes = [1, 2, np.nan]
600
+ dtype = CategoricalDtype(categories=["a", "b", "c"])
601
+ with pytest.raises(ValueError, match="codes need to be array-like integers"):
602
+ Categorical.from_codes(codes, categories=dtype.categories)
603
+ with pytest.raises(ValueError, match="codes need to be array-like integers"):
604
+ Categorical.from_codes(codes, dtype=dtype)
605
+
606
+ @pytest.mark.parametrize("codes", [[1.0, 2.0, 0], [1.1, 2.0, 0]])
607
+ def test_from_codes_with_float(self, codes):
608
+ # GH21767
609
+ # float codes should raise even if values are equal to integers
610
+ dtype = CategoricalDtype(categories=["a", "b", "c"])
611
+
612
+ msg = "codes need to be array-like integers"
613
+ with pytest.raises(ValueError, match=msg):
614
+ Categorical.from_codes(codes, dtype.categories)
615
+ with pytest.raises(ValueError, match=msg):
616
+ Categorical.from_codes(codes, dtype=dtype)
617
+
618
+ def test_from_codes_with_dtype_raises(self):
619
+ msg = "Cannot specify"
620
+ with pytest.raises(ValueError, match=msg):
621
+ Categorical.from_codes(
622
+ [0, 1], categories=["a", "b"], dtype=CategoricalDtype(["a", "b"])
623
+ )
624
+
625
+ with pytest.raises(ValueError, match=msg):
626
+ Categorical.from_codes(
627
+ [0, 1], ordered=True, dtype=CategoricalDtype(["a", "b"])
628
+ )
629
+
630
+ def test_from_codes_neither(self):
631
+ msg = "Both were None"
632
+ with pytest.raises(ValueError, match=msg):
633
+ Categorical.from_codes([0, 1])
634
+
635
+ def test_from_codes_with_nullable_int(self):
636
+ codes = pd.array([0, 1], dtype="Int64")
637
+ categories = ["a", "b"]
638
+
639
+ result = Categorical.from_codes(codes, categories=categories)
640
+ expected = Categorical.from_codes(codes.to_numpy(int), categories=categories)
641
+
642
+ tm.assert_categorical_equal(result, expected)
643
+
644
+ def test_from_codes_with_nullable_int_na_raises(self):
645
+ codes = pd.array([0, None], dtype="Int64")
646
+ categories = ["a", "b"]
647
+
648
+ msg = "codes cannot contain NA values"
649
+ with pytest.raises(ValueError, match=msg):
650
+ Categorical.from_codes(codes, categories=categories)
651
+
652
+ @pytest.mark.parametrize("dtype", [None, "category"])
653
+ def test_from_inferred_categories(self, dtype):
654
+ cats = ["a", "b"]
655
+ codes = np.array([0, 0, 1, 1], dtype="i8")
656
+ result = Categorical._from_inferred_categories(cats, codes, dtype)
657
+ expected = Categorical.from_codes(codes, cats)
658
+ tm.assert_categorical_equal(result, expected)
659
+
660
+ @pytest.mark.parametrize("dtype", [None, "category"])
661
+ def test_from_inferred_categories_sorts(self, dtype):
662
+ cats = ["b", "a"]
663
+ codes = np.array([0, 1, 1, 1], dtype="i8")
664
+ result = Categorical._from_inferred_categories(cats, codes, dtype)
665
+ expected = Categorical.from_codes([1, 0, 0, 0], ["a", "b"])
666
+ tm.assert_categorical_equal(result, expected)
667
+
668
+ def test_from_inferred_categories_dtype(self):
669
+ cats = ["a", "b", "d"]
670
+ codes = np.array([0, 1, 0, 2], dtype="i8")
671
+ dtype = CategoricalDtype(["c", "b", "a"], ordered=True)
672
+ result = Categorical._from_inferred_categories(cats, codes, dtype)
673
+ expected = Categorical(
674
+ ["a", "b", "a", "d"], categories=["c", "b", "a"], ordered=True
675
+ )
676
+ tm.assert_categorical_equal(result, expected)
677
+
678
+ def test_from_inferred_categories_coerces(self):
679
+ cats = ["1", "2", "bad"]
680
+ codes = np.array([0, 0, 1, 2], dtype="i8")
681
+ dtype = CategoricalDtype([1, 2])
682
+ result = Categorical._from_inferred_categories(cats, codes, dtype)
683
+ expected = Categorical([1, 1, 2, np.nan])
684
+ tm.assert_categorical_equal(result, expected)
685
+
686
+ @pytest.mark.parametrize("ordered", [None, True, False])
687
+ def test_construction_with_ordered(self, ordered):
688
+ # GH 9347, 9190
689
+ cat = Categorical([0, 1, 2], ordered=ordered)
690
+ assert cat.ordered == bool(ordered)
691
+
692
+ def test_constructor_imaginary(self):
693
+ values = [1, 2, 3 + 1j]
694
+ c1 = Categorical(values)
695
+ tm.assert_index_equal(c1.categories, Index(values))
696
+ tm.assert_numpy_array_equal(np.array(c1), np.array(values))
697
+
698
+ def test_constructor_string_and_tuples(self):
699
+ # GH 21416
700
+ c = Categorical(np.array(["c", ("a", "b"), ("b", "a"), "c"], dtype=object))
701
+ expected_index = Index([("a", "b"), ("b", "a"), "c"])
702
+ assert c.categories.equals(expected_index)
703
+
704
+ def test_interval(self):
705
+ idx = pd.interval_range(0, 10, periods=10)
706
+ cat = Categorical(idx, categories=idx)
707
+ expected_codes = np.arange(10, dtype="int8")
708
+ tm.assert_numpy_array_equal(cat.codes, expected_codes)
709
+ tm.assert_index_equal(cat.categories, idx)
710
+
711
+ # infer categories
712
+ cat = Categorical(idx)
713
+ tm.assert_numpy_array_equal(cat.codes, expected_codes)
714
+ tm.assert_index_equal(cat.categories, idx)
715
+
716
+ # list values
717
+ cat = Categorical(list(idx))
718
+ tm.assert_numpy_array_equal(cat.codes, expected_codes)
719
+ tm.assert_index_equal(cat.categories, idx)
720
+
721
+ # list values, categories
722
+ cat = Categorical(list(idx), categories=list(idx))
723
+ tm.assert_numpy_array_equal(cat.codes, expected_codes)
724
+ tm.assert_index_equal(cat.categories, idx)
725
+
726
+ # shuffled
727
+ values = idx.take([1, 2, 0])
728
+ cat = Categorical(values, categories=idx)
729
+ tm.assert_numpy_array_equal(cat.codes, np.array([1, 2, 0], dtype="int8"))
730
+ tm.assert_index_equal(cat.categories, idx)
731
+
732
+ # extra
733
+ values = pd.interval_range(8, 11, periods=3)
734
+ cat = Categorical(values, categories=idx)
735
+ expected_codes = np.array([8, 9, -1], dtype="int8")
736
+ tm.assert_numpy_array_equal(cat.codes, expected_codes)
737
+ tm.assert_index_equal(cat.categories, idx)
738
+
739
+ # overlapping
740
+ idx = IntervalIndex([Interval(0, 2), Interval(0, 1)])
741
+ cat = Categorical(idx, categories=idx)
742
+ expected_codes = np.array([0, 1], dtype="int8")
743
+ tm.assert_numpy_array_equal(cat.codes, expected_codes)
744
+ tm.assert_index_equal(cat.categories, idx)
745
+
746
+ def test_categorical_extension_array_nullable(self, nulls_fixture):
747
+ # GH:
748
+ arr = pd.arrays.StringArray._from_sequence(
749
+ [nulls_fixture] * 2, dtype=pd.StringDtype()
750
+ )
751
+ result = Categorical(arr)
752
+ assert arr.dtype == result.categories.dtype
753
+ expected = Categorical(Series([pd.NA, pd.NA], dtype=arr.dtype))
754
+ tm.assert_categorical_equal(result, expected)
755
+
756
+ def test_from_sequence_copy(self):
757
+ cat = Categorical(np.arange(5).repeat(2))
758
+ result = Categorical._from_sequence(cat, dtype=cat.dtype, copy=False)
759
+
760
+ # more generally, we'd be OK with a view
761
+ assert result._codes is cat._codes
762
+
763
+ result = Categorical._from_sequence(cat, dtype=cat.dtype, copy=True)
764
+
765
+ assert not tm.shares_memory(result, cat)
766
+
767
+ def test_constructor_datetime64_non_nano(self):
768
+ categories = np.arange(10).view("M8[D]")
769
+ values = categories[::2].copy()
770
+
771
+ cat = Categorical(values, categories=categories)
772
+ assert (cat == values).all()
773
+
774
+ def test_constructor_preserves_freq(self):
775
+ # GH33830 freq retention in categorical
776
+ dti = date_range("2016-01-01", periods=5)
777
+
778
+ expected = dti.freq
779
+
780
+ cat = Categorical(dti)
781
+ result = cat.categories.freq
782
+
783
+ assert expected == result
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_dtypes.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas.core.dtypes.dtypes import CategoricalDtype
5
+
6
+ from pandas import (
7
+ Categorical,
8
+ CategoricalIndex,
9
+ Index,
10
+ IntervalIndex,
11
+ Series,
12
+ Timestamp,
13
+ )
14
+ import pandas._testing as tm
15
+
16
+
17
+ class TestCategoricalDtypes:
18
+ def test_categories_match_up_to_permutation(self):
19
+ # test dtype comparisons between cats
20
+
21
+ c1 = Categorical(list("aabca"), categories=list("abc"), ordered=False)
22
+ c2 = Categorical(list("aabca"), categories=list("cab"), ordered=False)
23
+ c3 = Categorical(list("aabca"), categories=list("cab"), ordered=True)
24
+ assert c1._categories_match_up_to_permutation(c1)
25
+ assert c2._categories_match_up_to_permutation(c2)
26
+ assert c3._categories_match_up_to_permutation(c3)
27
+ assert c1._categories_match_up_to_permutation(c2)
28
+ assert not c1._categories_match_up_to_permutation(c3)
29
+ assert not c1._categories_match_up_to_permutation(Index(list("aabca")))
30
+ assert not c1._categories_match_up_to_permutation(c1.astype(object))
31
+ assert c1._categories_match_up_to_permutation(CategoricalIndex(c1))
32
+ assert c1._categories_match_up_to_permutation(
33
+ CategoricalIndex(c1, categories=list("cab"))
34
+ )
35
+ assert not c1._categories_match_up_to_permutation(
36
+ CategoricalIndex(c1, ordered=True)
37
+ )
38
+
39
+ # GH 16659
40
+ s1 = Series(c1)
41
+ s2 = Series(c2)
42
+ s3 = Series(c3)
43
+ assert c1._categories_match_up_to_permutation(s1)
44
+ assert c2._categories_match_up_to_permutation(s2)
45
+ assert c3._categories_match_up_to_permutation(s3)
46
+ assert c1._categories_match_up_to_permutation(s2)
47
+ assert not c1._categories_match_up_to_permutation(s3)
48
+ assert not c1._categories_match_up_to_permutation(s1.astype(object))
49
+
50
+ def test_set_dtype_same(self):
51
+ c = Categorical(["a", "b", "c"])
52
+ result = c._set_dtype(CategoricalDtype(["a", "b", "c"]))
53
+ tm.assert_categorical_equal(result, c)
54
+
55
+ def test_set_dtype_new_categories(self):
56
+ c = Categorical(["a", "b", "c"])
57
+ result = c._set_dtype(CategoricalDtype(list("abcd")))
58
+ tm.assert_numpy_array_equal(result.codes, c.codes)
59
+ tm.assert_index_equal(result.dtype.categories, Index(list("abcd")))
60
+
61
+ @pytest.mark.parametrize(
62
+ "values, categories, new_categories",
63
+ [
64
+ # No NaNs, same cats, same order
65
+ (["a", "b", "a"], ["a", "b"], ["a", "b"]),
66
+ # No NaNs, same cats, different order
67
+ (["a", "b", "a"], ["a", "b"], ["b", "a"]),
68
+ # Same, unsorted
69
+ (["b", "a", "a"], ["a", "b"], ["a", "b"]),
70
+ # No NaNs, same cats, different order
71
+ (["b", "a", "a"], ["a", "b"], ["b", "a"]),
72
+ # NaNs
73
+ (["a", "b", "c"], ["a", "b"], ["a", "b"]),
74
+ (["a", "b", "c"], ["a", "b"], ["b", "a"]),
75
+ (["b", "a", "c"], ["a", "b"], ["a", "b"]),
76
+ (["b", "a", "c"], ["a", "b"], ["a", "b"]),
77
+ # Introduce NaNs
78
+ (["a", "b", "c"], ["a", "b"], ["a"]),
79
+ (["a", "b", "c"], ["a", "b"], ["b"]),
80
+ (["b", "a", "c"], ["a", "b"], ["a"]),
81
+ (["b", "a", "c"], ["a", "b"], ["a"]),
82
+ # No overlap
83
+ (["a", "b", "c"], ["a", "b"], ["d", "e"]),
84
+ ],
85
+ )
86
+ @pytest.mark.parametrize("ordered", [True, False])
87
+ def test_set_dtype_many(self, values, categories, new_categories, ordered):
88
+ c = Categorical(values, categories)
89
+ expected = Categorical(values, new_categories, ordered)
90
+ result = c._set_dtype(expected.dtype)
91
+ tm.assert_categorical_equal(result, expected)
92
+
93
+ def test_set_dtype_no_overlap(self):
94
+ c = Categorical(["a", "b", "c"], ["d", "e"])
95
+ result = c._set_dtype(CategoricalDtype(["a", "b"]))
96
+ expected = Categorical([None, None, None], categories=["a", "b"])
97
+ tm.assert_categorical_equal(result, expected)
98
+
99
+ def test_codes_dtypes(self):
100
+ # GH 8453
101
+ result = Categorical(["foo", "bar", "baz"])
102
+ assert result.codes.dtype == "int8"
103
+
104
+ result = Categorical([f"foo{i:05d}" for i in range(400)])
105
+ assert result.codes.dtype == "int16"
106
+
107
+ result = Categorical([f"foo{i:05d}" for i in range(40000)])
108
+ assert result.codes.dtype == "int32"
109
+
110
+ # adding cats
111
+ result = Categorical(["foo", "bar", "baz"])
112
+ assert result.codes.dtype == "int8"
113
+ result = result.add_categories([f"foo{i:05d}" for i in range(400)])
114
+ assert result.codes.dtype == "int16"
115
+
116
+ # removing cats
117
+ result = result.remove_categories([f"foo{i:05d}" for i in range(300)])
118
+ assert result.codes.dtype == "int8"
119
+
120
+ def test_iter_python_types(self):
121
+ # GH-19909
122
+ cat = Categorical([1, 2])
123
+ assert isinstance(next(iter(cat)), int)
124
+ assert isinstance(cat.tolist()[0], int)
125
+
126
+ def test_iter_python_types_datetime(self):
127
+ cat = Categorical([Timestamp("2017-01-01"), Timestamp("2017-01-02")])
128
+ assert isinstance(next(iter(cat)), Timestamp)
129
+ assert isinstance(cat.tolist()[0], Timestamp)
130
+
131
+ def test_interval_index_category(self):
132
+ # GH 38316
133
+ index = IntervalIndex.from_breaks(np.arange(3, dtype="uint64"))
134
+
135
+ result = CategoricalIndex(index).dtype.categories
136
+ expected = IntervalIndex.from_arrays(
137
+ [0, 1], [1, 2], dtype="interval[uint64, right]"
138
+ )
139
+ tm.assert_index_equal(result, expected)
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_indexing.py ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ from pandas import (
7
+ NA,
8
+ Categorical,
9
+ CategoricalIndex,
10
+ Index,
11
+ Interval,
12
+ IntervalIndex,
13
+ NaT,
14
+ PeriodIndex,
15
+ Series,
16
+ Timedelta,
17
+ Timestamp,
18
+ )
19
+ import pandas._testing as tm
20
+ import pandas.core.common as com
21
+
22
+
23
+ class TestCategoricalIndexingWithFactor:
24
+ def test_getitem(self):
25
+ factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)
26
+ assert factor[0] == "a"
27
+ assert factor[-1] == "c"
28
+
29
+ subf = factor[[0, 1, 2]]
30
+ tm.assert_numpy_array_equal(subf._codes, np.array([0, 1, 1], dtype=np.int8))
31
+
32
+ subf = factor[np.asarray(factor) == "c"]
33
+ tm.assert_numpy_array_equal(subf._codes, np.array([2, 2, 2], dtype=np.int8))
34
+
35
+ def test_setitem(self):
36
+ factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)
37
+ # int/positional
38
+ c = factor.copy()
39
+ c[0] = "b"
40
+ assert c[0] == "b"
41
+ c[-1] = "a"
42
+ assert c[-1] == "a"
43
+
44
+ # boolean
45
+ c = factor.copy()
46
+ indexer = np.zeros(len(c), dtype="bool")
47
+ indexer[0] = True
48
+ indexer[-1] = True
49
+ c[indexer] = "c"
50
+ expected = Categorical(["c", "b", "b", "a", "a", "c", "c", "c"], ordered=True)
51
+
52
+ tm.assert_categorical_equal(c, expected)
53
+
54
+ @pytest.mark.parametrize(
55
+ "other",
56
+ [Categorical(["b", "a"]), Categorical(["b", "a"], categories=["b", "a"])],
57
+ )
58
+ def test_setitem_same_but_unordered(self, other):
59
+ # GH-24142
60
+ target = Categorical(["a", "b"], categories=["a", "b"])
61
+ mask = np.array([True, False])
62
+ target[mask] = other[mask]
63
+ expected = Categorical(["b", "b"], categories=["a", "b"])
64
+ tm.assert_categorical_equal(target, expected)
65
+
66
+ @pytest.mark.parametrize(
67
+ "other",
68
+ [
69
+ Categorical(["b", "a"], categories=["b", "a", "c"]),
70
+ Categorical(["b", "a"], categories=["a", "b", "c"]),
71
+ Categorical(["a", "a"], categories=["a"]),
72
+ Categorical(["b", "b"], categories=["b"]),
73
+ ],
74
+ )
75
+ def test_setitem_different_unordered_raises(self, other):
76
+ # GH-24142
77
+ target = Categorical(["a", "b"], categories=["a", "b"])
78
+ mask = np.array([True, False])
79
+ msg = "Cannot set a Categorical with another, without identical categories"
80
+ with pytest.raises(TypeError, match=msg):
81
+ target[mask] = other[mask]
82
+
83
+ @pytest.mark.parametrize(
84
+ "other",
85
+ [
86
+ Categorical(["b", "a"]),
87
+ Categorical(["b", "a"], categories=["b", "a"], ordered=True),
88
+ Categorical(["b", "a"], categories=["a", "b", "c"], ordered=True),
89
+ ],
90
+ )
91
+ def test_setitem_same_ordered_raises(self, other):
92
+ # Gh-24142
93
+ target = Categorical(["a", "b"], categories=["a", "b"], ordered=True)
94
+ mask = np.array([True, False])
95
+ msg = "Cannot set a Categorical with another, without identical categories"
96
+ with pytest.raises(TypeError, match=msg):
97
+ target[mask] = other[mask]
98
+
99
+ def test_setitem_tuple(self):
100
+ # GH#20439
101
+ cat = Categorical([(0, 1), (0, 2), (0, 1)])
102
+
103
+ # This should not raise
104
+ cat[1] = cat[0]
105
+ assert cat[1] == (0, 1)
106
+
107
+ def test_setitem_listlike(self):
108
+ # GH#9469
109
+ # properly coerce the input indexers
110
+
111
+ cat = Categorical(
112
+ np.random.default_rng(2).integers(0, 5, size=150000).astype(np.int8)
113
+ ).add_categories([-1000])
114
+ indexer = np.array([100000]).astype(np.int64)
115
+ cat[indexer] = -1000
116
+
117
+ # we are asserting the code result here
118
+ # which maps to the -1000 category
119
+ result = cat.codes[np.array([100000]).astype(np.int64)]
120
+ tm.assert_numpy_array_equal(result, np.array([5], dtype="int8"))
121
+
122
+
123
+ class TestCategoricalIndexing:
124
+ def test_getitem_slice(self):
125
+ cat = Categorical(["a", "b", "c", "d", "a", "b", "c"])
126
+ sliced = cat[3]
127
+ assert sliced == "d"
128
+
129
+ sliced = cat[3:5]
130
+ expected = Categorical(["d", "a"], categories=["a", "b", "c", "d"])
131
+ tm.assert_categorical_equal(sliced, expected)
132
+
133
+ def test_getitem_listlike(self):
134
+ # GH 9469
135
+ # properly coerce the input indexers
136
+
137
+ c = Categorical(
138
+ np.random.default_rng(2).integers(0, 5, size=150000).astype(np.int8)
139
+ )
140
+ result = c.codes[np.array([100000]).astype(np.int64)]
141
+ expected = c[np.array([100000]).astype(np.int64)].codes
142
+ tm.assert_numpy_array_equal(result, expected)
143
+
144
+ def test_periodindex(self):
145
+ idx1 = PeriodIndex(
146
+ ["2014-01", "2014-01", "2014-02", "2014-02", "2014-03", "2014-03"],
147
+ freq="M",
148
+ )
149
+
150
+ cat1 = Categorical(idx1)
151
+ str(cat1)
152
+ exp_arr = np.array([0, 0, 1, 1, 2, 2], dtype=np.int8)
153
+ exp_idx = PeriodIndex(["2014-01", "2014-02", "2014-03"], freq="M")
154
+ tm.assert_numpy_array_equal(cat1._codes, exp_arr)
155
+ tm.assert_index_equal(cat1.categories, exp_idx)
156
+
157
+ idx2 = PeriodIndex(
158
+ ["2014-03", "2014-03", "2014-02", "2014-01", "2014-03", "2014-01"],
159
+ freq="M",
160
+ )
161
+ cat2 = Categorical(idx2, ordered=True)
162
+ str(cat2)
163
+ exp_arr = np.array([2, 2, 1, 0, 2, 0], dtype=np.int8)
164
+ exp_idx2 = PeriodIndex(["2014-01", "2014-02", "2014-03"], freq="M")
165
+ tm.assert_numpy_array_equal(cat2._codes, exp_arr)
166
+ tm.assert_index_equal(cat2.categories, exp_idx2)
167
+
168
+ idx3 = PeriodIndex(
169
+ [
170
+ "2013-12",
171
+ "2013-11",
172
+ "2013-10",
173
+ "2013-09",
174
+ "2013-08",
175
+ "2013-07",
176
+ "2013-05",
177
+ ],
178
+ freq="M",
179
+ )
180
+ cat3 = Categorical(idx3, ordered=True)
181
+ exp_arr = np.array([6, 5, 4, 3, 2, 1, 0], dtype=np.int8)
182
+ exp_idx = PeriodIndex(
183
+ [
184
+ "2013-05",
185
+ "2013-07",
186
+ "2013-08",
187
+ "2013-09",
188
+ "2013-10",
189
+ "2013-11",
190
+ "2013-12",
191
+ ],
192
+ freq="M",
193
+ )
194
+ tm.assert_numpy_array_equal(cat3._codes, exp_arr)
195
+ tm.assert_index_equal(cat3.categories, exp_idx)
196
+
197
+ @pytest.mark.parametrize(
198
+ "null_val",
199
+ [None, np.nan, NaT, NA, math.nan, "NaT", "nat", "NAT", "nan", "NaN", "NAN"],
200
+ )
201
+ def test_periodindex_on_null_types(self, null_val):
202
+ # GH 46673
203
+ result = PeriodIndex(["2022-04-06", "2022-04-07", null_val], freq="D")
204
+ expected = PeriodIndex(["2022-04-06", "2022-04-07", "NaT"], dtype="period[D]")
205
+ assert result[2] is NaT
206
+ tm.assert_index_equal(result, expected)
207
+
208
+ @pytest.mark.parametrize("new_categories", [[1, 2, 3, 4], [1, 2]])
209
+ def test_categories_assignments_wrong_length_raises(self, new_categories):
210
+ cat = Categorical(["a", "b", "c", "a"])
211
+ msg = (
212
+ "new categories need to have the same number of items "
213
+ "as the old categories!"
214
+ )
215
+ with pytest.raises(ValueError, match=msg):
216
+ cat.rename_categories(new_categories)
217
+
218
+ # Combinations of sorted/unique:
219
+ @pytest.mark.parametrize(
220
+ "idx_values", [[1, 2, 3, 4], [1, 3, 2, 4], [1, 3, 3, 4], [1, 2, 2, 4]]
221
+ )
222
+ # Combinations of missing/unique
223
+ @pytest.mark.parametrize("key_values", [[1, 2], [1, 5], [1, 1], [5, 5]])
224
+ @pytest.mark.parametrize("key_class", [Categorical, CategoricalIndex])
225
+ @pytest.mark.parametrize("dtype", [None, "category", "key"])
226
+ def test_get_indexer_non_unique(self, idx_values, key_values, key_class, dtype):
227
+ # GH 21448
228
+ key = key_class(key_values, categories=range(1, 5))
229
+
230
+ if dtype == "key":
231
+ dtype = key.dtype
232
+
233
+ # Test for flat index and CategoricalIndex with same/different cats:
234
+ idx = Index(idx_values, dtype=dtype)
235
+ expected, exp_miss = idx.get_indexer_non_unique(key_values)
236
+ result, res_miss = idx.get_indexer_non_unique(key)
237
+
238
+ tm.assert_numpy_array_equal(expected, result)
239
+ tm.assert_numpy_array_equal(exp_miss, res_miss)
240
+
241
+ exp_unique = idx.unique().get_indexer(key_values)
242
+ res_unique = idx.unique().get_indexer(key)
243
+ tm.assert_numpy_array_equal(res_unique, exp_unique)
244
+
245
+ def test_where_unobserved_nan(self):
246
+ ser = Series(Categorical(["a", "b"]))
247
+ result = ser.where([True, False])
248
+ expected = Series(Categorical(["a", None], categories=["a", "b"]))
249
+ tm.assert_series_equal(result, expected)
250
+
251
+ # all NA
252
+ ser = Series(Categorical(["a", "b"]))
253
+ result = ser.where([False, False])
254
+ expected = Series(Categorical([None, None], categories=["a", "b"]))
255
+ tm.assert_series_equal(result, expected)
256
+
257
+ def test_where_unobserved_categories(self):
258
+ ser = Series(Categorical(["a", "b", "c"], categories=["d", "c", "b", "a"]))
259
+ result = ser.where([True, True, False], other="b")
260
+ expected = Series(Categorical(["a", "b", "b"], categories=ser.cat.categories))
261
+ tm.assert_series_equal(result, expected)
262
+
263
+ def test_where_other_categorical(self):
264
+ ser = Series(Categorical(["a", "b", "c"], categories=["d", "c", "b", "a"]))
265
+ other = Categorical(["b", "c", "a"], categories=["a", "c", "b", "d"])
266
+ result = ser.where([True, False, True], other)
267
+ expected = Series(Categorical(["a", "c", "c"], dtype=ser.dtype))
268
+ tm.assert_series_equal(result, expected)
269
+
270
+ def test_where_new_category_raises(self):
271
+ ser = Series(Categorical(["a", "b", "c"]))
272
+ msg = "Cannot setitem on a Categorical with a new category"
273
+ with pytest.raises(TypeError, match=msg):
274
+ ser.where([True, False, True], "d")
275
+
276
+ def test_where_ordered_differs_rasies(self):
277
+ ser = Series(
278
+ Categorical(["a", "b", "c"], categories=["d", "c", "b", "a"], ordered=True)
279
+ )
280
+ other = Categorical(
281
+ ["b", "c", "a"], categories=["a", "c", "b", "d"], ordered=True
282
+ )
283
+ with pytest.raises(TypeError, match="without identical categories"):
284
+ ser.where([True, False, True], other)
285
+
286
+
287
+ class TestContains:
288
+ def test_contains(self):
289
+ # GH#21508
290
+ cat = Categorical(list("aabbca"), categories=list("cab"))
291
+
292
+ assert "b" in cat
293
+ assert "z" not in cat
294
+ assert np.nan not in cat
295
+ with pytest.raises(TypeError, match="unhashable type: 'list'"):
296
+ assert [1] in cat
297
+
298
+ # assert codes NOT in index
299
+ assert 0 not in cat
300
+ assert 1 not in cat
301
+
302
+ cat = Categorical(list("aabbca") + [np.nan], categories=list("cab"))
303
+ assert np.nan in cat
304
+
305
+ @pytest.mark.parametrize(
306
+ "item, expected",
307
+ [
308
+ (Interval(0, 1), True),
309
+ (1.5, True),
310
+ (Interval(0.5, 1.5), False),
311
+ ("a", False),
312
+ (Timestamp(1), False),
313
+ (Timedelta(1), False),
314
+ ],
315
+ ids=str,
316
+ )
317
+ def test_contains_interval(self, item, expected):
318
+ # GH#23705
319
+ cat = Categorical(IntervalIndex.from_breaks(range(3)))
320
+ result = item in cat
321
+ assert result is expected
322
+
323
+ def test_contains_list(self):
324
+ # GH#21729
325
+ cat = Categorical([1, 2, 3])
326
+
327
+ assert "a" not in cat
328
+
329
+ with pytest.raises(TypeError, match="unhashable type"):
330
+ ["a"] in cat
331
+
332
+ with pytest.raises(TypeError, match="unhashable type"):
333
+ ["a", "b"] in cat
334
+
335
+
336
+ @pytest.mark.parametrize("index", [True, False])
337
+ def test_mask_with_boolean(index):
338
+ ser = Series(range(3))
339
+ idx = Categorical([True, False, True])
340
+ if index:
341
+ idx = CategoricalIndex(idx)
342
+
343
+ assert com.is_bool_indexer(idx)
344
+ result = ser[idx]
345
+ expected = ser[idx.astype("object")]
346
+ tm.assert_series_equal(result, expected)
347
+
348
+
349
+ @pytest.mark.parametrize("index", [True, False])
350
+ def test_mask_with_boolean_na_treated_as_false(index):
351
+ # https://github.com/pandas-dev/pandas/issues/31503
352
+ ser = Series(range(3))
353
+ idx = Categorical([True, False, None])
354
+ if index:
355
+ idx = CategoricalIndex(idx)
356
+
357
+ result = ser[idx]
358
+ expected = ser[idx.fillna(False)]
359
+
360
+ tm.assert_series_equal(result, expected)
361
+
362
+
363
+ @pytest.fixture
364
+ def non_coercible_categorical(monkeypatch):
365
+ """
366
+ Monkeypatch Categorical.__array__ to ensure no implicit conversion.
367
+
368
+ Raises
369
+ ------
370
+ ValueError
371
+ When Categorical.__array__ is called.
372
+ """
373
+
374
+ # TODO(Categorical): identify other places where this may be
375
+ # useful and move to a conftest.py
376
+ def array(self, dtype=None):
377
+ raise ValueError("I cannot be converted.")
378
+
379
+ with monkeypatch.context() as m:
380
+ m.setattr(Categorical, "__array__", array)
381
+ yield
382
+
383
+
384
+ def test_series_at():
385
+ arr = Categorical(["a", "b", "c"])
386
+ ser = Series(arr)
387
+ result = ser.at[0]
388
+ assert result == "a"
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_map.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ import pandas as pd
5
+ from pandas import (
6
+ Categorical,
7
+ Index,
8
+ Series,
9
+ )
10
+ import pandas._testing as tm
11
+
12
+
13
+ @pytest.fixture(params=[None, "ignore"])
14
+ def na_action(request):
15
+ return request.param
16
+
17
+
18
+ @pytest.mark.parametrize(
19
+ "data, categories",
20
+ [
21
+ (list("abcbca"), list("cab")),
22
+ (pd.interval_range(0, 3).repeat(3), pd.interval_range(0, 3)),
23
+ ],
24
+ ids=["string", "interval"],
25
+ )
26
+ def test_map_str(data, categories, ordered, na_action):
27
+ # GH 31202 - override base class since we want to maintain categorical/ordered
28
+ cat = Categorical(data, categories=categories, ordered=ordered)
29
+ result = cat.map(str, na_action=na_action)
30
+ expected = Categorical(
31
+ map(str, data), categories=map(str, categories), ordered=ordered
32
+ )
33
+ tm.assert_categorical_equal(result, expected)
34
+
35
+
36
+ def test_map(na_action):
37
+ cat = Categorical(list("ABABC"), categories=list("CBA"), ordered=True)
38
+ result = cat.map(lambda x: x.lower(), na_action=na_action)
39
+ exp = Categorical(list("ababc"), categories=list("cba"), ordered=True)
40
+ tm.assert_categorical_equal(result, exp)
41
+
42
+ cat = Categorical(list("ABABC"), categories=list("BAC"), ordered=False)
43
+ result = cat.map(lambda x: x.lower(), na_action=na_action)
44
+ exp = Categorical(list("ababc"), categories=list("bac"), ordered=False)
45
+ tm.assert_categorical_equal(result, exp)
46
+
47
+ # GH 12766: Return an index not an array
48
+ result = cat.map(lambda x: 1, na_action=na_action)
49
+ exp = Index(np.array([1] * 5, dtype=np.int64))
50
+ tm.assert_index_equal(result, exp)
51
+
52
+ # change categories dtype
53
+ cat = Categorical(list("ABABC"), categories=list("BAC"), ordered=False)
54
+
55
+ def f(x):
56
+ return {"A": 10, "B": 20, "C": 30}.get(x)
57
+
58
+ result = cat.map(f, na_action=na_action)
59
+ exp = Categorical([10, 20, 10, 20, 30], categories=[20, 10, 30], ordered=False)
60
+ tm.assert_categorical_equal(result, exp)
61
+
62
+ mapper = Series([10, 20, 30], index=["A", "B", "C"])
63
+ result = cat.map(mapper, na_action=na_action)
64
+ tm.assert_categorical_equal(result, exp)
65
+
66
+ result = cat.map({"A": 10, "B": 20, "C": 30}, na_action=na_action)
67
+ tm.assert_categorical_equal(result, exp)
68
+
69
+
70
+ @pytest.mark.parametrize(
71
+ ("data", "f", "expected"),
72
+ (
73
+ ([1, 1, np.nan], pd.isna, Index([False, False, True])),
74
+ ([1, 2, np.nan], pd.isna, Index([False, False, True])),
75
+ ([1, 1, np.nan], {1: False}, Categorical([False, False, np.nan])),
76
+ ([1, 2, np.nan], {1: False, 2: False}, Index([False, False, np.nan])),
77
+ (
78
+ [1, 1, np.nan],
79
+ Series([False, False]),
80
+ Categorical([False, False, np.nan]),
81
+ ),
82
+ (
83
+ [1, 2, np.nan],
84
+ Series([False] * 3),
85
+ Index([False, False, np.nan]),
86
+ ),
87
+ ),
88
+ )
89
+ def test_map_with_nan_none(data, f, expected): # GH 24241
90
+ values = Categorical(data)
91
+ result = values.map(f, na_action=None)
92
+ if isinstance(expected, Categorical):
93
+ tm.assert_categorical_equal(result, expected)
94
+ else:
95
+ tm.assert_index_equal(result, expected)
96
+
97
+
98
+ @pytest.mark.parametrize(
99
+ ("data", "f", "expected"),
100
+ (
101
+ ([1, 1, np.nan], pd.isna, Categorical([False, False, np.nan])),
102
+ ([1, 2, np.nan], pd.isna, Index([False, False, np.nan])),
103
+ ([1, 1, np.nan], {1: False}, Categorical([False, False, np.nan])),
104
+ ([1, 2, np.nan], {1: False, 2: False}, Index([False, False, np.nan])),
105
+ (
106
+ [1, 1, np.nan],
107
+ Series([False, False]),
108
+ Categorical([False, False, np.nan]),
109
+ ),
110
+ (
111
+ [1, 2, np.nan],
112
+ Series([False, False, False]),
113
+ Index([False, False, np.nan]),
114
+ ),
115
+ ),
116
+ )
117
+ def test_map_with_nan_ignore(data, f, expected): # GH 24241
118
+ values = Categorical(data)
119
+ result = values.map(f, na_action="ignore")
120
+ if data[1] == 1:
121
+ tm.assert_categorical_equal(result, expected)
122
+ else:
123
+ tm.assert_index_equal(result, expected)
124
+
125
+
126
+ def test_map_with_dict_or_series(na_action):
127
+ orig_values = ["a", "B", 1, "a"]
128
+ new_values = ["one", 2, 3.0, "one"]
129
+ cat = Categorical(orig_values)
130
+
131
+ mapper = Series(new_values[:-1], index=orig_values[:-1])
132
+ result = cat.map(mapper, na_action=na_action)
133
+
134
+ # Order of categories in result can be different
135
+ expected = Categorical(new_values, categories=[3.0, 2, "one"])
136
+ tm.assert_categorical_equal(result, expected)
137
+
138
+ mapper = dict(zip(orig_values[:-1], new_values[:-1]))
139
+ result = cat.map(mapper, na_action=na_action)
140
+ # Order of categories in result can be different
141
+ tm.assert_categorical_equal(result, expected)
142
+
143
+
144
+ def test_map_na_action_no_default_deprecated():
145
+ # GH51645
146
+ cat = Categorical(["a", "b", "c"])
147
+ msg = (
148
+ "The default value of 'ignore' for the `na_action` parameter in "
149
+ "pandas.Categorical.map is deprecated and will be "
150
+ "changed to 'None' in a future version. Please set na_action to the "
151
+ "desired value to avoid seeing this warning"
152
+ )
153
+ with tm.assert_produces_warning(FutureWarning, match=msg):
154
+ cat.map(lambda x: x)
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_operators.py ADDED
@@ -0,0 +1,414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ import pandas as pd
5
+ from pandas import (
6
+ Categorical,
7
+ DataFrame,
8
+ Series,
9
+ Timestamp,
10
+ date_range,
11
+ )
12
+ import pandas._testing as tm
13
+
14
+
15
+ class TestCategoricalOpsWithFactor:
16
+ def test_categories_none_comparisons(self):
17
+ factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)
18
+ tm.assert_categorical_equal(factor, factor)
19
+
20
+ def test_comparisons(self):
21
+ factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)
22
+ result = factor[factor == "a"]
23
+ expected = factor[np.asarray(factor) == "a"]
24
+ tm.assert_categorical_equal(result, expected)
25
+
26
+ result = factor[factor != "a"]
27
+ expected = factor[np.asarray(factor) != "a"]
28
+ tm.assert_categorical_equal(result, expected)
29
+
30
+ result = factor[factor < "c"]
31
+ expected = factor[np.asarray(factor) < "c"]
32
+ tm.assert_categorical_equal(result, expected)
33
+
34
+ result = factor[factor > "a"]
35
+ expected = factor[np.asarray(factor) > "a"]
36
+ tm.assert_categorical_equal(result, expected)
37
+
38
+ result = factor[factor >= "b"]
39
+ expected = factor[np.asarray(factor) >= "b"]
40
+ tm.assert_categorical_equal(result, expected)
41
+
42
+ result = factor[factor <= "b"]
43
+ expected = factor[np.asarray(factor) <= "b"]
44
+ tm.assert_categorical_equal(result, expected)
45
+
46
+ n = len(factor)
47
+
48
+ other = factor[np.random.default_rng(2).permutation(n)]
49
+ result = factor == other
50
+ expected = np.asarray(factor) == np.asarray(other)
51
+ tm.assert_numpy_array_equal(result, expected)
52
+
53
+ result = factor == "d"
54
+ expected = np.zeros(len(factor), dtype=bool)
55
+ tm.assert_numpy_array_equal(result, expected)
56
+
57
+ # comparisons with categoricals
58
+ cat_rev = Categorical(["a", "b", "c"], categories=["c", "b", "a"], ordered=True)
59
+ cat_rev_base = Categorical(
60
+ ["b", "b", "b"], categories=["c", "b", "a"], ordered=True
61
+ )
62
+ cat = Categorical(["a", "b", "c"], ordered=True)
63
+ cat_base = Categorical(["b", "b", "b"], categories=cat.categories, ordered=True)
64
+
65
+ # comparisons need to take categories ordering into account
66
+ res_rev = cat_rev > cat_rev_base
67
+ exp_rev = np.array([True, False, False])
68
+ tm.assert_numpy_array_equal(res_rev, exp_rev)
69
+
70
+ res_rev = cat_rev < cat_rev_base
71
+ exp_rev = np.array([False, False, True])
72
+ tm.assert_numpy_array_equal(res_rev, exp_rev)
73
+
74
+ res = cat > cat_base
75
+ exp = np.array([False, False, True])
76
+ tm.assert_numpy_array_equal(res, exp)
77
+
78
+ # Only categories with same categories can be compared
79
+ msg = "Categoricals can only be compared if 'categories' are the same"
80
+ with pytest.raises(TypeError, match=msg):
81
+ cat > cat_rev
82
+
83
+ cat_rev_base2 = Categorical(["b", "b", "b"], categories=["c", "b", "a", "d"])
84
+
85
+ with pytest.raises(TypeError, match=msg):
86
+ cat_rev > cat_rev_base2
87
+
88
+ # Only categories with same ordering information can be compared
89
+ cat_unordered = cat.set_ordered(False)
90
+ assert not (cat > cat).any()
91
+
92
+ with pytest.raises(TypeError, match=msg):
93
+ cat > cat_unordered
94
+
95
+ # comparison (in both directions) with Series will raise
96
+ s = Series(["b", "b", "b"], dtype=object)
97
+ msg = (
98
+ "Cannot compare a Categorical for op __gt__ with type "
99
+ r"<class 'numpy\.ndarray'>"
100
+ )
101
+ with pytest.raises(TypeError, match=msg):
102
+ cat > s
103
+ with pytest.raises(TypeError, match=msg):
104
+ cat_rev > s
105
+ with pytest.raises(TypeError, match=msg):
106
+ s < cat
107
+ with pytest.raises(TypeError, match=msg):
108
+ s < cat_rev
109
+
110
+ # comparison with numpy.array will raise in both direction, but only on
111
+ # newer numpy versions
112
+ a = np.array(["b", "b", "b"], dtype=object)
113
+ with pytest.raises(TypeError, match=msg):
114
+ cat > a
115
+ with pytest.raises(TypeError, match=msg):
116
+ cat_rev > a
117
+
118
+ # Make sure that unequal comparison take the categories order in
119
+ # account
120
+ cat_rev = Categorical(list("abc"), categories=list("cba"), ordered=True)
121
+ exp = np.array([True, False, False])
122
+ res = cat_rev > "b"
123
+ tm.assert_numpy_array_equal(res, exp)
124
+
125
+ # check that zero-dim array gets unboxed
126
+ res = cat_rev > np.array("b")
127
+ tm.assert_numpy_array_equal(res, exp)
128
+
129
+
130
+ class TestCategoricalOps:
131
+ @pytest.mark.parametrize(
132
+ "categories",
133
+ [["a", "b"], [0, 1], [Timestamp("2019"), Timestamp("2020")]],
134
+ )
135
+ def test_not_equal_with_na(self, categories):
136
+ # https://github.com/pandas-dev/pandas/issues/32276
137
+ c1 = Categorical.from_codes([-1, 0], categories=categories)
138
+ c2 = Categorical.from_codes([0, 1], categories=categories)
139
+
140
+ result = c1 != c2
141
+
142
+ assert result.all()
143
+
144
+ def test_compare_frame(self):
145
+ # GH#24282 check that Categorical.__cmp__(DataFrame) defers to frame
146
+ data = ["a", "b", 2, "a"]
147
+ cat = Categorical(data)
148
+
149
+ df = DataFrame(cat)
150
+
151
+ result = cat == df.T
152
+ expected = DataFrame([[True, True, True, True]])
153
+ tm.assert_frame_equal(result, expected)
154
+
155
+ result = cat[::-1] != df.T
156
+ expected = DataFrame([[False, True, True, False]])
157
+ tm.assert_frame_equal(result, expected)
158
+
159
+ def test_compare_frame_raises(self, comparison_op):
160
+ # alignment raises unless we transpose
161
+ op = comparison_op
162
+ cat = Categorical(["a", "b", 2, "a"])
163
+ df = DataFrame(cat)
164
+ msg = "Unable to coerce to Series, length must be 1: given 4"
165
+ with pytest.raises(ValueError, match=msg):
166
+ op(cat, df)
167
+
168
+ def test_datetime_categorical_comparison(self):
169
+ dt_cat = Categorical(date_range("2014-01-01", periods=3), ordered=True)
170
+ tm.assert_numpy_array_equal(dt_cat > dt_cat[0], np.array([False, True, True]))
171
+ tm.assert_numpy_array_equal(dt_cat[0] < dt_cat, np.array([False, True, True]))
172
+
173
+ def test_reflected_comparison_with_scalars(self):
174
+ # GH8658
175
+ cat = Categorical([1, 2, 3], ordered=True)
176
+ tm.assert_numpy_array_equal(cat > cat[0], np.array([False, True, True]))
177
+ tm.assert_numpy_array_equal(cat[0] < cat, np.array([False, True, True]))
178
+
179
+ def test_comparison_with_unknown_scalars(self):
180
+ # https://github.com/pandas-dev/pandas/issues/9836#issuecomment-92123057
181
+ # and following comparisons with scalars not in categories should raise
182
+ # for unequal comps, but not for equal/not equal
183
+ cat = Categorical([1, 2, 3], ordered=True)
184
+
185
+ msg = "Invalid comparison between dtype=category and int"
186
+ with pytest.raises(TypeError, match=msg):
187
+ cat < 4
188
+ with pytest.raises(TypeError, match=msg):
189
+ cat > 4
190
+ with pytest.raises(TypeError, match=msg):
191
+ 4 < cat
192
+ with pytest.raises(TypeError, match=msg):
193
+ 4 > cat
194
+
195
+ tm.assert_numpy_array_equal(cat == 4, np.array([False, False, False]))
196
+ tm.assert_numpy_array_equal(cat != 4, np.array([True, True, True]))
197
+
198
+ def test_comparison_with_tuple(self):
199
+ cat = Categorical(np.array(["foo", (0, 1), 3, (0, 1)], dtype=object))
200
+
201
+ result = cat == "foo"
202
+ expected = np.array([True, False, False, False], dtype=bool)
203
+ tm.assert_numpy_array_equal(result, expected)
204
+
205
+ result = cat == (0, 1)
206
+ expected = np.array([False, True, False, True], dtype=bool)
207
+ tm.assert_numpy_array_equal(result, expected)
208
+
209
+ result = cat != (0, 1)
210
+ tm.assert_numpy_array_equal(result, ~expected)
211
+
212
+ @pytest.mark.filterwarnings("ignore::RuntimeWarning")
213
+ def test_comparison_of_ordered_categorical_with_nan_to_scalar(
214
+ self, compare_operators_no_eq_ne
215
+ ):
216
+ # https://github.com/pandas-dev/pandas/issues/26504
217
+ # BUG: fix ordered categorical comparison with missing values (#26504 )
218
+ # and following comparisons with scalars in categories with missing
219
+ # values should be evaluated as False
220
+
221
+ cat = Categorical([1, 2, 3, None], categories=[1, 2, 3], ordered=True)
222
+ scalar = 2
223
+ expected = getattr(np.array(cat), compare_operators_no_eq_ne)(scalar)
224
+ actual = getattr(cat, compare_operators_no_eq_ne)(scalar)
225
+ tm.assert_numpy_array_equal(actual, expected)
226
+
227
+ @pytest.mark.filterwarnings("ignore::RuntimeWarning")
228
+ def test_comparison_of_ordered_categorical_with_nan_to_listlike(
229
+ self, compare_operators_no_eq_ne
230
+ ):
231
+ # https://github.com/pandas-dev/pandas/issues/26504
232
+ # and following comparisons of missing values in ordered Categorical
233
+ # with listlike should be evaluated as False
234
+
235
+ cat = Categorical([1, 2, 3, None], categories=[1, 2, 3], ordered=True)
236
+ other = Categorical([2, 2, 2, 2], categories=[1, 2, 3], ordered=True)
237
+ expected = getattr(np.array(cat), compare_operators_no_eq_ne)(2)
238
+ actual = getattr(cat, compare_operators_no_eq_ne)(other)
239
+ tm.assert_numpy_array_equal(actual, expected)
240
+
241
+ @pytest.mark.parametrize(
242
+ "data,reverse,base",
243
+ [(list("abc"), list("cba"), list("bbb")), ([1, 2, 3], [3, 2, 1], [2, 2, 2])],
244
+ )
245
+ def test_comparisons(self, data, reverse, base):
246
+ cat_rev = Series(Categorical(data, categories=reverse, ordered=True))
247
+ cat_rev_base = Series(Categorical(base, categories=reverse, ordered=True))
248
+ cat = Series(Categorical(data, ordered=True))
249
+ cat_base = Series(
250
+ Categorical(base, categories=cat.cat.categories, ordered=True)
251
+ )
252
+ s = Series(base, dtype=object if base == list("bbb") else None)
253
+ a = np.array(base)
254
+
255
+ # comparisons need to take categories ordering into account
256
+ res_rev = cat_rev > cat_rev_base
257
+ exp_rev = Series([True, False, False])
258
+ tm.assert_series_equal(res_rev, exp_rev)
259
+
260
+ res_rev = cat_rev < cat_rev_base
261
+ exp_rev = Series([False, False, True])
262
+ tm.assert_series_equal(res_rev, exp_rev)
263
+
264
+ res = cat > cat_base
265
+ exp = Series([False, False, True])
266
+ tm.assert_series_equal(res, exp)
267
+
268
+ scalar = base[1]
269
+ res = cat > scalar
270
+ exp = Series([False, False, True])
271
+ exp2 = cat.values > scalar
272
+ tm.assert_series_equal(res, exp)
273
+ tm.assert_numpy_array_equal(res.values, exp2)
274
+ res_rev = cat_rev > scalar
275
+ exp_rev = Series([True, False, False])
276
+ exp_rev2 = cat_rev.values > scalar
277
+ tm.assert_series_equal(res_rev, exp_rev)
278
+ tm.assert_numpy_array_equal(res_rev.values, exp_rev2)
279
+
280
+ # Only categories with same categories can be compared
281
+ msg = "Categoricals can only be compared if 'categories' are the same"
282
+ with pytest.raises(TypeError, match=msg):
283
+ cat > cat_rev
284
+
285
+ # categorical cannot be compared to Series or numpy array, and also
286
+ # not the other way around
287
+ msg = (
288
+ "Cannot compare a Categorical for op __gt__ with type "
289
+ r"<class 'numpy\.ndarray'>"
290
+ )
291
+ with pytest.raises(TypeError, match=msg):
292
+ cat > s
293
+ with pytest.raises(TypeError, match=msg):
294
+ cat_rev > s
295
+ with pytest.raises(TypeError, match=msg):
296
+ cat > a
297
+ with pytest.raises(TypeError, match=msg):
298
+ cat_rev > a
299
+
300
+ with pytest.raises(TypeError, match=msg):
301
+ s < cat
302
+ with pytest.raises(TypeError, match=msg):
303
+ s < cat_rev
304
+
305
+ with pytest.raises(TypeError, match=msg):
306
+ a < cat
307
+ with pytest.raises(TypeError, match=msg):
308
+ a < cat_rev
309
+
310
+ @pytest.mark.parametrize(
311
+ "ctor",
312
+ [
313
+ lambda *args, **kwargs: Categorical(*args, **kwargs),
314
+ lambda *args, **kwargs: Series(Categorical(*args, **kwargs)),
315
+ ],
316
+ )
317
+ def test_unordered_different_order_equal(self, ctor):
318
+ # https://github.com/pandas-dev/pandas/issues/16014
319
+ c1 = ctor(["a", "b"], categories=["a", "b"], ordered=False)
320
+ c2 = ctor(["a", "b"], categories=["b", "a"], ordered=False)
321
+ assert (c1 == c2).all()
322
+
323
+ c1 = ctor(["a", "b"], categories=["a", "b"], ordered=False)
324
+ c2 = ctor(["b", "a"], categories=["b", "a"], ordered=False)
325
+ assert (c1 != c2).all()
326
+
327
+ c1 = ctor(["a", "a"], categories=["a", "b"], ordered=False)
328
+ c2 = ctor(["b", "b"], categories=["b", "a"], ordered=False)
329
+ assert (c1 != c2).all()
330
+
331
+ c1 = ctor(["a", "a"], categories=["a", "b"], ordered=False)
332
+ c2 = ctor(["a", "b"], categories=["b", "a"], ordered=False)
333
+ result = c1 == c2
334
+ tm.assert_numpy_array_equal(np.array(result), np.array([True, False]))
335
+
336
+ def test_unordered_different_categories_raises(self):
337
+ c1 = Categorical(["a", "b"], categories=["a", "b"], ordered=False)
338
+ c2 = Categorical(["a", "c"], categories=["c", "a"], ordered=False)
339
+
340
+ with pytest.raises(TypeError, match=("Categoricals can only be compared")):
341
+ c1 == c2
342
+
343
+ def test_compare_different_lengths(self):
344
+ c1 = Categorical([], categories=["a", "b"])
345
+ c2 = Categorical([], categories=["a"])
346
+
347
+ msg = "Categoricals can only be compared if 'categories' are the same."
348
+ with pytest.raises(TypeError, match=msg):
349
+ c1 == c2
350
+
351
+ def test_compare_unordered_different_order(self):
352
+ # https://github.com/pandas-dev/pandas/issues/16603#issuecomment-
353
+ # 349290078
354
+ a = Categorical(["a"], categories=["a", "b"])
355
+ b = Categorical(["b"], categories=["b", "a"])
356
+ assert not a.equals(b)
357
+
358
+ def test_numeric_like_ops(self):
359
+ df = DataFrame({"value": np.random.default_rng(2).integers(0, 10000, 100)})
360
+ labels = [f"{i} - {i + 499}" for i in range(0, 10000, 500)]
361
+ cat_labels = Categorical(labels, labels)
362
+
363
+ df = df.sort_values(by=["value"], ascending=True)
364
+ df["value_group"] = pd.cut(
365
+ df.value, range(0, 10500, 500), right=False, labels=cat_labels
366
+ )
367
+
368
+ # numeric ops should not succeed
369
+ for op, str_rep in [
370
+ ("__add__", r"\+"),
371
+ ("__sub__", "-"),
372
+ ("__mul__", r"\*"),
373
+ ("__truediv__", "/"),
374
+ ]:
375
+ msg = f"Series cannot perform the operation {str_rep}|unsupported operand"
376
+ with pytest.raises(TypeError, match=msg):
377
+ getattr(df, op)(df)
378
+
379
+ # reduction ops should not succeed (unless specifically defined, e.g.
380
+ # min/max)
381
+ s = df["value_group"]
382
+ for op in ["kurt", "skew", "var", "std", "mean", "sum", "median"]:
383
+ msg = f"does not support reduction '{op}'"
384
+ with pytest.raises(TypeError, match=msg):
385
+ getattr(s, op)(numeric_only=False)
386
+
387
+ def test_numeric_like_ops_series(self):
388
+ # numpy ops
389
+ s = Series(Categorical([1, 2, 3, 4]))
390
+ with pytest.raises(TypeError, match="does not support reduction 'sum'"):
391
+ np.sum(s)
392
+
393
+ @pytest.mark.parametrize(
394
+ "op, str_rep",
395
+ [
396
+ ("__add__", r"\+"),
397
+ ("__sub__", "-"),
398
+ ("__mul__", r"\*"),
399
+ ("__truediv__", "/"),
400
+ ],
401
+ )
402
+ def test_numeric_like_ops_series_arith(self, op, str_rep):
403
+ # numeric ops on a Series
404
+ s = Series(Categorical([1, 2, 3, 4]))
405
+ msg = f"Series cannot perform the operation {str_rep}|unsupported operand"
406
+ with pytest.raises(TypeError, match=msg):
407
+ getattr(s, op)(2)
408
+
409
+ def test_numeric_like_ops_series_invalid(self):
410
+ # invalid ufunc
411
+ s = Series(Categorical([1, 2, 3, 4]))
412
+ msg = "Object with dtype category cannot perform the numpy op log"
413
+ with pytest.raises(TypeError, match=msg):
414
+ np.log(s)
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_sorting.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas import (
5
+ Categorical,
6
+ Index,
7
+ )
8
+ import pandas._testing as tm
9
+
10
+
11
+ class TestCategoricalSort:
12
+ def test_argsort(self):
13
+ c = Categorical([5, 3, 1, 4, 2], ordered=True)
14
+
15
+ expected = np.array([2, 4, 1, 3, 0])
16
+ tm.assert_numpy_array_equal(
17
+ c.argsort(ascending=True), expected, check_dtype=False
18
+ )
19
+
20
+ expected = expected[::-1]
21
+ tm.assert_numpy_array_equal(
22
+ c.argsort(ascending=False), expected, check_dtype=False
23
+ )
24
+
25
+ def test_numpy_argsort(self):
26
+ c = Categorical([5, 3, 1, 4, 2], ordered=True)
27
+
28
+ expected = np.array([2, 4, 1, 3, 0])
29
+ tm.assert_numpy_array_equal(np.argsort(c), expected, check_dtype=False)
30
+
31
+ tm.assert_numpy_array_equal(
32
+ np.argsort(c, kind="mergesort"), expected, check_dtype=False
33
+ )
34
+
35
+ msg = "the 'axis' parameter is not supported"
36
+ with pytest.raises(ValueError, match=msg):
37
+ np.argsort(c, axis=0)
38
+
39
+ msg = "the 'order' parameter is not supported"
40
+ with pytest.raises(ValueError, match=msg):
41
+ np.argsort(c, order="C")
42
+
43
+ def test_sort_values(self):
44
+ # unordered cats are sortable
45
+ cat = Categorical(["a", "b", "b", "a"], ordered=False)
46
+ cat.sort_values()
47
+
48
+ cat = Categorical(["a", "c", "b", "d"], ordered=True)
49
+
50
+ # sort_values
51
+ res = cat.sort_values()
52
+ exp = np.array(["a", "b", "c", "d"], dtype=object)
53
+ tm.assert_numpy_array_equal(res.__array__(), exp)
54
+ tm.assert_index_equal(res.categories, cat.categories)
55
+
56
+ cat = Categorical(
57
+ ["a", "c", "b", "d"], categories=["a", "b", "c", "d"], ordered=True
58
+ )
59
+ res = cat.sort_values()
60
+ exp = np.array(["a", "b", "c", "d"], dtype=object)
61
+ tm.assert_numpy_array_equal(res.__array__(), exp)
62
+ tm.assert_index_equal(res.categories, cat.categories)
63
+
64
+ res = cat.sort_values(ascending=False)
65
+ exp = np.array(["d", "c", "b", "a"], dtype=object)
66
+ tm.assert_numpy_array_equal(res.__array__(), exp)
67
+ tm.assert_index_equal(res.categories, cat.categories)
68
+
69
+ # sort (inplace order)
70
+ cat1 = cat.copy()
71
+ orig_codes = cat1._codes
72
+ cat1.sort_values(inplace=True)
73
+ assert cat1._codes is orig_codes
74
+ exp = np.array(["a", "b", "c", "d"], dtype=object)
75
+ tm.assert_numpy_array_equal(cat1.__array__(), exp)
76
+ tm.assert_index_equal(res.categories, cat.categories)
77
+
78
+ # reverse
79
+ cat = Categorical(["a", "c", "c", "b", "d"], ordered=True)
80
+ res = cat.sort_values(ascending=False)
81
+ exp_val = np.array(["d", "c", "c", "b", "a"], dtype=object)
82
+ exp_categories = Index(["a", "b", "c", "d"])
83
+ tm.assert_numpy_array_equal(res.__array__(), exp_val)
84
+ tm.assert_index_equal(res.categories, exp_categories)
85
+
86
+ def test_sort_values_na_position(self):
87
+ # see gh-12882
88
+ cat = Categorical([5, 2, np.nan, 2, np.nan], ordered=True)
89
+ exp_categories = Index([2, 5])
90
+
91
+ exp = np.array([2.0, 2.0, 5.0, np.nan, np.nan])
92
+ res = cat.sort_values() # default arguments
93
+ tm.assert_numpy_array_equal(res.__array__(), exp)
94
+ tm.assert_index_equal(res.categories, exp_categories)
95
+
96
+ exp = np.array([np.nan, np.nan, 2.0, 2.0, 5.0])
97
+ res = cat.sort_values(ascending=True, na_position="first")
98
+ tm.assert_numpy_array_equal(res.__array__(), exp)
99
+ tm.assert_index_equal(res.categories, exp_categories)
100
+
101
+ exp = np.array([np.nan, np.nan, 5.0, 2.0, 2.0])
102
+ res = cat.sort_values(ascending=False, na_position="first")
103
+ tm.assert_numpy_array_equal(res.__array__(), exp)
104
+ tm.assert_index_equal(res.categories, exp_categories)
105
+
106
+ exp = np.array([2.0, 2.0, 5.0, np.nan, np.nan])
107
+ res = cat.sort_values(ascending=True, na_position="last")
108
+ tm.assert_numpy_array_equal(res.__array__(), exp)
109
+ tm.assert_index_equal(res.categories, exp_categories)
110
+
111
+ exp = np.array([5.0, 2.0, 2.0, np.nan, np.nan])
112
+ res = cat.sort_values(ascending=False, na_position="last")
113
+ tm.assert_numpy_array_equal(res.__array__(), exp)
114
+ tm.assert_index_equal(res.categories, exp_categories)
115
+
116
+ cat = Categorical(["a", "c", "b", "d", np.nan], ordered=True)
117
+ res = cat.sort_values(ascending=False, na_position="last")
118
+ exp_val = np.array(["d", "c", "b", "a", np.nan], dtype=object)
119
+ exp_categories = Index(["a", "b", "c", "d"])
120
+ tm.assert_numpy_array_equal(res.__array__(), exp_val)
121
+ tm.assert_index_equal(res.categories, exp_categories)
122
+
123
+ cat = Categorical(["a", "c", "b", "d", np.nan], ordered=True)
124
+ res = cat.sort_values(ascending=False, na_position="first")
125
+ exp_val = np.array([np.nan, "d", "c", "b", "a"], dtype=object)
126
+ exp_categories = Index(["a", "b", "c", "d"])
127
+ tm.assert_numpy_array_equal(res.__array__(), exp_val)
128
+ tm.assert_index_equal(res.categories, exp_categories)
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_subclass.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pandas import Categorical
2
+ import pandas._testing as tm
3
+
4
+
5
+ class SubclassedCategorical(Categorical):
6
+ pass
7
+
8
+
9
+ class TestCategoricalSubclassing:
10
+ def test_constructor(self):
11
+ sc = SubclassedCategorical(["a", "b", "c"])
12
+ assert isinstance(sc, SubclassedCategorical)
13
+ tm.assert_categorical_equal(sc, Categorical(["a", "b", "c"]))
14
+
15
+ def test_from_codes(self):
16
+ sc = SubclassedCategorical.from_codes([1, 0, 2], ["a", "b", "c"])
17
+ assert isinstance(sc, SubclassedCategorical)
18
+ exp = Categorical.from_codes([1, 0, 2], ["a", "b", "c"])
19
+ tm.assert_categorical_equal(sc, exp)
20
+
21
+ def test_map(self):
22
+ sc = SubclassedCategorical(["a", "b", "c"])
23
+ res = sc.map(lambda x: x.upper(), na_action=None)
24
+ assert isinstance(res, SubclassedCategorical)
25
+ exp = Categorical(["A", "B", "C"])
26
+ tm.assert_categorical_equal(res, exp)
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_take.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas import Categorical
5
+ import pandas._testing as tm
6
+
7
+
8
+ @pytest.fixture(params=[True, False])
9
+ def allow_fill(request):
10
+ """Boolean 'allow_fill' parameter for Categorical.take"""
11
+ return request.param
12
+
13
+
14
+ class TestTake:
15
+ # https://github.com/pandas-dev/pandas/issues/20664
16
+
17
+ def test_take_default_allow_fill(self):
18
+ cat = Categorical(["a", "b"])
19
+ with tm.assert_produces_warning(None):
20
+ result = cat.take([0, -1])
21
+
22
+ assert result.equals(cat)
23
+
24
+ def test_take_positive_no_warning(self):
25
+ cat = Categorical(["a", "b"])
26
+ with tm.assert_produces_warning(None):
27
+ cat.take([0, 0])
28
+
29
+ def test_take_bounds(self, allow_fill):
30
+ # https://github.com/pandas-dev/pandas/issues/20664
31
+ cat = Categorical(["a", "b", "a"])
32
+ if allow_fill:
33
+ msg = "indices are out-of-bounds"
34
+ else:
35
+ msg = "index 4 is out of bounds for( axis 0 with)? size 3"
36
+ with pytest.raises(IndexError, match=msg):
37
+ cat.take([4, 5], allow_fill=allow_fill)
38
+
39
+ def test_take_empty(self, allow_fill):
40
+ # https://github.com/pandas-dev/pandas/issues/20664
41
+ cat = Categorical([], categories=["a", "b"])
42
+ if allow_fill:
43
+ msg = "indices are out-of-bounds"
44
+ else:
45
+ msg = "cannot do a non-empty take from an empty axes"
46
+ with pytest.raises(IndexError, match=msg):
47
+ cat.take([0], allow_fill=allow_fill)
48
+
49
+ def test_positional_take(self, ordered):
50
+ cat = Categorical(["a", "a", "b", "b"], categories=["b", "a"], ordered=ordered)
51
+ result = cat.take([0, 1, 2], allow_fill=False)
52
+ expected = Categorical(
53
+ ["a", "a", "b"], categories=cat.categories, ordered=ordered
54
+ )
55
+ tm.assert_categorical_equal(result, expected)
56
+
57
+ def test_positional_take_unobserved(self, ordered):
58
+ cat = Categorical(["a", "b"], categories=["a", "b", "c"], ordered=ordered)
59
+ result = cat.take([1, 0], allow_fill=False)
60
+ expected = Categorical(["b", "a"], categories=cat.categories, ordered=ordered)
61
+ tm.assert_categorical_equal(result, expected)
62
+
63
+ def test_take_allow_fill(self):
64
+ # https://github.com/pandas-dev/pandas/issues/23296
65
+ cat = Categorical(["a", "a", "b"])
66
+ result = cat.take([0, -1, -1], allow_fill=True)
67
+ expected = Categorical(["a", np.nan, np.nan], categories=["a", "b"])
68
+ tm.assert_categorical_equal(result, expected)
69
+
70
+ def test_take_fill_with_negative_one(self):
71
+ # -1 was a category
72
+ cat = Categorical([-1, 0, 1])
73
+ result = cat.take([0, -1, 1], allow_fill=True, fill_value=-1)
74
+ expected = Categorical([-1, -1, 0], categories=[-1, 0, 1])
75
+ tm.assert_categorical_equal(result, expected)
76
+
77
+ def test_take_fill_value(self):
78
+ # https://github.com/pandas-dev/pandas/issues/23296
79
+ cat = Categorical(["a", "b", "c"])
80
+ result = cat.take([0, 1, -1], fill_value="a", allow_fill=True)
81
+ expected = Categorical(["a", "b", "a"], categories=["a", "b", "c"])
82
+ tm.assert_categorical_equal(result, expected)
83
+
84
+ def test_take_fill_value_new_raises(self):
85
+ # https://github.com/pandas-dev/pandas/issues/23296
86
+ cat = Categorical(["a", "b", "c"])
87
+ xpr = r"Cannot setitem on a Categorical with a new category \(d\)"
88
+ with pytest.raises(TypeError, match=xpr):
89
+ cat.take([0, 1, -1], fill_value="d", allow_fill=True)
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_warnings.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import pandas._testing as tm
4
+
5
+
6
+ class TestCategoricalWarnings:
7
+ def test_tab_complete_warning(self, ip):
8
+ # https://github.com/pandas-dev/pandas/issues/16409
9
+ pytest.importorskip("IPython", minversion="6.0.0")
10
+ from IPython.core.completer import provisionalcompleter
11
+
12
+ code = "import pandas as pd; c = pd.Categorical([])"
13
+ ip.run_cell(code)
14
+
15
+ # GH 31324 newer jedi version raises Deprecation warning;
16
+ # appears resolved 2021-02-02
17
+ with tm.assert_produces_warning(None, raise_on_extra_warnings=False):
18
+ with provisionalcompleter("ignore"):
19
+ list(ip.Completer.completions("c.", 1))
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/datetimes/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/datetimes/__pycache__/test_constructors.cpython-310.pyc ADDED
Binary file (10.9 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/datetimes/__pycache__/test_cumulative.cpython-310.pyc ADDED
Binary file (1.4 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/datetimes/__pycache__/test_reductions.cpython-310.pyc ADDED
Binary file (5.08 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/datetimes/test_constructors.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas._libs import iNaT
5
+
6
+ from pandas.core.dtypes.dtypes import DatetimeTZDtype
7
+
8
+ import pandas as pd
9
+ import pandas._testing as tm
10
+ from pandas.core.arrays import DatetimeArray
11
+
12
+
13
+ class TestDatetimeArrayConstructor:
14
+ def test_from_sequence_invalid_type(self):
15
+ mi = pd.MultiIndex.from_product([np.arange(5), np.arange(5)])
16
+ with pytest.raises(TypeError, match="Cannot create a DatetimeArray"):
17
+ DatetimeArray._from_sequence(mi, dtype="M8[ns]")
18
+
19
+ def test_only_1dim_accepted(self):
20
+ arr = np.array([0, 1, 2, 3], dtype="M8[h]").astype("M8[ns]")
21
+
22
+ depr_msg = "DatetimeArray.__init__ is deprecated"
23
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
24
+ with pytest.raises(ValueError, match="Only 1-dimensional"):
25
+ # 3-dim, we allow 2D to sneak in for ops purposes GH#29853
26
+ DatetimeArray(arr.reshape(2, 2, 1))
27
+
28
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
29
+ with pytest.raises(ValueError, match="Only 1-dimensional"):
30
+ # 0-dim
31
+ DatetimeArray(arr[[0]].squeeze())
32
+
33
+ def test_freq_validation(self):
34
+ # GH#24623 check that invalid instances cannot be created with the
35
+ # public constructor
36
+ arr = np.arange(5, dtype=np.int64) * 3600 * 10**9
37
+
38
+ msg = (
39
+ "Inferred frequency h from passed values does not "
40
+ "conform to passed frequency W-SUN"
41
+ )
42
+ depr_msg = "DatetimeArray.__init__ is deprecated"
43
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
44
+ with pytest.raises(ValueError, match=msg):
45
+ DatetimeArray(arr, freq="W")
46
+
47
+ @pytest.mark.parametrize(
48
+ "meth",
49
+ [
50
+ DatetimeArray._from_sequence,
51
+ pd.to_datetime,
52
+ pd.DatetimeIndex,
53
+ ],
54
+ )
55
+ def test_mixing_naive_tzaware_raises(self, meth):
56
+ # GH#24569
57
+ arr = np.array([pd.Timestamp("2000"), pd.Timestamp("2000", tz="CET")])
58
+
59
+ msg = (
60
+ "Cannot mix tz-aware with tz-naive values|"
61
+ "Tz-aware datetime.datetime cannot be converted "
62
+ "to datetime64 unless utc=True"
63
+ )
64
+
65
+ for obj in [arr, arr[::-1]]:
66
+ # check that we raise regardless of whether naive is found
67
+ # before aware or vice-versa
68
+ with pytest.raises(ValueError, match=msg):
69
+ meth(obj)
70
+
71
+ def test_from_pandas_array(self):
72
+ arr = pd.array(np.arange(5, dtype=np.int64)) * 3600 * 10**9
73
+
74
+ result = DatetimeArray._from_sequence(arr, dtype="M8[ns]")._with_freq("infer")
75
+
76
+ expected = pd.date_range("1970-01-01", periods=5, freq="h")._data
77
+ tm.assert_datetime_array_equal(result, expected)
78
+
79
+ def test_mismatched_timezone_raises(self):
80
+ depr_msg = "DatetimeArray.__init__ is deprecated"
81
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
82
+ arr = DatetimeArray(
83
+ np.array(["2000-01-01T06:00:00"], dtype="M8[ns]"),
84
+ dtype=DatetimeTZDtype(tz="US/Central"),
85
+ )
86
+ dtype = DatetimeTZDtype(tz="US/Eastern")
87
+ msg = r"dtype=datetime64\[ns.*\] does not match data dtype datetime64\[ns.*\]"
88
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
89
+ with pytest.raises(TypeError, match=msg):
90
+ DatetimeArray(arr, dtype=dtype)
91
+
92
+ # also with mismatched tzawareness
93
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
94
+ with pytest.raises(TypeError, match=msg):
95
+ DatetimeArray(arr, dtype=np.dtype("M8[ns]"))
96
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
97
+ with pytest.raises(TypeError, match=msg):
98
+ DatetimeArray(arr.tz_localize(None), dtype=arr.dtype)
99
+
100
+ def test_non_array_raises(self):
101
+ depr_msg = "DatetimeArray.__init__ is deprecated"
102
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
103
+ with pytest.raises(ValueError, match="list"):
104
+ DatetimeArray([1, 2, 3])
105
+
106
+ def test_bool_dtype_raises(self):
107
+ arr = np.array([1, 2, 3], dtype="bool")
108
+
109
+ depr_msg = "DatetimeArray.__init__ is deprecated"
110
+ msg = "Unexpected value for 'dtype': 'bool'. Must be"
111
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
112
+ with pytest.raises(ValueError, match=msg):
113
+ DatetimeArray(arr)
114
+
115
+ msg = r"dtype bool cannot be converted to datetime64\[ns\]"
116
+ with pytest.raises(TypeError, match=msg):
117
+ DatetimeArray._from_sequence(arr, dtype="M8[ns]")
118
+
119
+ with pytest.raises(TypeError, match=msg):
120
+ pd.DatetimeIndex(arr)
121
+
122
+ with pytest.raises(TypeError, match=msg):
123
+ pd.to_datetime(arr)
124
+
125
+ def test_incorrect_dtype_raises(self):
126
+ depr_msg = "DatetimeArray.__init__ is deprecated"
127
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
128
+ with pytest.raises(ValueError, match="Unexpected value for 'dtype'."):
129
+ DatetimeArray(np.array([1, 2, 3], dtype="i8"), dtype="category")
130
+
131
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
132
+ with pytest.raises(ValueError, match="Unexpected value for 'dtype'."):
133
+ DatetimeArray(np.array([1, 2, 3], dtype="i8"), dtype="m8[s]")
134
+
135
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
136
+ with pytest.raises(ValueError, match="Unexpected value for 'dtype'."):
137
+ DatetimeArray(np.array([1, 2, 3], dtype="i8"), dtype="M8[D]")
138
+
139
+ def test_mismatched_values_dtype_units(self):
140
+ arr = np.array([1, 2, 3], dtype="M8[s]")
141
+ dtype = np.dtype("M8[ns]")
142
+ msg = "Values resolution does not match dtype."
143
+ depr_msg = "DatetimeArray.__init__ is deprecated"
144
+
145
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
146
+ with pytest.raises(ValueError, match=msg):
147
+ DatetimeArray(arr, dtype=dtype)
148
+
149
+ dtype2 = DatetimeTZDtype(tz="UTC", unit="ns")
150
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
151
+ with pytest.raises(ValueError, match=msg):
152
+ DatetimeArray(arr, dtype=dtype2)
153
+
154
+ def test_freq_infer_raises(self):
155
+ depr_msg = "DatetimeArray.__init__ is deprecated"
156
+ with tm.assert_produces_warning(FutureWarning, match=depr_msg):
157
+ with pytest.raises(ValueError, match="Frequency inference"):
158
+ DatetimeArray(np.array([1, 2, 3], dtype="i8"), freq="infer")
159
+
160
+ def test_copy(self):
161
+ data = np.array([1, 2, 3], dtype="M8[ns]")
162
+ arr = DatetimeArray._from_sequence(data, copy=False)
163
+ assert arr._ndarray is data
164
+
165
+ arr = DatetimeArray._from_sequence(data, copy=True)
166
+ assert arr._ndarray is not data
167
+
168
+ @pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"])
169
+ def test_numpy_datetime_unit(self, unit):
170
+ data = np.array([1, 2, 3], dtype=f"M8[{unit}]")
171
+ arr = DatetimeArray._from_sequence(data)
172
+ assert arr.unit == unit
173
+ assert arr[0].unit == unit
174
+
175
+
176
+ class TestSequenceToDT64NS:
177
+ def test_tz_dtype_mismatch_raises(self):
178
+ arr = DatetimeArray._from_sequence(
179
+ ["2000"], dtype=DatetimeTZDtype(tz="US/Central")
180
+ )
181
+ with pytest.raises(TypeError, match="data is already tz-aware"):
182
+ DatetimeArray._from_sequence(arr, dtype=DatetimeTZDtype(tz="UTC"))
183
+
184
+ def test_tz_dtype_matches(self):
185
+ dtype = DatetimeTZDtype(tz="US/Central")
186
+ arr = DatetimeArray._from_sequence(["2000"], dtype=dtype)
187
+ result = DatetimeArray._from_sequence(arr, dtype=dtype)
188
+ tm.assert_equal(arr, result)
189
+
190
+ @pytest.mark.parametrize("order", ["F", "C"])
191
+ def test_2d(self, order):
192
+ dti = pd.date_range("2016-01-01", periods=6, tz="US/Pacific")
193
+ arr = np.array(dti, dtype=object).reshape(3, 2)
194
+ if order == "F":
195
+ arr = arr.T
196
+
197
+ res = DatetimeArray._from_sequence(arr, dtype=dti.dtype)
198
+ expected = DatetimeArray._from_sequence(arr.ravel(), dtype=dti.dtype).reshape(
199
+ arr.shape
200
+ )
201
+ tm.assert_datetime_array_equal(res, expected)
202
+
203
+
204
+ # ----------------------------------------------------------------------------
205
+ # Arrow interaction
206
+
207
+
208
+ EXTREME_VALUES = [0, 123456789, None, iNaT, 2**63 - 1, -(2**63) + 1]
209
+ FINE_TO_COARSE_SAFE = [123_000_000_000, None, -123_000_000_000]
210
+ COARSE_TO_FINE_SAFE = [123, None, -123]
211
+
212
+
213
+ @pytest.mark.parametrize(
214
+ ("pa_unit", "pd_unit", "pa_tz", "pd_tz", "data"),
215
+ [
216
+ ("s", "s", "UTC", "UTC", EXTREME_VALUES),
217
+ ("ms", "ms", "UTC", "Europe/Berlin", EXTREME_VALUES),
218
+ ("us", "us", "US/Eastern", "UTC", EXTREME_VALUES),
219
+ ("ns", "ns", "US/Central", "Asia/Kolkata", EXTREME_VALUES),
220
+ ("ns", "s", "UTC", "UTC", FINE_TO_COARSE_SAFE),
221
+ ("us", "ms", "UTC", "Europe/Berlin", FINE_TO_COARSE_SAFE),
222
+ ("ms", "us", "US/Eastern", "UTC", COARSE_TO_FINE_SAFE),
223
+ ("s", "ns", "US/Central", "Asia/Kolkata", COARSE_TO_FINE_SAFE),
224
+ ],
225
+ )
226
+ def test_from_arrow_with_different_units_and_timezones_with(
227
+ pa_unit, pd_unit, pa_tz, pd_tz, data
228
+ ):
229
+ pa = pytest.importorskip("pyarrow")
230
+
231
+ pa_type = pa.timestamp(pa_unit, tz=pa_tz)
232
+ arr = pa.array(data, type=pa_type)
233
+ dtype = DatetimeTZDtype(unit=pd_unit, tz=pd_tz)
234
+
235
+ result = dtype.__from_arrow__(arr)
236
+ expected = DatetimeArray._from_sequence(data, dtype=f"M8[{pa_unit}, UTC]").astype(
237
+ dtype, copy=False
238
+ )
239
+ tm.assert_extension_array_equal(result, expected)
240
+
241
+ result = dtype.__from_arrow__(pa.chunked_array([arr]))
242
+ tm.assert_extension_array_equal(result, expected)
243
+
244
+
245
+ @pytest.mark.parametrize(
246
+ ("unit", "tz"),
247
+ [
248
+ ("s", "UTC"),
249
+ ("ms", "Europe/Berlin"),
250
+ ("us", "US/Eastern"),
251
+ ("ns", "Asia/Kolkata"),
252
+ ("ns", "UTC"),
253
+ ],
254
+ )
255
+ def test_from_arrow_from_empty(unit, tz):
256
+ pa = pytest.importorskip("pyarrow")
257
+
258
+ data = []
259
+ arr = pa.array(data)
260
+ dtype = DatetimeTZDtype(unit=unit, tz=tz)
261
+
262
+ result = dtype.__from_arrow__(arr)
263
+ expected = DatetimeArray._from_sequence(np.array(data, dtype=f"datetime64[{unit}]"))
264
+ expected = expected.tz_localize(tz=tz)
265
+ tm.assert_extension_array_equal(result, expected)
266
+
267
+ result = dtype.__from_arrow__(pa.chunked_array([arr]))
268
+ tm.assert_extension_array_equal(result, expected)
269
+
270
+
271
+ def test_from_arrow_from_integers():
272
+ pa = pytest.importorskip("pyarrow")
273
+
274
+ data = [0, 123456789, None, 2**63 - 1, iNaT, -123456789]
275
+ arr = pa.array(data)
276
+ dtype = DatetimeTZDtype(unit="ns", tz="UTC")
277
+
278
+ result = dtype.__from_arrow__(arr)
279
+ expected = DatetimeArray._from_sequence(np.array(data, dtype="datetime64[ns]"))
280
+ expected = expected.tz_localize("UTC")
281
+ tm.assert_extension_array_equal(result, expected)
282
+
283
+ result = dtype.__from_arrow__(pa.chunked_array([arr]))
284
+ tm.assert_extension_array_equal(result, expected)
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/datetimes/test_cumulative.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import pandas._testing as tm
4
+ from pandas.core.arrays import DatetimeArray
5
+
6
+
7
+ class TestAccumulator:
8
+ def test_accumulators_freq(self):
9
+ # GH#50297
10
+ arr = DatetimeArray._from_sequence(
11
+ [
12
+ "2000-01-01",
13
+ "2000-01-02",
14
+ "2000-01-03",
15
+ ],
16
+ dtype="M8[ns]",
17
+ )._with_freq("infer")
18
+ result = arr._accumulate("cummin")
19
+ expected = DatetimeArray._from_sequence(["2000-01-01"] * 3, dtype="M8[ns]")
20
+ tm.assert_datetime_array_equal(result, expected)
21
+
22
+ result = arr._accumulate("cummax")
23
+ expected = DatetimeArray._from_sequence(
24
+ [
25
+ "2000-01-01",
26
+ "2000-01-02",
27
+ "2000-01-03",
28
+ ],
29
+ dtype="M8[ns]",
30
+ )
31
+ tm.assert_datetime_array_equal(result, expected)
32
+
33
+ @pytest.mark.parametrize("func", ["cumsum", "cumprod"])
34
+ def test_accumulators_disallowed(self, func):
35
+ # GH#50297
36
+ arr = DatetimeArray._from_sequence(
37
+ [
38
+ "2000-01-01",
39
+ "2000-01-02",
40
+ ],
41
+ dtype="M8[ns]",
42
+ )._with_freq("infer")
43
+ with pytest.raises(TypeError, match=f"Accumulation {func}"):
44
+ arr._accumulate(func)
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/datetimes/test_reductions.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas.core.dtypes.dtypes import DatetimeTZDtype
5
+
6
+ import pandas as pd
7
+ from pandas import NaT
8
+ import pandas._testing as tm
9
+ from pandas.core.arrays import DatetimeArray
10
+
11
+
12
+ class TestReductions:
13
+ @pytest.fixture(params=["s", "ms", "us", "ns"])
14
+ def unit(self, request):
15
+ return request.param
16
+
17
+ @pytest.fixture
18
+ def arr1d(self, tz_naive_fixture):
19
+ """Fixture returning DatetimeArray with parametrized timezones"""
20
+ tz = tz_naive_fixture
21
+ dtype = DatetimeTZDtype(tz=tz) if tz is not None else np.dtype("M8[ns]")
22
+ arr = DatetimeArray._from_sequence(
23
+ [
24
+ "2000-01-03",
25
+ "2000-01-03",
26
+ "NaT",
27
+ "2000-01-02",
28
+ "2000-01-05",
29
+ "2000-01-04",
30
+ ],
31
+ dtype=dtype,
32
+ )
33
+ return arr
34
+
35
+ def test_min_max(self, arr1d, unit):
36
+ arr = arr1d
37
+ arr = arr.as_unit(unit)
38
+ tz = arr.tz
39
+
40
+ result = arr.min()
41
+ expected = pd.Timestamp("2000-01-02", tz=tz).as_unit(unit)
42
+ assert result == expected
43
+ assert result.unit == expected.unit
44
+
45
+ result = arr.max()
46
+ expected = pd.Timestamp("2000-01-05", tz=tz).as_unit(unit)
47
+ assert result == expected
48
+ assert result.unit == expected.unit
49
+
50
+ result = arr.min(skipna=False)
51
+ assert result is NaT
52
+
53
+ result = arr.max(skipna=False)
54
+ assert result is NaT
55
+
56
+ @pytest.mark.parametrize("tz", [None, "US/Central"])
57
+ @pytest.mark.parametrize("skipna", [True, False])
58
+ def test_min_max_empty(self, skipna, tz):
59
+ dtype = DatetimeTZDtype(tz=tz) if tz is not None else np.dtype("M8[ns]")
60
+ arr = DatetimeArray._from_sequence([], dtype=dtype)
61
+ result = arr.min(skipna=skipna)
62
+ assert result is NaT
63
+
64
+ result = arr.max(skipna=skipna)
65
+ assert result is NaT
66
+
67
+ @pytest.mark.parametrize("tz", [None, "US/Central"])
68
+ @pytest.mark.parametrize("skipna", [True, False])
69
+ def test_median_empty(self, skipna, tz):
70
+ dtype = DatetimeTZDtype(tz=tz) if tz is not None else np.dtype("M8[ns]")
71
+ arr = DatetimeArray._from_sequence([], dtype=dtype)
72
+ result = arr.median(skipna=skipna)
73
+ assert result is NaT
74
+
75
+ arr = arr.reshape(0, 3)
76
+ result = arr.median(axis=0, skipna=skipna)
77
+ expected = type(arr)._from_sequence([NaT, NaT, NaT], dtype=arr.dtype)
78
+ tm.assert_equal(result, expected)
79
+
80
+ result = arr.median(axis=1, skipna=skipna)
81
+ expected = type(arr)._from_sequence([], dtype=arr.dtype)
82
+ tm.assert_equal(result, expected)
83
+
84
+ def test_median(self, arr1d):
85
+ arr = arr1d
86
+
87
+ result = arr.median()
88
+ assert result == arr[0]
89
+ result = arr.median(skipna=False)
90
+ assert result is NaT
91
+
92
+ result = arr.dropna().median(skipna=False)
93
+ assert result == arr[0]
94
+
95
+ result = arr.median(axis=0)
96
+ assert result == arr[0]
97
+
98
+ def test_median_axis(self, arr1d):
99
+ arr = arr1d
100
+ assert arr.median(axis=0) == arr.median()
101
+ assert arr.median(axis=0, skipna=False) is NaT
102
+
103
+ msg = r"abs\(axis\) must be less than ndim"
104
+ with pytest.raises(ValueError, match=msg):
105
+ arr.median(axis=1)
106
+
107
+ @pytest.mark.filterwarnings("ignore:All-NaN slice encountered:RuntimeWarning")
108
+ def test_median_2d(self, arr1d):
109
+ arr = arr1d.reshape(1, -1)
110
+
111
+ # axis = None
112
+ assert arr.median() == arr1d.median()
113
+ assert arr.median(skipna=False) is NaT
114
+
115
+ # axis = 0
116
+ result = arr.median(axis=0)
117
+ expected = arr1d
118
+ tm.assert_equal(result, expected)
119
+
120
+ # Since column 3 is all-NaT, we get NaT there with or without skipna
121
+ result = arr.median(axis=0, skipna=False)
122
+ expected = arr1d
123
+ tm.assert_equal(result, expected)
124
+
125
+ # axis = 1
126
+ result = arr.median(axis=1)
127
+ expected = type(arr)._from_sequence([arr1d.median()], dtype=arr.dtype)
128
+ tm.assert_equal(result, expected)
129
+
130
+ result = arr.median(axis=1, skipna=False)
131
+ expected = type(arr)._from_sequence([NaT], dtype=arr.dtype)
132
+ tm.assert_equal(result, expected)
133
+
134
+ def test_mean(self, arr1d):
135
+ arr = arr1d
136
+
137
+ # manually verified result
138
+ expected = arr[0] + 0.4 * pd.Timedelta(days=1)
139
+
140
+ result = arr.mean()
141
+ assert result == expected
142
+ result = arr.mean(skipna=False)
143
+ assert result is NaT
144
+
145
+ result = arr.dropna().mean(skipna=False)
146
+ assert result == expected
147
+
148
+ result = arr.mean(axis=0)
149
+ assert result == expected
150
+
151
+ def test_mean_2d(self):
152
+ dti = pd.date_range("2016-01-01", periods=6, tz="US/Pacific")
153
+ dta = dti._data.reshape(3, 2)
154
+
155
+ result = dta.mean(axis=0)
156
+ expected = dta[1]
157
+ tm.assert_datetime_array_equal(result, expected)
158
+
159
+ result = dta.mean(axis=1)
160
+ expected = dta[:, 0] + pd.Timedelta(hours=12)
161
+ tm.assert_datetime_array_equal(result, expected)
162
+
163
+ result = dta.mean(axis=None)
164
+ expected = dti.mean()
165
+ assert result == expected
166
+
167
+ @pytest.mark.parametrize("skipna", [True, False])
168
+ def test_mean_empty(self, arr1d, skipna):
169
+ arr = arr1d[:0]
170
+
171
+ assert arr.mean(skipna=skipna) is NaT
172
+
173
+ arr2d = arr.reshape(0, 3)
174
+ result = arr2d.mean(axis=0, skipna=skipna)
175
+ expected = DatetimeArray._from_sequence([NaT, NaT, NaT], dtype=arr.dtype)
176
+ tm.assert_datetime_array_equal(result, expected)
177
+
178
+ result = arr2d.mean(axis=1, skipna=skipna)
179
+ expected = arr # i.e. 1D, empty
180
+ tm.assert_datetime_array_equal(result, expected)
181
+
182
+ result = arr2d.mean(axis=None, skipna=skipna)
183
+ assert result is NaT
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/floating/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (193 Bytes). View file