Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +2 -0
- llava_next/lib/python3.10/site-packages/pandas/io/__pycache__/stata.cpython-310.pyc +3 -0
- llava_next/lib/python3.10/site-packages/pandas/io/formats/__pycache__/style.cpython-310.pyc +3 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/__init__.py +0 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__init__.py +0 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/boolean/test_indexing.py +13 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/boolean/test_ops.py +27 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__init__.py +0 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_algos.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_astype.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_map.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_missing.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_replace.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_repr.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_sorting.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_algos.py +89 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_analytics.py +349 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_api.py +501 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_astype.py +155 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_constructors.py +783 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_dtypes.py +139 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_indexing.py +388 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_map.py +154 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_missing.py +216 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_operators.py +414 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_replace.py +111 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_repr.py +550 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_sorting.py +128 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_subclass.py +26 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_take.py +89 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_warnings.py +19 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/__init__.py +0 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/__init__.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/conftest.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_arithmetic.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_astype.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_comparison.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_concat.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_construction.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_contains.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_function.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_repr.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_to_numpy.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/conftest.py +48 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/test_arithmetic.py +244 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/test_astype.py +128 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/test_comparison.py +65 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/test_concat.py +20 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/test_construction.py +204 -0
- llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/test_contains.py +12 -0
.gitattributes
CHANGED
|
@@ -322,3 +322,5 @@ parrot/lib/python3.10/site-packages/transformers/generation/__pycache__/tf_utils
|
|
| 322 |
llava_next/lib/python3.10/site-packages/pandas/_libs/tslib.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 323 |
llava_next/lib/python3.10/site-packages/altair/vegalite/v5/schema/__pycache__/channels.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 324 |
llava_next/lib/python3.10/site-packages/pandas/_libs/sparse.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 322 |
llava_next/lib/python3.10/site-packages/pandas/_libs/tslib.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 323 |
llava_next/lib/python3.10/site-packages/altair/vegalite/v5/schema/__pycache__/channels.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 324 |
llava_next/lib/python3.10/site-packages/pandas/_libs/sparse.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 325 |
+
llava_next/lib/python3.10/site-packages/pandas/io/formats/__pycache__/style.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 326 |
+
llava_next/lib/python3.10/site-packages/pandas/io/__pycache__/stata.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
llava_next/lib/python3.10/site-packages/pandas/io/__pycache__/stata.cpython-310.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8cbbad77c1a4f67bab413d8c4a41d72a970b93489582cbcc5d684505aa209918
|
| 3 |
+
size 102666
|
llava_next/lib/python3.10/site-packages/pandas/io/formats/__pycache__/style.cpython-310.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:69450f8a73a562cb4952d959f40b44574427d0784db539ec1d28a060c7bedfcd
|
| 3 |
+
size 137387
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/__init__.py
ADDED
|
File without changes
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/boolean/__init__.py
ADDED
|
File without changes
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/boolean/test_indexing.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import pandas._testing as tm
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@pytest.mark.parametrize("na", [None, np.nan, pd.NA])
|
| 9 |
+
def test_setitem_missing_values(na):
|
| 10 |
+
arr = pd.array([True, False, None], dtype="boolean")
|
| 11 |
+
expected = pd.array([True, None, None], dtype="boolean")
|
| 12 |
+
arr[1] = na
|
| 13 |
+
tm.assert_extension_array_equal(arr, expected)
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/boolean/test_ops.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import pandas._testing as tm
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class TestUnaryOps:
|
| 6 |
+
def test_invert(self):
|
| 7 |
+
a = pd.array([True, False, None], dtype="boolean")
|
| 8 |
+
expected = pd.array([False, True, None], dtype="boolean")
|
| 9 |
+
tm.assert_extension_array_equal(~a, expected)
|
| 10 |
+
|
| 11 |
+
expected = pd.Series(expected, index=["a", "b", "c"], name="name")
|
| 12 |
+
result = ~pd.Series(a, index=["a", "b", "c"], name="name")
|
| 13 |
+
tm.assert_series_equal(result, expected)
|
| 14 |
+
|
| 15 |
+
df = pd.DataFrame({"A": a, "B": [True, False, False]}, index=["a", "b", "c"])
|
| 16 |
+
result = ~df
|
| 17 |
+
expected = pd.DataFrame(
|
| 18 |
+
{"A": expected, "B": [False, True, True]}, index=["a", "b", "c"]
|
| 19 |
+
)
|
| 20 |
+
tm.assert_frame_equal(result, expected)
|
| 21 |
+
|
| 22 |
+
def test_abs(self):
|
| 23 |
+
# matching numpy behavior, abs is the identity function
|
| 24 |
+
arr = pd.array([True, False, None], dtype="boolean")
|
| 25 |
+
result = abs(arr)
|
| 26 |
+
|
| 27 |
+
tm.assert_extension_array_equal(result, arr)
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__init__.py
ADDED
|
File without changes
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_algos.cpython-310.pyc
ADDED
|
Binary file (2.83 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_astype.cpython-310.pyc
ADDED
|
Binary file (5.46 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_map.cpython-310.pyc
ADDED
|
Binary file (4.32 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_missing.cpython-310.pyc
ADDED
|
Binary file (6.71 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_replace.cpython-310.pyc
ADDED
|
Binary file (3.32 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_repr.cpython-310.pyc
ADDED
|
Binary file (24.4 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/__pycache__/test_sorting.cpython-310.pyc
ADDED
|
Binary file (3.49 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_algos.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import pandas._testing as tm
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@pytest.mark.parametrize("ordered", [True, False])
|
| 9 |
+
@pytest.mark.parametrize("categories", [["b", "a", "c"], ["a", "b", "c", "d"]])
|
| 10 |
+
def test_factorize(categories, ordered):
|
| 11 |
+
cat = pd.Categorical(
|
| 12 |
+
["b", "b", "a", "c", None], categories=categories, ordered=ordered
|
| 13 |
+
)
|
| 14 |
+
codes, uniques = pd.factorize(cat)
|
| 15 |
+
expected_codes = np.array([0, 0, 1, 2, -1], dtype=np.intp)
|
| 16 |
+
expected_uniques = pd.Categorical(
|
| 17 |
+
["b", "a", "c"], categories=categories, ordered=ordered
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
tm.assert_numpy_array_equal(codes, expected_codes)
|
| 21 |
+
tm.assert_categorical_equal(uniques, expected_uniques)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def test_factorized_sort():
|
| 25 |
+
cat = pd.Categorical(["b", "b", None, "a"])
|
| 26 |
+
codes, uniques = pd.factorize(cat, sort=True)
|
| 27 |
+
expected_codes = np.array([1, 1, -1, 0], dtype=np.intp)
|
| 28 |
+
expected_uniques = pd.Categorical(["a", "b"])
|
| 29 |
+
|
| 30 |
+
tm.assert_numpy_array_equal(codes, expected_codes)
|
| 31 |
+
tm.assert_categorical_equal(uniques, expected_uniques)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def test_factorized_sort_ordered():
|
| 35 |
+
cat = pd.Categorical(
|
| 36 |
+
["b", "b", None, "a"], categories=["c", "b", "a"], ordered=True
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
codes, uniques = pd.factorize(cat, sort=True)
|
| 40 |
+
expected_codes = np.array([0, 0, -1, 1], dtype=np.intp)
|
| 41 |
+
expected_uniques = pd.Categorical(
|
| 42 |
+
["b", "a"], categories=["c", "b", "a"], ordered=True
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
tm.assert_numpy_array_equal(codes, expected_codes)
|
| 46 |
+
tm.assert_categorical_equal(uniques, expected_uniques)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def test_isin_cats():
|
| 50 |
+
# GH2003
|
| 51 |
+
cat = pd.Categorical(["a", "b", np.nan])
|
| 52 |
+
|
| 53 |
+
result = cat.isin(["a", np.nan])
|
| 54 |
+
expected = np.array([True, False, True], dtype=bool)
|
| 55 |
+
tm.assert_numpy_array_equal(expected, result)
|
| 56 |
+
|
| 57 |
+
result = cat.isin(["a", "c"])
|
| 58 |
+
expected = np.array([True, False, False], dtype=bool)
|
| 59 |
+
tm.assert_numpy_array_equal(expected, result)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@pytest.mark.parametrize("value", [[""], [None, ""], [pd.NaT, ""]])
|
| 63 |
+
def test_isin_cats_corner_cases(value):
|
| 64 |
+
# GH36550
|
| 65 |
+
cat = pd.Categorical([""])
|
| 66 |
+
result = cat.isin(value)
|
| 67 |
+
expected = np.array([True], dtype=bool)
|
| 68 |
+
tm.assert_numpy_array_equal(expected, result)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
@pytest.mark.parametrize("empty", [[], pd.Series(dtype=object), np.array([])])
|
| 72 |
+
def test_isin_empty(empty):
|
| 73 |
+
s = pd.Categorical(["a", "b"])
|
| 74 |
+
expected = np.array([False, False], dtype=bool)
|
| 75 |
+
|
| 76 |
+
result = s.isin(empty)
|
| 77 |
+
tm.assert_numpy_array_equal(expected, result)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def test_diff():
|
| 81 |
+
ser = pd.Series([1, 2, 3], dtype="category")
|
| 82 |
+
|
| 83 |
+
msg = "Convert to a suitable dtype"
|
| 84 |
+
with pytest.raises(TypeError, match=msg):
|
| 85 |
+
ser.diff()
|
| 86 |
+
|
| 87 |
+
df = ser.to_frame(name="A")
|
| 88 |
+
with pytest.raises(TypeError, match=msg):
|
| 89 |
+
df.diff()
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_analytics.py
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
from pandas.compat import PYPY
|
| 8 |
+
|
| 9 |
+
from pandas import (
|
| 10 |
+
Categorical,
|
| 11 |
+
CategoricalDtype,
|
| 12 |
+
DataFrame,
|
| 13 |
+
Index,
|
| 14 |
+
NaT,
|
| 15 |
+
Series,
|
| 16 |
+
date_range,
|
| 17 |
+
)
|
| 18 |
+
import pandas._testing as tm
|
| 19 |
+
from pandas.api.types import is_scalar
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class TestCategoricalAnalytics:
|
| 23 |
+
@pytest.mark.parametrize("aggregation", ["min", "max"])
|
| 24 |
+
def test_min_max_not_ordered_raises(self, aggregation):
|
| 25 |
+
# unordered cats have no min/max
|
| 26 |
+
cat = Categorical(["a", "b", "c", "d"], ordered=False)
|
| 27 |
+
msg = f"Categorical is not ordered for operation {aggregation}"
|
| 28 |
+
agg_func = getattr(cat, aggregation)
|
| 29 |
+
|
| 30 |
+
with pytest.raises(TypeError, match=msg):
|
| 31 |
+
agg_func()
|
| 32 |
+
|
| 33 |
+
ufunc = np.minimum if aggregation == "min" else np.maximum
|
| 34 |
+
with pytest.raises(TypeError, match=msg):
|
| 35 |
+
ufunc.reduce(cat)
|
| 36 |
+
|
| 37 |
+
def test_min_max_ordered(self, index_or_series_or_array):
|
| 38 |
+
cat = Categorical(["a", "b", "c", "d"], ordered=True)
|
| 39 |
+
obj = index_or_series_or_array(cat)
|
| 40 |
+
_min = obj.min()
|
| 41 |
+
_max = obj.max()
|
| 42 |
+
assert _min == "a"
|
| 43 |
+
assert _max == "d"
|
| 44 |
+
|
| 45 |
+
assert np.minimum.reduce(obj) == "a"
|
| 46 |
+
assert np.maximum.reduce(obj) == "d"
|
| 47 |
+
# TODO: raises if we pass axis=0 (on Index and Categorical, not Series)
|
| 48 |
+
|
| 49 |
+
cat = Categorical(
|
| 50 |
+
["a", "b", "c", "d"], categories=["d", "c", "b", "a"], ordered=True
|
| 51 |
+
)
|
| 52 |
+
obj = index_or_series_or_array(cat)
|
| 53 |
+
_min = obj.min()
|
| 54 |
+
_max = obj.max()
|
| 55 |
+
assert _min == "d"
|
| 56 |
+
assert _max == "a"
|
| 57 |
+
assert np.minimum.reduce(obj) == "d"
|
| 58 |
+
assert np.maximum.reduce(obj) == "a"
|
| 59 |
+
|
| 60 |
+
def test_min_max_reduce(self):
|
| 61 |
+
# GH52788
|
| 62 |
+
cat = Categorical(["a", "b", "c", "d"], ordered=True)
|
| 63 |
+
df = DataFrame(cat)
|
| 64 |
+
|
| 65 |
+
result_max = df.agg("max")
|
| 66 |
+
expected_max = Series(Categorical(["d"], dtype=cat.dtype))
|
| 67 |
+
tm.assert_series_equal(result_max, expected_max)
|
| 68 |
+
|
| 69 |
+
result_min = df.agg("min")
|
| 70 |
+
expected_min = Series(Categorical(["a"], dtype=cat.dtype))
|
| 71 |
+
tm.assert_series_equal(result_min, expected_min)
|
| 72 |
+
|
| 73 |
+
@pytest.mark.parametrize(
|
| 74 |
+
"categories,expected",
|
| 75 |
+
[
|
| 76 |
+
(list("ABC"), np.nan),
|
| 77 |
+
([1, 2, 3], np.nan),
|
| 78 |
+
pytest.param(
|
| 79 |
+
Series(date_range("2020-01-01", periods=3), dtype="category"),
|
| 80 |
+
NaT,
|
| 81 |
+
marks=pytest.mark.xfail(
|
| 82 |
+
reason="https://github.com/pandas-dev/pandas/issues/29962"
|
| 83 |
+
),
|
| 84 |
+
),
|
| 85 |
+
],
|
| 86 |
+
)
|
| 87 |
+
@pytest.mark.parametrize("aggregation", ["min", "max"])
|
| 88 |
+
def test_min_max_ordered_empty(self, categories, expected, aggregation):
|
| 89 |
+
# GH 30227
|
| 90 |
+
cat = Categorical([], categories=categories, ordered=True)
|
| 91 |
+
|
| 92 |
+
agg_func = getattr(cat, aggregation)
|
| 93 |
+
result = agg_func()
|
| 94 |
+
assert result is expected
|
| 95 |
+
|
| 96 |
+
@pytest.mark.parametrize(
|
| 97 |
+
"values, categories",
|
| 98 |
+
[(["a", "b", "c", np.nan], list("cba")), ([1, 2, 3, np.nan], [3, 2, 1])],
|
| 99 |
+
)
|
| 100 |
+
@pytest.mark.parametrize("skipna", [True, False])
|
| 101 |
+
@pytest.mark.parametrize("function", ["min", "max"])
|
| 102 |
+
def test_min_max_with_nan(self, values, categories, function, skipna):
|
| 103 |
+
# GH 25303
|
| 104 |
+
cat = Categorical(values, categories=categories, ordered=True)
|
| 105 |
+
result = getattr(cat, function)(skipna=skipna)
|
| 106 |
+
|
| 107 |
+
if skipna is False:
|
| 108 |
+
assert result is np.nan
|
| 109 |
+
else:
|
| 110 |
+
expected = categories[0] if function == "min" else categories[2]
|
| 111 |
+
assert result == expected
|
| 112 |
+
|
| 113 |
+
@pytest.mark.parametrize("function", ["min", "max"])
|
| 114 |
+
@pytest.mark.parametrize("skipna", [True, False])
|
| 115 |
+
def test_min_max_only_nan(self, function, skipna):
|
| 116 |
+
# https://github.com/pandas-dev/pandas/issues/33450
|
| 117 |
+
cat = Categorical([np.nan], categories=[1, 2], ordered=True)
|
| 118 |
+
result = getattr(cat, function)(skipna=skipna)
|
| 119 |
+
assert result is np.nan
|
| 120 |
+
|
| 121 |
+
@pytest.mark.parametrize("method", ["min", "max"])
|
| 122 |
+
def test_numeric_only_min_max_raises(self, method):
|
| 123 |
+
# GH 25303
|
| 124 |
+
cat = Categorical(
|
| 125 |
+
[np.nan, 1, 2, np.nan], categories=[5, 4, 3, 2, 1], ordered=True
|
| 126 |
+
)
|
| 127 |
+
with pytest.raises(TypeError, match=".* got an unexpected keyword"):
|
| 128 |
+
getattr(cat, method)(numeric_only=True)
|
| 129 |
+
|
| 130 |
+
@pytest.mark.parametrize("method", ["min", "max"])
|
| 131 |
+
def test_numpy_min_max_raises(self, method):
|
| 132 |
+
cat = Categorical(["a", "b", "c", "b"], ordered=False)
|
| 133 |
+
msg = (
|
| 134 |
+
f"Categorical is not ordered for operation {method}\n"
|
| 135 |
+
"you can use .as_ordered() to change the Categorical to an ordered one"
|
| 136 |
+
)
|
| 137 |
+
method = getattr(np, method)
|
| 138 |
+
with pytest.raises(TypeError, match=re.escape(msg)):
|
| 139 |
+
method(cat)
|
| 140 |
+
|
| 141 |
+
@pytest.mark.parametrize("kwarg", ["axis", "out", "keepdims"])
|
| 142 |
+
@pytest.mark.parametrize("method", ["min", "max"])
|
| 143 |
+
def test_numpy_min_max_unsupported_kwargs_raises(self, method, kwarg):
|
| 144 |
+
cat = Categorical(["a", "b", "c", "b"], ordered=True)
|
| 145 |
+
msg = (
|
| 146 |
+
f"the '{kwarg}' parameter is not supported in the pandas implementation "
|
| 147 |
+
f"of {method}"
|
| 148 |
+
)
|
| 149 |
+
if kwarg == "axis":
|
| 150 |
+
msg = r"`axis` must be fewer than the number of dimensions \(1\)"
|
| 151 |
+
kwargs = {kwarg: 42}
|
| 152 |
+
method = getattr(np, method)
|
| 153 |
+
with pytest.raises(ValueError, match=msg):
|
| 154 |
+
method(cat, **kwargs)
|
| 155 |
+
|
| 156 |
+
@pytest.mark.parametrize("method, expected", [("min", "a"), ("max", "c")])
|
| 157 |
+
def test_numpy_min_max_axis_equals_none(self, method, expected):
|
| 158 |
+
cat = Categorical(["a", "b", "c", "b"], ordered=True)
|
| 159 |
+
method = getattr(np, method)
|
| 160 |
+
result = method(cat, axis=None)
|
| 161 |
+
assert result == expected
|
| 162 |
+
|
| 163 |
+
@pytest.mark.parametrize(
|
| 164 |
+
"values,categories,exp_mode",
|
| 165 |
+
[
|
| 166 |
+
([1, 1, 2, 4, 5, 5, 5], [5, 4, 3, 2, 1], [5]),
|
| 167 |
+
([1, 1, 1, 4, 5, 5, 5], [5, 4, 3, 2, 1], [5, 1]),
|
| 168 |
+
([1, 2, 3, 4, 5], [5, 4, 3, 2, 1], [5, 4, 3, 2, 1]),
|
| 169 |
+
([np.nan, np.nan, np.nan, 4, 5], [5, 4, 3, 2, 1], [5, 4]),
|
| 170 |
+
([np.nan, np.nan, np.nan, 4, 5, 4], [5, 4, 3, 2, 1], [4]),
|
| 171 |
+
([np.nan, np.nan, 4, 5, 4], [5, 4, 3, 2, 1], [4]),
|
| 172 |
+
],
|
| 173 |
+
)
|
| 174 |
+
def test_mode(self, values, categories, exp_mode):
|
| 175 |
+
cat = Categorical(values, categories=categories, ordered=True)
|
| 176 |
+
res = Series(cat).mode()._values
|
| 177 |
+
exp = Categorical(exp_mode, categories=categories, ordered=True)
|
| 178 |
+
tm.assert_categorical_equal(res, exp)
|
| 179 |
+
|
| 180 |
+
def test_searchsorted(self, ordered):
|
| 181 |
+
# https://github.com/pandas-dev/pandas/issues/8420
|
| 182 |
+
# https://github.com/pandas-dev/pandas/issues/14522
|
| 183 |
+
|
| 184 |
+
cat = Categorical(
|
| 185 |
+
["cheese", "milk", "apple", "bread", "bread"],
|
| 186 |
+
categories=["cheese", "milk", "apple", "bread"],
|
| 187 |
+
ordered=ordered,
|
| 188 |
+
)
|
| 189 |
+
ser = Series(cat)
|
| 190 |
+
|
| 191 |
+
# Searching for single item argument, side='left' (default)
|
| 192 |
+
res_cat = cat.searchsorted("apple")
|
| 193 |
+
assert res_cat == 2
|
| 194 |
+
assert is_scalar(res_cat)
|
| 195 |
+
|
| 196 |
+
res_ser = ser.searchsorted("apple")
|
| 197 |
+
assert res_ser == 2
|
| 198 |
+
assert is_scalar(res_ser)
|
| 199 |
+
|
| 200 |
+
# Searching for single item array, side='left' (default)
|
| 201 |
+
res_cat = cat.searchsorted(["bread"])
|
| 202 |
+
res_ser = ser.searchsorted(["bread"])
|
| 203 |
+
exp = np.array([3], dtype=np.intp)
|
| 204 |
+
tm.assert_numpy_array_equal(res_cat, exp)
|
| 205 |
+
tm.assert_numpy_array_equal(res_ser, exp)
|
| 206 |
+
|
| 207 |
+
# Searching for several items array, side='right'
|
| 208 |
+
res_cat = cat.searchsorted(["apple", "bread"], side="right")
|
| 209 |
+
res_ser = ser.searchsorted(["apple", "bread"], side="right")
|
| 210 |
+
exp = np.array([3, 5], dtype=np.intp)
|
| 211 |
+
tm.assert_numpy_array_equal(res_cat, exp)
|
| 212 |
+
tm.assert_numpy_array_equal(res_ser, exp)
|
| 213 |
+
|
| 214 |
+
# Searching for a single value that is not from the Categorical
|
| 215 |
+
with pytest.raises(TypeError, match="cucumber"):
|
| 216 |
+
cat.searchsorted("cucumber")
|
| 217 |
+
with pytest.raises(TypeError, match="cucumber"):
|
| 218 |
+
ser.searchsorted("cucumber")
|
| 219 |
+
|
| 220 |
+
# Searching for multiple values one of each is not from the Categorical
|
| 221 |
+
msg = (
|
| 222 |
+
"Cannot setitem on a Categorical with a new category, "
|
| 223 |
+
"set the categories first"
|
| 224 |
+
)
|
| 225 |
+
with pytest.raises(TypeError, match=msg):
|
| 226 |
+
cat.searchsorted(["bread", "cucumber"])
|
| 227 |
+
with pytest.raises(TypeError, match=msg):
|
| 228 |
+
ser.searchsorted(["bread", "cucumber"])
|
| 229 |
+
|
| 230 |
+
def test_unique(self, ordered):
|
| 231 |
+
# GH38140
|
| 232 |
+
dtype = CategoricalDtype(["a", "b", "c"], ordered=ordered)
|
| 233 |
+
|
| 234 |
+
# categories are reordered based on value when ordered=False
|
| 235 |
+
cat = Categorical(["a", "b", "c"], dtype=dtype)
|
| 236 |
+
res = cat.unique()
|
| 237 |
+
tm.assert_categorical_equal(res, cat)
|
| 238 |
+
|
| 239 |
+
cat = Categorical(["a", "b", "a", "a"], dtype=dtype)
|
| 240 |
+
res = cat.unique()
|
| 241 |
+
tm.assert_categorical_equal(res, Categorical(["a", "b"], dtype=dtype))
|
| 242 |
+
|
| 243 |
+
cat = Categorical(["c", "a", "b", "a", "a"], dtype=dtype)
|
| 244 |
+
res = cat.unique()
|
| 245 |
+
exp_cat = Categorical(["c", "a", "b"], dtype=dtype)
|
| 246 |
+
tm.assert_categorical_equal(res, exp_cat)
|
| 247 |
+
|
| 248 |
+
# nan must be removed
|
| 249 |
+
cat = Categorical(["b", np.nan, "b", np.nan, "a"], dtype=dtype)
|
| 250 |
+
res = cat.unique()
|
| 251 |
+
exp_cat = Categorical(["b", np.nan, "a"], dtype=dtype)
|
| 252 |
+
tm.assert_categorical_equal(res, exp_cat)
|
| 253 |
+
|
| 254 |
+
def test_unique_index_series(self, ordered):
|
| 255 |
+
# GH38140
|
| 256 |
+
dtype = CategoricalDtype([3, 2, 1], ordered=ordered)
|
| 257 |
+
|
| 258 |
+
c = Categorical([3, 1, 2, 2, 1], dtype=dtype)
|
| 259 |
+
# Categorical.unique sorts categories by appearance order
|
| 260 |
+
# if ordered=False
|
| 261 |
+
exp = Categorical([3, 1, 2], dtype=dtype)
|
| 262 |
+
tm.assert_categorical_equal(c.unique(), exp)
|
| 263 |
+
|
| 264 |
+
tm.assert_index_equal(Index(c).unique(), Index(exp))
|
| 265 |
+
tm.assert_categorical_equal(Series(c).unique(), exp)
|
| 266 |
+
|
| 267 |
+
c = Categorical([1, 1, 2, 2], dtype=dtype)
|
| 268 |
+
exp = Categorical([1, 2], dtype=dtype)
|
| 269 |
+
tm.assert_categorical_equal(c.unique(), exp)
|
| 270 |
+
tm.assert_index_equal(Index(c).unique(), Index(exp))
|
| 271 |
+
tm.assert_categorical_equal(Series(c).unique(), exp)
|
| 272 |
+
|
| 273 |
+
def test_shift(self):
|
| 274 |
+
# GH 9416
|
| 275 |
+
cat = Categorical(["a", "b", "c", "d", "a"])
|
| 276 |
+
|
| 277 |
+
# shift forward
|
| 278 |
+
sp1 = cat.shift(1)
|
| 279 |
+
xp1 = Categorical([np.nan, "a", "b", "c", "d"])
|
| 280 |
+
tm.assert_categorical_equal(sp1, xp1)
|
| 281 |
+
tm.assert_categorical_equal(cat[:-1], sp1[1:])
|
| 282 |
+
|
| 283 |
+
# shift back
|
| 284 |
+
sn2 = cat.shift(-2)
|
| 285 |
+
xp2 = Categorical(
|
| 286 |
+
["c", "d", "a", np.nan, np.nan], categories=["a", "b", "c", "d"]
|
| 287 |
+
)
|
| 288 |
+
tm.assert_categorical_equal(sn2, xp2)
|
| 289 |
+
tm.assert_categorical_equal(cat[2:], sn2[:-2])
|
| 290 |
+
|
| 291 |
+
# shift by zero
|
| 292 |
+
tm.assert_categorical_equal(cat, cat.shift(0))
|
| 293 |
+
|
| 294 |
+
def test_nbytes(self):
|
| 295 |
+
cat = Categorical([1, 2, 3])
|
| 296 |
+
exp = 3 + 3 * 8 # 3 int8s for values + 3 int64s for categories
|
| 297 |
+
assert cat.nbytes == exp
|
| 298 |
+
|
| 299 |
+
def test_memory_usage(self):
|
| 300 |
+
cat = Categorical([1, 2, 3])
|
| 301 |
+
|
| 302 |
+
# .categories is an index, so we include the hashtable
|
| 303 |
+
assert 0 < cat.nbytes <= cat.memory_usage()
|
| 304 |
+
assert 0 < cat.nbytes <= cat.memory_usage(deep=True)
|
| 305 |
+
|
| 306 |
+
cat = Categorical(["foo", "foo", "bar"])
|
| 307 |
+
assert cat.memory_usage(deep=True) > cat.nbytes
|
| 308 |
+
|
| 309 |
+
if not PYPY:
|
| 310 |
+
# sys.getsizeof will call the .memory_usage with
|
| 311 |
+
# deep=True, and add on some GC overhead
|
| 312 |
+
diff = cat.memory_usage(deep=True) - sys.getsizeof(cat)
|
| 313 |
+
assert abs(diff) < 100
|
| 314 |
+
|
| 315 |
+
def test_map(self):
|
| 316 |
+
c = Categorical(list("ABABC"), categories=list("CBA"), ordered=True)
|
| 317 |
+
result = c.map(lambda x: x.lower(), na_action=None)
|
| 318 |
+
exp = Categorical(list("ababc"), categories=list("cba"), ordered=True)
|
| 319 |
+
tm.assert_categorical_equal(result, exp)
|
| 320 |
+
|
| 321 |
+
c = Categorical(list("ABABC"), categories=list("ABC"), ordered=False)
|
| 322 |
+
result = c.map(lambda x: x.lower(), na_action=None)
|
| 323 |
+
exp = Categorical(list("ababc"), categories=list("abc"), ordered=False)
|
| 324 |
+
tm.assert_categorical_equal(result, exp)
|
| 325 |
+
|
| 326 |
+
result = c.map(lambda x: 1, na_action=None)
|
| 327 |
+
# GH 12766: Return an index not an array
|
| 328 |
+
tm.assert_index_equal(result, Index(np.array([1] * 5, dtype=np.int64)))
|
| 329 |
+
|
| 330 |
+
@pytest.mark.parametrize("value", [1, "True", [1, 2, 3], 5.0])
|
| 331 |
+
def test_validate_inplace_raises(self, value):
|
| 332 |
+
cat = Categorical(["A", "B", "B", "C", "A"])
|
| 333 |
+
msg = (
|
| 334 |
+
'For argument "inplace" expected type bool, '
|
| 335 |
+
f"received type {type(value).__name__}"
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
with pytest.raises(ValueError, match=msg):
|
| 339 |
+
cat.sort_values(inplace=value)
|
| 340 |
+
|
| 341 |
+
def test_quantile_empty(self):
|
| 342 |
+
# make sure we have correct itemsize on resulting codes
|
| 343 |
+
cat = Categorical(["A", "B"])
|
| 344 |
+
idx = Index([0.0, 0.5])
|
| 345 |
+
result = cat[:0]._quantile(idx, interpolation="linear")
|
| 346 |
+
assert result._codes.dtype == np.int8
|
| 347 |
+
|
| 348 |
+
expected = cat.take([-1, -1], allow_fill=True)
|
| 349 |
+
tm.assert_extension_array_equal(result, expected)
|
llava_next/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)
|
llava_next/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)
|
llava_next/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
|
llava_next/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)
|
llava_next/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"
|
llava_next/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)
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_missing.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import collections
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from pandas.core.dtypes.dtypes import CategoricalDtype
|
| 7 |
+
|
| 8 |
+
import pandas as pd
|
| 9 |
+
from pandas import (
|
| 10 |
+
Categorical,
|
| 11 |
+
DataFrame,
|
| 12 |
+
Index,
|
| 13 |
+
Series,
|
| 14 |
+
isna,
|
| 15 |
+
)
|
| 16 |
+
import pandas._testing as tm
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class TestCategoricalMissing:
|
| 20 |
+
def test_isna(self):
|
| 21 |
+
exp = np.array([False, False, True])
|
| 22 |
+
cat = Categorical(["a", "b", np.nan])
|
| 23 |
+
res = cat.isna()
|
| 24 |
+
|
| 25 |
+
tm.assert_numpy_array_equal(res, exp)
|
| 26 |
+
|
| 27 |
+
def test_na_flags_int_categories(self):
|
| 28 |
+
# #1457
|
| 29 |
+
|
| 30 |
+
categories = list(range(10))
|
| 31 |
+
labels = np.random.default_rng(2).integers(0, 10, 20)
|
| 32 |
+
labels[::5] = -1
|
| 33 |
+
|
| 34 |
+
cat = Categorical(labels, categories)
|
| 35 |
+
repr(cat)
|
| 36 |
+
|
| 37 |
+
tm.assert_numpy_array_equal(isna(cat), labels == -1)
|
| 38 |
+
|
| 39 |
+
def test_nan_handling(self):
|
| 40 |
+
# Nans are represented as -1 in codes
|
| 41 |
+
c = Categorical(["a", "b", np.nan, "a"])
|
| 42 |
+
tm.assert_index_equal(c.categories, Index(["a", "b"]))
|
| 43 |
+
tm.assert_numpy_array_equal(c._codes, np.array([0, 1, -1, 0], dtype=np.int8))
|
| 44 |
+
c[1] = np.nan
|
| 45 |
+
tm.assert_index_equal(c.categories, Index(["a", "b"]))
|
| 46 |
+
tm.assert_numpy_array_equal(c._codes, np.array([0, -1, -1, 0], dtype=np.int8))
|
| 47 |
+
|
| 48 |
+
# Adding nan to categories should make assigned nan point to the
|
| 49 |
+
# category!
|
| 50 |
+
c = Categorical(["a", "b", np.nan, "a"])
|
| 51 |
+
tm.assert_index_equal(c.categories, Index(["a", "b"]))
|
| 52 |
+
tm.assert_numpy_array_equal(c._codes, np.array([0, 1, -1, 0], dtype=np.int8))
|
| 53 |
+
|
| 54 |
+
def test_set_dtype_nans(self):
|
| 55 |
+
c = Categorical(["a", "b", np.nan])
|
| 56 |
+
result = c._set_dtype(CategoricalDtype(["a", "c"]))
|
| 57 |
+
tm.assert_numpy_array_equal(result.codes, np.array([0, -1, -1], dtype="int8"))
|
| 58 |
+
|
| 59 |
+
def test_set_item_nan(self):
|
| 60 |
+
cat = Categorical([1, 2, 3])
|
| 61 |
+
cat[1] = np.nan
|
| 62 |
+
|
| 63 |
+
exp = Categorical([1, np.nan, 3], categories=[1, 2, 3])
|
| 64 |
+
tm.assert_categorical_equal(cat, exp)
|
| 65 |
+
|
| 66 |
+
@pytest.mark.parametrize(
|
| 67 |
+
"fillna_kwargs, msg",
|
| 68 |
+
[
|
| 69 |
+
(
|
| 70 |
+
{"value": 1, "method": "ffill"},
|
| 71 |
+
"Cannot specify both 'value' and 'method'.",
|
| 72 |
+
),
|
| 73 |
+
({}, "Must specify a fill 'value' or 'method'."),
|
| 74 |
+
({"method": "bad"}, "Invalid fill method. Expecting .* bad"),
|
| 75 |
+
(
|
| 76 |
+
{"value": Series([1, 2, 3, 4, "a"])},
|
| 77 |
+
"Cannot setitem on a Categorical with a new category",
|
| 78 |
+
),
|
| 79 |
+
],
|
| 80 |
+
)
|
| 81 |
+
def test_fillna_raises(self, fillna_kwargs, msg):
|
| 82 |
+
# https://github.com/pandas-dev/pandas/issues/19682
|
| 83 |
+
# https://github.com/pandas-dev/pandas/issues/13628
|
| 84 |
+
cat = Categorical([1, 2, 3, None, None])
|
| 85 |
+
|
| 86 |
+
if len(fillna_kwargs) == 1 and "value" in fillna_kwargs:
|
| 87 |
+
err = TypeError
|
| 88 |
+
else:
|
| 89 |
+
err = ValueError
|
| 90 |
+
|
| 91 |
+
with pytest.raises(err, match=msg):
|
| 92 |
+
cat.fillna(**fillna_kwargs)
|
| 93 |
+
|
| 94 |
+
@pytest.mark.parametrize("named", [True, False])
|
| 95 |
+
def test_fillna_iterable_category(self, named):
|
| 96 |
+
# https://github.com/pandas-dev/pandas/issues/21097
|
| 97 |
+
if named:
|
| 98 |
+
Point = collections.namedtuple("Point", "x y")
|
| 99 |
+
else:
|
| 100 |
+
Point = lambda *args: args # tuple
|
| 101 |
+
cat = Categorical(np.array([Point(0, 0), Point(0, 1), None], dtype=object))
|
| 102 |
+
result = cat.fillna(Point(0, 0))
|
| 103 |
+
expected = Categorical([Point(0, 0), Point(0, 1), Point(0, 0)])
|
| 104 |
+
|
| 105 |
+
tm.assert_categorical_equal(result, expected)
|
| 106 |
+
|
| 107 |
+
# Case where the Point is not among our categories; we want ValueError,
|
| 108 |
+
# not NotImplementedError GH#41914
|
| 109 |
+
cat = Categorical(np.array([Point(1, 0), Point(0, 1), None], dtype=object))
|
| 110 |
+
msg = "Cannot setitem on a Categorical with a new category"
|
| 111 |
+
with pytest.raises(TypeError, match=msg):
|
| 112 |
+
cat.fillna(Point(0, 0))
|
| 113 |
+
|
| 114 |
+
def test_fillna_array(self):
|
| 115 |
+
# accept Categorical or ndarray value if it holds appropriate values
|
| 116 |
+
cat = Categorical(["A", "B", "C", None, None])
|
| 117 |
+
|
| 118 |
+
other = cat.fillna("C")
|
| 119 |
+
result = cat.fillna(other)
|
| 120 |
+
tm.assert_categorical_equal(result, other)
|
| 121 |
+
assert isna(cat[-1]) # didn't modify original inplace
|
| 122 |
+
|
| 123 |
+
other = np.array(["A", "B", "C", "B", "A"])
|
| 124 |
+
result = cat.fillna(other)
|
| 125 |
+
expected = Categorical(["A", "B", "C", "B", "A"], dtype=cat.dtype)
|
| 126 |
+
tm.assert_categorical_equal(result, expected)
|
| 127 |
+
assert isna(cat[-1]) # didn't modify original inplace
|
| 128 |
+
|
| 129 |
+
@pytest.mark.parametrize(
|
| 130 |
+
"values, expected",
|
| 131 |
+
[
|
| 132 |
+
([1, 2, 3], np.array([False, False, False])),
|
| 133 |
+
([1, 2, np.nan], np.array([False, False, True])),
|
| 134 |
+
([1, 2, np.inf], np.array([False, False, True])),
|
| 135 |
+
([1, 2, pd.NA], np.array([False, False, True])),
|
| 136 |
+
],
|
| 137 |
+
)
|
| 138 |
+
def test_use_inf_as_na(self, values, expected):
|
| 139 |
+
# https://github.com/pandas-dev/pandas/issues/33594
|
| 140 |
+
msg = "use_inf_as_na option is deprecated"
|
| 141 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 142 |
+
with pd.option_context("mode.use_inf_as_na", True):
|
| 143 |
+
cat = Categorical(values)
|
| 144 |
+
result = cat.isna()
|
| 145 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 146 |
+
|
| 147 |
+
result = Series(cat).isna()
|
| 148 |
+
expected = Series(expected)
|
| 149 |
+
tm.assert_series_equal(result, expected)
|
| 150 |
+
|
| 151 |
+
result = DataFrame(cat).isna()
|
| 152 |
+
expected = DataFrame(expected)
|
| 153 |
+
tm.assert_frame_equal(result, expected)
|
| 154 |
+
|
| 155 |
+
@pytest.mark.parametrize(
|
| 156 |
+
"values, expected",
|
| 157 |
+
[
|
| 158 |
+
([1, 2, 3], np.array([False, False, False])),
|
| 159 |
+
([1, 2, np.nan], np.array([False, False, True])),
|
| 160 |
+
([1, 2, np.inf], np.array([False, False, True])),
|
| 161 |
+
([1, 2, pd.NA], np.array([False, False, True])),
|
| 162 |
+
],
|
| 163 |
+
)
|
| 164 |
+
def test_use_inf_as_na_outside_context(self, values, expected):
|
| 165 |
+
# https://github.com/pandas-dev/pandas/issues/33594
|
| 166 |
+
# Using isna directly for Categorical will fail in general here
|
| 167 |
+
cat = Categorical(values)
|
| 168 |
+
|
| 169 |
+
msg = "use_inf_as_na option is deprecated"
|
| 170 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 171 |
+
with pd.option_context("mode.use_inf_as_na", True):
|
| 172 |
+
result = isna(cat)
|
| 173 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 174 |
+
|
| 175 |
+
result = isna(Series(cat))
|
| 176 |
+
expected = Series(expected)
|
| 177 |
+
tm.assert_series_equal(result, expected)
|
| 178 |
+
|
| 179 |
+
result = isna(DataFrame(cat))
|
| 180 |
+
expected = DataFrame(expected)
|
| 181 |
+
tm.assert_frame_equal(result, expected)
|
| 182 |
+
|
| 183 |
+
@pytest.mark.parametrize(
|
| 184 |
+
"a1, a2, categories",
|
| 185 |
+
[
|
| 186 |
+
(["a", "b", "c"], [np.nan, "a", "b"], ["a", "b", "c"]),
|
| 187 |
+
([1, 2, 3], [np.nan, 1, 2], [1, 2, 3]),
|
| 188 |
+
],
|
| 189 |
+
)
|
| 190 |
+
def test_compare_categorical_with_missing(self, a1, a2, categories):
|
| 191 |
+
# GH 28384
|
| 192 |
+
cat_type = CategoricalDtype(categories)
|
| 193 |
+
|
| 194 |
+
# !=
|
| 195 |
+
result = Series(a1, dtype=cat_type) != Series(a2, dtype=cat_type)
|
| 196 |
+
expected = Series(a1) != Series(a2)
|
| 197 |
+
tm.assert_series_equal(result, expected)
|
| 198 |
+
|
| 199 |
+
# ==
|
| 200 |
+
result = Series(a1, dtype=cat_type) == Series(a2, dtype=cat_type)
|
| 201 |
+
expected = Series(a1) == Series(a2)
|
| 202 |
+
tm.assert_series_equal(result, expected)
|
| 203 |
+
|
| 204 |
+
@pytest.mark.parametrize(
|
| 205 |
+
"na_value, dtype",
|
| 206 |
+
[
|
| 207 |
+
(pd.NaT, "datetime64[ns]"),
|
| 208 |
+
(None, "float64"),
|
| 209 |
+
(np.nan, "float64"),
|
| 210 |
+
(pd.NA, "float64"),
|
| 211 |
+
],
|
| 212 |
+
)
|
| 213 |
+
def test_categorical_only_missing_values_no_cast(self, na_value, dtype):
|
| 214 |
+
# GH#44900
|
| 215 |
+
result = Categorical([na_value, na_value])
|
| 216 |
+
tm.assert_index_equal(result.categories, Index([], dtype=dtype))
|
llava_next/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)
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_replace.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
import pandas as pd
|
| 4 |
+
from pandas import Categorical
|
| 5 |
+
import pandas._testing as tm
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@pytest.mark.parametrize(
|
| 9 |
+
"to_replace,value,expected,flip_categories",
|
| 10 |
+
[
|
| 11 |
+
# one-to-one
|
| 12 |
+
(1, 2, [2, 2, 3], False),
|
| 13 |
+
(1, 4, [4, 2, 3], False),
|
| 14 |
+
(4, 1, [1, 2, 3], False),
|
| 15 |
+
(5, 6, [1, 2, 3], False),
|
| 16 |
+
# many-to-one
|
| 17 |
+
([1], 2, [2, 2, 3], False),
|
| 18 |
+
([1, 2], 3, [3, 3, 3], False),
|
| 19 |
+
([1, 2], 4, [4, 4, 3], False),
|
| 20 |
+
((1, 2, 4), 5, [5, 5, 3], False),
|
| 21 |
+
((5, 6), 2, [1, 2, 3], False),
|
| 22 |
+
([1], [2], [2, 2, 3], False),
|
| 23 |
+
([1, 4], [5, 2], [5, 2, 3], False),
|
| 24 |
+
# GH49404: overlap between to_replace and value
|
| 25 |
+
([1, 2, 3], [2, 3, 4], [2, 3, 4], False),
|
| 26 |
+
# GH50872, GH46884: replace with null
|
| 27 |
+
(1, None, [None, 2, 3], False),
|
| 28 |
+
(1, pd.NA, [None, 2, 3], False),
|
| 29 |
+
# check_categorical sorts categories, which crashes on mixed dtypes
|
| 30 |
+
(3, "4", [1, 2, "4"], False),
|
| 31 |
+
([1, 2, "3"], "5", ["5", "5", 3], True),
|
| 32 |
+
],
|
| 33 |
+
)
|
| 34 |
+
@pytest.mark.filterwarnings(
|
| 35 |
+
"ignore:.*with CategoricalDtype is deprecated:FutureWarning"
|
| 36 |
+
)
|
| 37 |
+
def test_replace_categorical_series(to_replace, value, expected, flip_categories):
|
| 38 |
+
# GH 31720
|
| 39 |
+
|
| 40 |
+
ser = pd.Series([1, 2, 3], dtype="category")
|
| 41 |
+
result = ser.replace(to_replace, value)
|
| 42 |
+
expected = pd.Series(expected, dtype="category")
|
| 43 |
+
ser.replace(to_replace, value, inplace=True)
|
| 44 |
+
|
| 45 |
+
if flip_categories:
|
| 46 |
+
expected = expected.cat.set_categories(expected.cat.categories[::-1])
|
| 47 |
+
|
| 48 |
+
tm.assert_series_equal(expected, result, check_category_order=False)
|
| 49 |
+
tm.assert_series_equal(expected, ser, check_category_order=False)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@pytest.mark.parametrize(
|
| 53 |
+
"to_replace, value, result, expected_error_msg",
|
| 54 |
+
[
|
| 55 |
+
("b", "c", ["a", "c"], "Categorical.categories are different"),
|
| 56 |
+
("c", "d", ["a", "b"], None),
|
| 57 |
+
# https://github.com/pandas-dev/pandas/issues/33288
|
| 58 |
+
("a", "a", ["a", "b"], None),
|
| 59 |
+
("b", None, ["a", None], "Categorical.categories length are different"),
|
| 60 |
+
],
|
| 61 |
+
)
|
| 62 |
+
def test_replace_categorical(to_replace, value, result, expected_error_msg):
|
| 63 |
+
# GH#26988
|
| 64 |
+
cat = Categorical(["a", "b"])
|
| 65 |
+
expected = Categorical(result)
|
| 66 |
+
msg = (
|
| 67 |
+
r"The behavior of Series\.replace \(and DataFrame.replace\) "
|
| 68 |
+
"with CategoricalDtype"
|
| 69 |
+
)
|
| 70 |
+
warn = FutureWarning if expected_error_msg is not None else None
|
| 71 |
+
with tm.assert_produces_warning(warn, match=msg):
|
| 72 |
+
result = pd.Series(cat, copy=False).replace(to_replace, value)._values
|
| 73 |
+
|
| 74 |
+
tm.assert_categorical_equal(result, expected)
|
| 75 |
+
if to_replace == "b": # the "c" test is supposed to be unchanged
|
| 76 |
+
with pytest.raises(AssertionError, match=expected_error_msg):
|
| 77 |
+
# ensure non-inplace call does not affect original
|
| 78 |
+
tm.assert_categorical_equal(cat, expected)
|
| 79 |
+
|
| 80 |
+
ser = pd.Series(cat, copy=False)
|
| 81 |
+
with tm.assert_produces_warning(warn, match=msg):
|
| 82 |
+
ser.replace(to_replace, value, inplace=True)
|
| 83 |
+
tm.assert_categorical_equal(cat, expected)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def test_replace_categorical_ea_dtype():
|
| 87 |
+
# GH49404
|
| 88 |
+
cat = Categorical(pd.array(["a", "b"], dtype="string"))
|
| 89 |
+
msg = (
|
| 90 |
+
r"The behavior of Series\.replace \(and DataFrame.replace\) "
|
| 91 |
+
"with CategoricalDtype"
|
| 92 |
+
)
|
| 93 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 94 |
+
result = pd.Series(cat).replace(["a", "b"], ["c", pd.NA])._values
|
| 95 |
+
expected = Categorical(pd.array(["c", pd.NA], dtype="string"))
|
| 96 |
+
tm.assert_categorical_equal(result, expected)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def test_replace_maintain_ordering():
|
| 100 |
+
# GH51016
|
| 101 |
+
dtype = pd.CategoricalDtype([0, 1, 2], ordered=True)
|
| 102 |
+
ser = pd.Series([0, 1, 2], dtype=dtype)
|
| 103 |
+
msg = (
|
| 104 |
+
r"The behavior of Series\.replace \(and DataFrame.replace\) "
|
| 105 |
+
"with CategoricalDtype"
|
| 106 |
+
)
|
| 107 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 108 |
+
result = ser.replace(0, 2)
|
| 109 |
+
expected_dtype = pd.CategoricalDtype([1, 2], ordered=True)
|
| 110 |
+
expected = pd.Series([2, 1, 2], dtype=expected_dtype)
|
| 111 |
+
tm.assert_series_equal(expected, result, check_category_order=True)
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/categorical/test_repr.py
ADDED
|
@@ -0,0 +1,550 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from pandas._config import using_pyarrow_string_dtype
|
| 5 |
+
|
| 6 |
+
from pandas import (
|
| 7 |
+
Categorical,
|
| 8 |
+
CategoricalDtype,
|
| 9 |
+
CategoricalIndex,
|
| 10 |
+
Index,
|
| 11 |
+
Series,
|
| 12 |
+
date_range,
|
| 13 |
+
option_context,
|
| 14 |
+
period_range,
|
| 15 |
+
timedelta_range,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class TestCategoricalReprWithFactor:
|
| 20 |
+
def test_print(self, using_infer_string):
|
| 21 |
+
factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)
|
| 22 |
+
if using_infer_string:
|
| 23 |
+
expected = [
|
| 24 |
+
"['a', 'b', 'b', 'a', 'a', 'c', 'c', 'c']",
|
| 25 |
+
"Categories (3, string): [a < b < c]",
|
| 26 |
+
]
|
| 27 |
+
else:
|
| 28 |
+
expected = [
|
| 29 |
+
"['a', 'b', 'b', 'a', 'a', 'c', 'c', 'c']",
|
| 30 |
+
"Categories (3, object): ['a' < 'b' < 'c']",
|
| 31 |
+
]
|
| 32 |
+
expected = "\n".join(expected)
|
| 33 |
+
actual = repr(factor)
|
| 34 |
+
assert actual == expected
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class TestCategoricalRepr:
|
| 38 |
+
def test_big_print(self):
|
| 39 |
+
codes = np.array([0, 1, 2, 0, 1, 2] * 100)
|
| 40 |
+
dtype = CategoricalDtype(categories=Index(["a", "b", "c"], dtype=object))
|
| 41 |
+
factor = Categorical.from_codes(codes, dtype=dtype)
|
| 42 |
+
expected = [
|
| 43 |
+
"['a', 'b', 'c', 'a', 'b', ..., 'b', 'c', 'a', 'b', 'c']",
|
| 44 |
+
"Length: 600",
|
| 45 |
+
"Categories (3, object): ['a', 'b', 'c']",
|
| 46 |
+
]
|
| 47 |
+
expected = "\n".join(expected)
|
| 48 |
+
|
| 49 |
+
actual = repr(factor)
|
| 50 |
+
|
| 51 |
+
assert actual == expected
|
| 52 |
+
|
| 53 |
+
def test_empty_print(self):
|
| 54 |
+
factor = Categorical([], Index(["a", "b", "c"], dtype=object))
|
| 55 |
+
expected = "[], Categories (3, object): ['a', 'b', 'c']"
|
| 56 |
+
actual = repr(factor)
|
| 57 |
+
assert actual == expected
|
| 58 |
+
|
| 59 |
+
assert expected == actual
|
| 60 |
+
factor = Categorical([], Index(["a", "b", "c"], dtype=object), ordered=True)
|
| 61 |
+
expected = "[], Categories (3, object): ['a' < 'b' < 'c']"
|
| 62 |
+
actual = repr(factor)
|
| 63 |
+
assert expected == actual
|
| 64 |
+
|
| 65 |
+
factor = Categorical([], [])
|
| 66 |
+
expected = "[], Categories (0, object): []"
|
| 67 |
+
assert expected == repr(factor)
|
| 68 |
+
|
| 69 |
+
def test_print_none_width(self):
|
| 70 |
+
# GH10087
|
| 71 |
+
a = Series(Categorical([1, 2, 3, 4]))
|
| 72 |
+
exp = (
|
| 73 |
+
"0 1\n1 2\n2 3\n3 4\n"
|
| 74 |
+
"dtype: category\nCategories (4, int64): [1, 2, 3, 4]"
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
with option_context("display.width", None):
|
| 78 |
+
assert exp == repr(a)
|
| 79 |
+
|
| 80 |
+
@pytest.mark.skipif(
|
| 81 |
+
using_pyarrow_string_dtype(),
|
| 82 |
+
reason="Change once infer_string is set to True by default",
|
| 83 |
+
)
|
| 84 |
+
def test_unicode_print(self):
|
| 85 |
+
c = Categorical(["aaaaa", "bb", "cccc"] * 20)
|
| 86 |
+
expected = """\
|
| 87 |
+
['aaaaa', 'bb', 'cccc', 'aaaaa', 'bb', ..., 'bb', 'cccc', 'aaaaa', 'bb', 'cccc']
|
| 88 |
+
Length: 60
|
| 89 |
+
Categories (3, object): ['aaaaa', 'bb', 'cccc']"""
|
| 90 |
+
|
| 91 |
+
assert repr(c) == expected
|
| 92 |
+
|
| 93 |
+
c = Categorical(["ああああ", "いいいいい", "ううううううう"] * 20)
|
| 94 |
+
expected = """\
|
| 95 |
+
['ああああ', 'いいいいい', 'ううううううう', 'ああああ', 'いいいいい', ..., 'いいいいい', 'ううううううう', 'ああああ', 'いいいいい', 'ううううううう']
|
| 96 |
+
Length: 60
|
| 97 |
+
Categories (3, object): ['ああああ', 'いいいいい', 'ううううううう']""" # noqa: E501
|
| 98 |
+
|
| 99 |
+
assert repr(c) == expected
|
| 100 |
+
|
| 101 |
+
# unicode option should not affect to Categorical, as it doesn't care
|
| 102 |
+
# the repr width
|
| 103 |
+
with option_context("display.unicode.east_asian_width", True):
|
| 104 |
+
c = Categorical(["ああああ", "いいいいい", "ううううううう"] * 20)
|
| 105 |
+
expected = """['ああああ', 'いいいいい', 'ううううううう', 'ああああ', 'いいいいい', ..., 'いいいいい', 'ううううううう', 'ああああ', 'いいいいい', 'ううううううう']
|
| 106 |
+
Length: 60
|
| 107 |
+
Categories (3, object): ['ああああ', 'いいいいい', 'ううううううう']""" # noqa: E501
|
| 108 |
+
|
| 109 |
+
assert repr(c) == expected
|
| 110 |
+
|
| 111 |
+
def test_categorical_repr(self):
|
| 112 |
+
c = Categorical([1, 2, 3])
|
| 113 |
+
exp = """[1, 2, 3]
|
| 114 |
+
Categories (3, int64): [1, 2, 3]"""
|
| 115 |
+
|
| 116 |
+
assert repr(c) == exp
|
| 117 |
+
|
| 118 |
+
c = Categorical([1, 2, 3, 1, 2, 3], categories=[1, 2, 3])
|
| 119 |
+
exp = """[1, 2, 3, 1, 2, 3]
|
| 120 |
+
Categories (3, int64): [1, 2, 3]"""
|
| 121 |
+
|
| 122 |
+
assert repr(c) == exp
|
| 123 |
+
|
| 124 |
+
c = Categorical([1, 2, 3, 4, 5] * 10)
|
| 125 |
+
exp = """[1, 2, 3, 4, 5, ..., 1, 2, 3, 4, 5]
|
| 126 |
+
Length: 50
|
| 127 |
+
Categories (5, int64): [1, 2, 3, 4, 5]"""
|
| 128 |
+
|
| 129 |
+
assert repr(c) == exp
|
| 130 |
+
|
| 131 |
+
c = Categorical(np.arange(20, dtype=np.int64))
|
| 132 |
+
exp = """[0, 1, 2, 3, 4, ..., 15, 16, 17, 18, 19]
|
| 133 |
+
Length: 20
|
| 134 |
+
Categories (20, int64): [0, 1, 2, 3, ..., 16, 17, 18, 19]"""
|
| 135 |
+
|
| 136 |
+
assert repr(c) == exp
|
| 137 |
+
|
| 138 |
+
def test_categorical_repr_ordered(self):
|
| 139 |
+
c = Categorical([1, 2, 3], ordered=True)
|
| 140 |
+
exp = """[1, 2, 3]
|
| 141 |
+
Categories (3, int64): [1 < 2 < 3]"""
|
| 142 |
+
|
| 143 |
+
assert repr(c) == exp
|
| 144 |
+
|
| 145 |
+
c = Categorical([1, 2, 3, 1, 2, 3], categories=[1, 2, 3], ordered=True)
|
| 146 |
+
exp = """[1, 2, 3, 1, 2, 3]
|
| 147 |
+
Categories (3, int64): [1 < 2 < 3]"""
|
| 148 |
+
|
| 149 |
+
assert repr(c) == exp
|
| 150 |
+
|
| 151 |
+
c = Categorical([1, 2, 3, 4, 5] * 10, ordered=True)
|
| 152 |
+
exp = """[1, 2, 3, 4, 5, ..., 1, 2, 3, 4, 5]
|
| 153 |
+
Length: 50
|
| 154 |
+
Categories (5, int64): [1 < 2 < 3 < 4 < 5]"""
|
| 155 |
+
|
| 156 |
+
assert repr(c) == exp
|
| 157 |
+
|
| 158 |
+
c = Categorical(np.arange(20, dtype=np.int64), ordered=True)
|
| 159 |
+
exp = """[0, 1, 2, 3, 4, ..., 15, 16, 17, 18, 19]
|
| 160 |
+
Length: 20
|
| 161 |
+
Categories (20, int64): [0 < 1 < 2 < 3 ... 16 < 17 < 18 < 19]"""
|
| 162 |
+
|
| 163 |
+
assert repr(c) == exp
|
| 164 |
+
|
| 165 |
+
def test_categorical_repr_datetime(self):
|
| 166 |
+
idx = date_range("2011-01-01 09:00", freq="h", periods=5)
|
| 167 |
+
c = Categorical(idx)
|
| 168 |
+
|
| 169 |
+
exp = (
|
| 170 |
+
"[2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, "
|
| 171 |
+
"2011-01-01 12:00:00, 2011-01-01 13:00:00]\n"
|
| 172 |
+
"Categories (5, datetime64[ns]): [2011-01-01 09:00:00, "
|
| 173 |
+
"2011-01-01 10:00:00, 2011-01-01 11:00:00,\n"
|
| 174 |
+
" 2011-01-01 12:00:00, "
|
| 175 |
+
"2011-01-01 13:00:00]"
|
| 176 |
+
""
|
| 177 |
+
)
|
| 178 |
+
assert repr(c) == exp
|
| 179 |
+
|
| 180 |
+
c = Categorical(idx.append(idx), categories=idx)
|
| 181 |
+
exp = (
|
| 182 |
+
"[2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, "
|
| 183 |
+
"2011-01-01 12:00:00, 2011-01-01 13:00:00, 2011-01-01 09:00:00, "
|
| 184 |
+
"2011-01-01 10:00:00, 2011-01-01 11:00:00, 2011-01-01 12:00:00, "
|
| 185 |
+
"2011-01-01 13:00:00]\n"
|
| 186 |
+
"Categories (5, datetime64[ns]): [2011-01-01 09:00:00, "
|
| 187 |
+
"2011-01-01 10:00:00, 2011-01-01 11:00:00,\n"
|
| 188 |
+
" 2011-01-01 12:00:00, "
|
| 189 |
+
"2011-01-01 13:00:00]"
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
assert repr(c) == exp
|
| 193 |
+
|
| 194 |
+
idx = date_range("2011-01-01 09:00", freq="h", periods=5, tz="US/Eastern")
|
| 195 |
+
c = Categorical(idx)
|
| 196 |
+
exp = (
|
| 197 |
+
"[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, "
|
| 198 |
+
"2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, "
|
| 199 |
+
"2011-01-01 13:00:00-05:00]\n"
|
| 200 |
+
"Categories (5, datetime64[ns, US/Eastern]): "
|
| 201 |
+
"[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00,\n"
|
| 202 |
+
" "
|
| 203 |
+
"2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00,\n"
|
| 204 |
+
" "
|
| 205 |
+
"2011-01-01 13:00:00-05:00]"
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
assert repr(c) == exp
|
| 209 |
+
|
| 210 |
+
c = Categorical(idx.append(idx), categories=idx)
|
| 211 |
+
exp = (
|
| 212 |
+
"[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, "
|
| 213 |
+
"2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, "
|
| 214 |
+
"2011-01-01 13:00:00-05:00, 2011-01-01 09:00:00-05:00, "
|
| 215 |
+
"2011-01-01 10:00:00-05:00, 2011-01-01 11:00:00-05:00, "
|
| 216 |
+
"2011-01-01 12:00:00-05:00, 2011-01-01 13:00:00-05:00]\n"
|
| 217 |
+
"Categories (5, datetime64[ns, US/Eastern]): "
|
| 218 |
+
"[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00,\n"
|
| 219 |
+
" "
|
| 220 |
+
"2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00,\n"
|
| 221 |
+
" "
|
| 222 |
+
"2011-01-01 13:00:00-05:00]"
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
assert repr(c) == exp
|
| 226 |
+
|
| 227 |
+
def test_categorical_repr_datetime_ordered(self):
|
| 228 |
+
idx = date_range("2011-01-01 09:00", freq="h", periods=5)
|
| 229 |
+
c = Categorical(idx, ordered=True)
|
| 230 |
+
exp = """[2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, 2011-01-01 12:00:00, 2011-01-01 13:00:00]
|
| 231 |
+
Categories (5, datetime64[ns]): [2011-01-01 09:00:00 < 2011-01-01 10:00:00 < 2011-01-01 11:00:00 <
|
| 232 |
+
2011-01-01 12:00:00 < 2011-01-01 13:00:00]""" # noqa: E501
|
| 233 |
+
|
| 234 |
+
assert repr(c) == exp
|
| 235 |
+
|
| 236 |
+
c = Categorical(idx.append(idx), categories=idx, ordered=True)
|
| 237 |
+
exp = """[2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, 2011-01-01 12:00:00, 2011-01-01 13:00:00, 2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, 2011-01-01 12:00:00, 2011-01-01 13:00:00]
|
| 238 |
+
Categories (5, datetime64[ns]): [2011-01-01 09:00:00 < 2011-01-01 10:00:00 < 2011-01-01 11:00:00 <
|
| 239 |
+
2011-01-01 12:00:00 < 2011-01-01 13:00:00]""" # noqa: E501
|
| 240 |
+
|
| 241 |
+
assert repr(c) == exp
|
| 242 |
+
|
| 243 |
+
idx = date_range("2011-01-01 09:00", freq="h", periods=5, tz="US/Eastern")
|
| 244 |
+
c = Categorical(idx, ordered=True)
|
| 245 |
+
exp = """[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, 2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, 2011-01-01 13:00:00-05:00]
|
| 246 |
+
Categories (5, datetime64[ns, US/Eastern]): [2011-01-01 09:00:00-05:00 < 2011-01-01 10:00:00-05:00 <
|
| 247 |
+
2011-01-01 11:00:00-05:00 < 2011-01-01 12:00:00-05:00 <
|
| 248 |
+
2011-01-01 13:00:00-05:00]""" # noqa: E501
|
| 249 |
+
|
| 250 |
+
assert repr(c) == exp
|
| 251 |
+
|
| 252 |
+
c = Categorical(idx.append(idx), categories=idx, ordered=True)
|
| 253 |
+
exp = """[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, 2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, 2011-01-01 13:00:00-05:00, 2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, 2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, 2011-01-01 13:00:00-05:00]
|
| 254 |
+
Categories (5, datetime64[ns, US/Eastern]): [2011-01-01 09:00:00-05:00 < 2011-01-01 10:00:00-05:00 <
|
| 255 |
+
2011-01-01 11:00:00-05:00 < 2011-01-01 12:00:00-05:00 <
|
| 256 |
+
2011-01-01 13:00:00-05:00]""" # noqa: E501
|
| 257 |
+
|
| 258 |
+
assert repr(c) == exp
|
| 259 |
+
|
| 260 |
+
def test_categorical_repr_int_with_nan(self):
|
| 261 |
+
c = Categorical([1, 2, np.nan])
|
| 262 |
+
c_exp = """[1, 2, NaN]\nCategories (2, int64): [1, 2]"""
|
| 263 |
+
assert repr(c) == c_exp
|
| 264 |
+
|
| 265 |
+
s = Series([1, 2, np.nan], dtype="object").astype("category")
|
| 266 |
+
s_exp = """0 1\n1 2\n2 NaN
|
| 267 |
+
dtype: category
|
| 268 |
+
Categories (2, int64): [1, 2]"""
|
| 269 |
+
assert repr(s) == s_exp
|
| 270 |
+
|
| 271 |
+
def test_categorical_repr_period(self):
|
| 272 |
+
idx = period_range("2011-01-01 09:00", freq="h", periods=5)
|
| 273 |
+
c = Categorical(idx)
|
| 274 |
+
exp = """[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00]
|
| 275 |
+
Categories (5, period[h]): [2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00,
|
| 276 |
+
2011-01-01 13:00]""" # noqa: E501
|
| 277 |
+
|
| 278 |
+
assert repr(c) == exp
|
| 279 |
+
|
| 280 |
+
c = Categorical(idx.append(idx), categories=idx)
|
| 281 |
+
exp = """[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00, 2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00]
|
| 282 |
+
Categories (5, period[h]): [2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00,
|
| 283 |
+
2011-01-01 13:00]""" # noqa: E501
|
| 284 |
+
|
| 285 |
+
assert repr(c) == exp
|
| 286 |
+
|
| 287 |
+
idx = period_range("2011-01", freq="M", periods=5)
|
| 288 |
+
c = Categorical(idx)
|
| 289 |
+
exp = """[2011-01, 2011-02, 2011-03, 2011-04, 2011-05]
|
| 290 |
+
Categories (5, period[M]): [2011-01, 2011-02, 2011-03, 2011-04, 2011-05]"""
|
| 291 |
+
|
| 292 |
+
assert repr(c) == exp
|
| 293 |
+
|
| 294 |
+
c = Categorical(idx.append(idx), categories=idx)
|
| 295 |
+
exp = """[2011-01, 2011-02, 2011-03, 2011-04, 2011-05, 2011-01, 2011-02, 2011-03, 2011-04, 2011-05]
|
| 296 |
+
Categories (5, period[M]): [2011-01, 2011-02, 2011-03, 2011-04, 2011-05]""" # noqa: E501
|
| 297 |
+
|
| 298 |
+
assert repr(c) == exp
|
| 299 |
+
|
| 300 |
+
def test_categorical_repr_period_ordered(self):
|
| 301 |
+
idx = period_range("2011-01-01 09:00", freq="h", periods=5)
|
| 302 |
+
c = Categorical(idx, ordered=True)
|
| 303 |
+
exp = """[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00]
|
| 304 |
+
Categories (5, period[h]): [2011-01-01 09:00 < 2011-01-01 10:00 < 2011-01-01 11:00 < 2011-01-01 12:00 <
|
| 305 |
+
2011-01-01 13:00]""" # noqa: E501
|
| 306 |
+
|
| 307 |
+
assert repr(c) == exp
|
| 308 |
+
|
| 309 |
+
c = Categorical(idx.append(idx), categories=idx, ordered=True)
|
| 310 |
+
exp = """[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00, 2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00]
|
| 311 |
+
Categories (5, period[h]): [2011-01-01 09:00 < 2011-01-01 10:00 < 2011-01-01 11:00 < 2011-01-01 12:00 <
|
| 312 |
+
2011-01-01 13:00]""" # noqa: E501
|
| 313 |
+
|
| 314 |
+
assert repr(c) == exp
|
| 315 |
+
|
| 316 |
+
idx = period_range("2011-01", freq="M", periods=5)
|
| 317 |
+
c = Categorical(idx, ordered=True)
|
| 318 |
+
exp = """[2011-01, 2011-02, 2011-03, 2011-04, 2011-05]
|
| 319 |
+
Categories (5, period[M]): [2011-01 < 2011-02 < 2011-03 < 2011-04 < 2011-05]"""
|
| 320 |
+
|
| 321 |
+
assert repr(c) == exp
|
| 322 |
+
|
| 323 |
+
c = Categorical(idx.append(idx), categories=idx, ordered=True)
|
| 324 |
+
exp = """[2011-01, 2011-02, 2011-03, 2011-04, 2011-05, 2011-01, 2011-02, 2011-03, 2011-04, 2011-05]
|
| 325 |
+
Categories (5, period[M]): [2011-01 < 2011-02 < 2011-03 < 2011-04 < 2011-05]""" # noqa: E501
|
| 326 |
+
|
| 327 |
+
assert repr(c) == exp
|
| 328 |
+
|
| 329 |
+
def test_categorical_repr_timedelta(self):
|
| 330 |
+
idx = timedelta_range("1 days", periods=5)
|
| 331 |
+
c = Categorical(idx)
|
| 332 |
+
exp = """[1 days, 2 days, 3 days, 4 days, 5 days]
|
| 333 |
+
Categories (5, timedelta64[ns]): [1 days, 2 days, 3 days, 4 days, 5 days]"""
|
| 334 |
+
|
| 335 |
+
assert repr(c) == exp
|
| 336 |
+
|
| 337 |
+
c = Categorical(idx.append(idx), categories=idx)
|
| 338 |
+
exp = """[1 days, 2 days, 3 days, 4 days, 5 days, 1 days, 2 days, 3 days, 4 days, 5 days]
|
| 339 |
+
Categories (5, timedelta64[ns]): [1 days, 2 days, 3 days, 4 days, 5 days]""" # noqa: E501
|
| 340 |
+
|
| 341 |
+
assert repr(c) == exp
|
| 342 |
+
|
| 343 |
+
idx = timedelta_range("1 hours", periods=20)
|
| 344 |
+
c = Categorical(idx)
|
| 345 |
+
exp = """[0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00, 3 days 01:00:00, 4 days 01:00:00, ..., 15 days 01:00:00, 16 days 01:00:00, 17 days 01:00:00, 18 days 01:00:00, 19 days 01:00:00]
|
| 346 |
+
Length: 20
|
| 347 |
+
Categories (20, timedelta64[ns]): [0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00,
|
| 348 |
+
3 days 01:00:00, ..., 16 days 01:00:00, 17 days 01:00:00,
|
| 349 |
+
18 days 01:00:00, 19 days 01:00:00]""" # noqa: E501
|
| 350 |
+
|
| 351 |
+
assert repr(c) == exp
|
| 352 |
+
|
| 353 |
+
c = Categorical(idx.append(idx), categories=idx)
|
| 354 |
+
exp = """[0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00, 3 days 01:00:00, 4 days 01:00:00, ..., 15 days 01:00:00, 16 days 01:00:00, 17 days 01:00:00, 18 days 01:00:00, 19 days 01:00:00]
|
| 355 |
+
Length: 40
|
| 356 |
+
Categories (20, timedelta64[ns]): [0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00,
|
| 357 |
+
3 days 01:00:00, ..., 16 days 01:00:00, 17 days 01:00:00,
|
| 358 |
+
18 days 01:00:00, 19 days 01:00:00]""" # noqa: E501
|
| 359 |
+
|
| 360 |
+
assert repr(c) == exp
|
| 361 |
+
|
| 362 |
+
def test_categorical_repr_timedelta_ordered(self):
|
| 363 |
+
idx = timedelta_range("1 days", periods=5)
|
| 364 |
+
c = Categorical(idx, ordered=True)
|
| 365 |
+
exp = """[1 days, 2 days, 3 days, 4 days, 5 days]
|
| 366 |
+
Categories (5, timedelta64[ns]): [1 days < 2 days < 3 days < 4 days < 5 days]"""
|
| 367 |
+
|
| 368 |
+
assert repr(c) == exp
|
| 369 |
+
|
| 370 |
+
c = Categorical(idx.append(idx), categories=idx, ordered=True)
|
| 371 |
+
exp = """[1 days, 2 days, 3 days, 4 days, 5 days, 1 days, 2 days, 3 days, 4 days, 5 days]
|
| 372 |
+
Categories (5, timedelta64[ns]): [1 days < 2 days < 3 days < 4 days < 5 days]""" # noqa: E501
|
| 373 |
+
|
| 374 |
+
assert repr(c) == exp
|
| 375 |
+
|
| 376 |
+
idx = timedelta_range("1 hours", periods=20)
|
| 377 |
+
c = Categorical(idx, ordered=True)
|
| 378 |
+
exp = """[0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00, 3 days 01:00:00, 4 days 01:00:00, ..., 15 days 01:00:00, 16 days 01:00:00, 17 days 01:00:00, 18 days 01:00:00, 19 days 01:00:00]
|
| 379 |
+
Length: 20
|
| 380 |
+
Categories (20, timedelta64[ns]): [0 days 01:00:00 < 1 days 01:00:00 < 2 days 01:00:00 <
|
| 381 |
+
3 days 01:00:00 ... 16 days 01:00:00 < 17 days 01:00:00 <
|
| 382 |
+
18 days 01:00:00 < 19 days 01:00:00]""" # noqa: E501
|
| 383 |
+
|
| 384 |
+
assert repr(c) == exp
|
| 385 |
+
|
| 386 |
+
c = Categorical(idx.append(idx), categories=idx, ordered=True)
|
| 387 |
+
exp = """[0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00, 3 days 01:00:00, 4 days 01:00:00, ..., 15 days 01:00:00, 16 days 01:00:00, 17 days 01:00:00, 18 days 01:00:00, 19 days 01:00:00]
|
| 388 |
+
Length: 40
|
| 389 |
+
Categories (20, timedelta64[ns]): [0 days 01:00:00 < 1 days 01:00:00 < 2 days 01:00:00 <
|
| 390 |
+
3 days 01:00:00 ... 16 days 01:00:00 < 17 days 01:00:00 <
|
| 391 |
+
18 days 01:00:00 < 19 days 01:00:00]""" # noqa: E501
|
| 392 |
+
|
| 393 |
+
assert repr(c) == exp
|
| 394 |
+
|
| 395 |
+
def test_categorical_index_repr(self):
|
| 396 |
+
idx = CategoricalIndex(Categorical([1, 2, 3]))
|
| 397 |
+
exp = """CategoricalIndex([1, 2, 3], categories=[1, 2, 3], ordered=False, dtype='category')""" # noqa: E501
|
| 398 |
+
assert repr(idx) == exp
|
| 399 |
+
|
| 400 |
+
i = CategoricalIndex(Categorical(np.arange(10, dtype=np.int64)))
|
| 401 |
+
exp = """CategoricalIndex([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], categories=[0, 1, 2, 3, ..., 6, 7, 8, 9], ordered=False, dtype='category')""" # noqa: E501
|
| 402 |
+
assert repr(i) == exp
|
| 403 |
+
|
| 404 |
+
def test_categorical_index_repr_ordered(self):
|
| 405 |
+
i = CategoricalIndex(Categorical([1, 2, 3], ordered=True))
|
| 406 |
+
exp = """CategoricalIndex([1, 2, 3], categories=[1, 2, 3], ordered=True, dtype='category')""" # noqa: E501
|
| 407 |
+
assert repr(i) == exp
|
| 408 |
+
|
| 409 |
+
i = CategoricalIndex(Categorical(np.arange(10, dtype=np.int64), ordered=True))
|
| 410 |
+
exp = """CategoricalIndex([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], categories=[0, 1, 2, 3, ..., 6, 7, 8, 9], ordered=True, dtype='category')""" # noqa: E501
|
| 411 |
+
assert repr(i) == exp
|
| 412 |
+
|
| 413 |
+
def test_categorical_index_repr_datetime(self):
|
| 414 |
+
idx = date_range("2011-01-01 09:00", freq="h", periods=5)
|
| 415 |
+
i = CategoricalIndex(Categorical(idx))
|
| 416 |
+
exp = """CategoricalIndex(['2011-01-01 09:00:00', '2011-01-01 10:00:00',
|
| 417 |
+
'2011-01-01 11:00:00', '2011-01-01 12:00:00',
|
| 418 |
+
'2011-01-01 13:00:00'],
|
| 419 |
+
categories=[2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, 2011-01-01 12:00:00, 2011-01-01 13:00:00], ordered=False, dtype='category')""" # noqa: E501
|
| 420 |
+
|
| 421 |
+
assert repr(i) == exp
|
| 422 |
+
|
| 423 |
+
idx = date_range("2011-01-01 09:00", freq="h", periods=5, tz="US/Eastern")
|
| 424 |
+
i = CategoricalIndex(Categorical(idx))
|
| 425 |
+
exp = """CategoricalIndex(['2011-01-01 09:00:00-05:00', '2011-01-01 10:00:00-05:00',
|
| 426 |
+
'2011-01-01 11:00:00-05:00', '2011-01-01 12:00:00-05:00',
|
| 427 |
+
'2011-01-01 13:00:00-05:00'],
|
| 428 |
+
categories=[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, 2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, 2011-01-01 13:00:00-05:00], ordered=False, dtype='category')""" # noqa: E501
|
| 429 |
+
|
| 430 |
+
assert repr(i) == exp
|
| 431 |
+
|
| 432 |
+
def test_categorical_index_repr_datetime_ordered(self):
|
| 433 |
+
idx = date_range("2011-01-01 09:00", freq="h", periods=5)
|
| 434 |
+
i = CategoricalIndex(Categorical(idx, ordered=True))
|
| 435 |
+
exp = """CategoricalIndex(['2011-01-01 09:00:00', '2011-01-01 10:00:00',
|
| 436 |
+
'2011-01-01 11:00:00', '2011-01-01 12:00:00',
|
| 437 |
+
'2011-01-01 13:00:00'],
|
| 438 |
+
categories=[2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, 2011-01-01 12:00:00, 2011-01-01 13:00:00], ordered=True, dtype='category')""" # noqa: E501
|
| 439 |
+
|
| 440 |
+
assert repr(i) == exp
|
| 441 |
+
|
| 442 |
+
idx = date_range("2011-01-01 09:00", freq="h", periods=5, tz="US/Eastern")
|
| 443 |
+
i = CategoricalIndex(Categorical(idx, ordered=True))
|
| 444 |
+
exp = """CategoricalIndex(['2011-01-01 09:00:00-05:00', '2011-01-01 10:00:00-05:00',
|
| 445 |
+
'2011-01-01 11:00:00-05:00', '2011-01-01 12:00:00-05:00',
|
| 446 |
+
'2011-01-01 13:00:00-05:00'],
|
| 447 |
+
categories=[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, 2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, 2011-01-01 13:00:00-05:00], ordered=True, dtype='category')""" # noqa: E501
|
| 448 |
+
|
| 449 |
+
assert repr(i) == exp
|
| 450 |
+
|
| 451 |
+
i = CategoricalIndex(Categorical(idx.append(idx), ordered=True))
|
| 452 |
+
exp = """CategoricalIndex(['2011-01-01 09:00:00-05:00', '2011-01-01 10:00:00-05:00',
|
| 453 |
+
'2011-01-01 11:00:00-05:00', '2011-01-01 12:00:00-05:00',
|
| 454 |
+
'2011-01-01 13:00:00-05:00', '2011-01-01 09:00:00-05:00',
|
| 455 |
+
'2011-01-01 10:00:00-05:00', '2011-01-01 11:00:00-05:00',
|
| 456 |
+
'2011-01-01 12:00:00-05:00', '2011-01-01 13:00:00-05:00'],
|
| 457 |
+
categories=[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, 2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, 2011-01-01 13:00:00-05:00], ordered=True, dtype='category')""" # noqa: E501
|
| 458 |
+
|
| 459 |
+
assert repr(i) == exp
|
| 460 |
+
|
| 461 |
+
def test_categorical_index_repr_period(self):
|
| 462 |
+
# test all length
|
| 463 |
+
idx = period_range("2011-01-01 09:00", freq="h", periods=1)
|
| 464 |
+
i = CategoricalIndex(Categorical(idx))
|
| 465 |
+
exp = """CategoricalIndex(['2011-01-01 09:00'], categories=[2011-01-01 09:00], ordered=False, dtype='category')""" # noqa: E501
|
| 466 |
+
assert repr(i) == exp
|
| 467 |
+
|
| 468 |
+
idx = period_range("2011-01-01 09:00", freq="h", periods=2)
|
| 469 |
+
i = CategoricalIndex(Categorical(idx))
|
| 470 |
+
exp = """CategoricalIndex(['2011-01-01 09:00', '2011-01-01 10:00'], categories=[2011-01-01 09:00, 2011-01-01 10:00], ordered=False, dtype='category')""" # noqa: E501
|
| 471 |
+
assert repr(i) == exp
|
| 472 |
+
|
| 473 |
+
idx = period_range("2011-01-01 09:00", freq="h", periods=3)
|
| 474 |
+
i = CategoricalIndex(Categorical(idx))
|
| 475 |
+
exp = """CategoricalIndex(['2011-01-01 09:00', '2011-01-01 10:00', '2011-01-01 11:00'], categories=[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00], ordered=False, dtype='category')""" # noqa: E501
|
| 476 |
+
assert repr(i) == exp
|
| 477 |
+
|
| 478 |
+
idx = period_range("2011-01-01 09:00", freq="h", periods=5)
|
| 479 |
+
i = CategoricalIndex(Categorical(idx))
|
| 480 |
+
exp = """CategoricalIndex(['2011-01-01 09:00', '2011-01-01 10:00', '2011-01-01 11:00',
|
| 481 |
+
'2011-01-01 12:00', '2011-01-01 13:00'],
|
| 482 |
+
categories=[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00], ordered=False, dtype='category')""" # noqa: E501
|
| 483 |
+
|
| 484 |
+
assert repr(i) == exp
|
| 485 |
+
|
| 486 |
+
i = CategoricalIndex(Categorical(idx.append(idx)))
|
| 487 |
+
exp = """CategoricalIndex(['2011-01-01 09:00', '2011-01-01 10:00', '2011-01-01 11:00',
|
| 488 |
+
'2011-01-01 12:00', '2011-01-01 13:00', '2011-01-01 09:00',
|
| 489 |
+
'2011-01-01 10:00', '2011-01-01 11:00', '2011-01-01 12:00',
|
| 490 |
+
'2011-01-01 13:00'],
|
| 491 |
+
categories=[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00], ordered=False, dtype='category')""" # noqa: E501
|
| 492 |
+
|
| 493 |
+
assert repr(i) == exp
|
| 494 |
+
|
| 495 |
+
idx = period_range("2011-01", freq="M", periods=5)
|
| 496 |
+
i = CategoricalIndex(Categorical(idx))
|
| 497 |
+
exp = """CategoricalIndex(['2011-01', '2011-02', '2011-03', '2011-04', '2011-05'], categories=[2011-01, 2011-02, 2011-03, 2011-04, 2011-05], ordered=False, dtype='category')""" # noqa: E501
|
| 498 |
+
assert repr(i) == exp
|
| 499 |
+
|
| 500 |
+
def test_categorical_index_repr_period_ordered(self):
|
| 501 |
+
idx = period_range("2011-01-01 09:00", freq="h", periods=5)
|
| 502 |
+
i = CategoricalIndex(Categorical(idx, ordered=True))
|
| 503 |
+
exp = """CategoricalIndex(['2011-01-01 09:00', '2011-01-01 10:00', '2011-01-01 11:00',
|
| 504 |
+
'2011-01-01 12:00', '2011-01-01 13:00'],
|
| 505 |
+
categories=[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00], ordered=True, dtype='category')""" # noqa: E501
|
| 506 |
+
|
| 507 |
+
assert repr(i) == exp
|
| 508 |
+
|
| 509 |
+
idx = period_range("2011-01", freq="M", periods=5)
|
| 510 |
+
i = CategoricalIndex(Categorical(idx, ordered=True))
|
| 511 |
+
exp = """CategoricalIndex(['2011-01', '2011-02', '2011-03', '2011-04', '2011-05'], categories=[2011-01, 2011-02, 2011-03, 2011-04, 2011-05], ordered=True, dtype='category')""" # noqa: E501
|
| 512 |
+
assert repr(i) == exp
|
| 513 |
+
|
| 514 |
+
def test_categorical_index_repr_timedelta(self):
|
| 515 |
+
idx = timedelta_range("1 days", periods=5)
|
| 516 |
+
i = CategoricalIndex(Categorical(idx))
|
| 517 |
+
exp = """CategoricalIndex(['1 days', '2 days', '3 days', '4 days', '5 days'], categories=[1 days, 2 days, 3 days, 4 days, 5 days], ordered=False, dtype='category')""" # noqa: E501
|
| 518 |
+
assert repr(i) == exp
|
| 519 |
+
|
| 520 |
+
idx = timedelta_range("1 hours", periods=10)
|
| 521 |
+
i = CategoricalIndex(Categorical(idx))
|
| 522 |
+
exp = """CategoricalIndex(['0 days 01:00:00', '1 days 01:00:00', '2 days 01:00:00',
|
| 523 |
+
'3 days 01:00:00', '4 days 01:00:00', '5 days 01:00:00',
|
| 524 |
+
'6 days 01:00:00', '7 days 01:00:00', '8 days 01:00:00',
|
| 525 |
+
'9 days 01:00:00'],
|
| 526 |
+
categories=[0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00, 3 days 01:00:00, ..., 6 days 01:00:00, 7 days 01:00:00, 8 days 01:00:00, 9 days 01:00:00], ordered=False, dtype='category')""" # noqa: E501
|
| 527 |
+
|
| 528 |
+
assert repr(i) == exp
|
| 529 |
+
|
| 530 |
+
def test_categorical_index_repr_timedelta_ordered(self):
|
| 531 |
+
idx = timedelta_range("1 days", periods=5)
|
| 532 |
+
i = CategoricalIndex(Categorical(idx, ordered=True))
|
| 533 |
+
exp = """CategoricalIndex(['1 days', '2 days', '3 days', '4 days', '5 days'], categories=[1 days, 2 days, 3 days, 4 days, 5 days], ordered=True, dtype='category')""" # noqa: E501
|
| 534 |
+
assert repr(i) == exp
|
| 535 |
+
|
| 536 |
+
idx = timedelta_range("1 hours", periods=10)
|
| 537 |
+
i = CategoricalIndex(Categorical(idx, ordered=True))
|
| 538 |
+
exp = """CategoricalIndex(['0 days 01:00:00', '1 days 01:00:00', '2 days 01:00:00',
|
| 539 |
+
'3 days 01:00:00', '4 days 01:00:00', '5 days 01:00:00',
|
| 540 |
+
'6 days 01:00:00', '7 days 01:00:00', '8 days 01:00:00',
|
| 541 |
+
'9 days 01:00:00'],
|
| 542 |
+
categories=[0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00, 3 days 01:00:00, ..., 6 days 01:00:00, 7 days 01:00:00, 8 days 01:00:00, 9 days 01:00:00], ordered=True, dtype='category')""" # noqa: E501
|
| 543 |
+
|
| 544 |
+
assert repr(i) == exp
|
| 545 |
+
|
| 546 |
+
def test_categorical_str_repr(self):
|
| 547 |
+
# GH 33676
|
| 548 |
+
result = repr(Categorical([1, "2", 3, 4]))
|
| 549 |
+
expected = "[1, '2', 3, 4]\nCategories (4, object): [1, 3, 4, '2']"
|
| 550 |
+
assert result == expected
|
llava_next/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)
|
llava_next/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)
|
llava_next/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)
|
llava_next/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))
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/__init__.py
ADDED
|
File without changes
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (184 Bytes). View file
|
|
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/conftest.cpython-310.pyc
ADDED
|
Binary file (1.46 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_arithmetic.cpython-310.pyc
ADDED
|
Binary file (6.55 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_astype.cpython-310.pyc
ADDED
|
Binary file (3.39 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_comparison.cpython-310.pyc
ADDED
|
Binary file (2.11 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_concat.cpython-310.pyc
ADDED
|
Binary file (907 Bytes). View file
|
|
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_construction.cpython-310.pyc
ADDED
|
Binary file (6.06 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_contains.cpython-310.pyc
ADDED
|
Binary file (476 Bytes). View file
|
|
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_function.cpython-310.pyc
ADDED
|
Binary file (5.84 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_repr.cpython-310.pyc
ADDED
|
Binary file (1.61 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/__pycache__/test_to_numpy.cpython-310.pyc
ADDED
|
Binary file (4 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/conftest.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from pandas.core.arrays.floating import (
|
| 6 |
+
Float32Dtype,
|
| 7 |
+
Float64Dtype,
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@pytest.fixture(params=[Float32Dtype, Float64Dtype])
|
| 12 |
+
def dtype(request):
|
| 13 |
+
"""Parametrized fixture returning a float 'dtype'"""
|
| 14 |
+
return request.param()
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@pytest.fixture
|
| 18 |
+
def data(dtype):
|
| 19 |
+
"""Fixture returning 'data' array according to parametrized float 'dtype'"""
|
| 20 |
+
return pd.array(
|
| 21 |
+
list(np.arange(0.1, 0.9, 0.1))
|
| 22 |
+
+ [pd.NA]
|
| 23 |
+
+ list(np.arange(1, 9.8, 0.1))
|
| 24 |
+
+ [pd.NA]
|
| 25 |
+
+ [9.9, 10.0],
|
| 26 |
+
dtype=dtype,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@pytest.fixture
|
| 31 |
+
def data_missing(dtype):
|
| 32 |
+
"""
|
| 33 |
+
Fixture returning array with missing data according to parametrized float
|
| 34 |
+
'dtype'.
|
| 35 |
+
"""
|
| 36 |
+
return pd.array([np.nan, 0.1], dtype=dtype)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@pytest.fixture(params=["data", "data_missing"])
|
| 40 |
+
def all_data(request, data, data_missing):
|
| 41 |
+
"""Parametrized fixture returning 'data' or 'data_missing' float arrays.
|
| 42 |
+
|
| 43 |
+
Used to test dtype conversion with and without missing values.
|
| 44 |
+
"""
|
| 45 |
+
if request.param == "data":
|
| 46 |
+
return data
|
| 47 |
+
elif request.param == "data_missing":
|
| 48 |
+
return data_missing
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/test_arithmetic.py
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import operator
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import pandas._testing as tm
|
| 8 |
+
from pandas.core.arrays import FloatingArray
|
| 9 |
+
|
| 10 |
+
# Basic test for the arithmetic array ops
|
| 11 |
+
# -----------------------------------------------------------------------------
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@pytest.mark.parametrize(
|
| 15 |
+
"opname, exp",
|
| 16 |
+
[
|
| 17 |
+
("add", [1.1, 2.2, None, None, 5.5]),
|
| 18 |
+
("mul", [0.1, 0.4, None, None, 2.5]),
|
| 19 |
+
("sub", [0.9, 1.8, None, None, 4.5]),
|
| 20 |
+
("truediv", [10.0, 10.0, None, None, 10.0]),
|
| 21 |
+
("floordiv", [9.0, 9.0, None, None, 10.0]),
|
| 22 |
+
("mod", [0.1, 0.2, None, None, 0.0]),
|
| 23 |
+
],
|
| 24 |
+
ids=["add", "mul", "sub", "div", "floordiv", "mod"],
|
| 25 |
+
)
|
| 26 |
+
def test_array_op(dtype, opname, exp):
|
| 27 |
+
a = pd.array([1.0, 2.0, None, 4.0, 5.0], dtype=dtype)
|
| 28 |
+
b = pd.array([0.1, 0.2, 0.3, None, 0.5], dtype=dtype)
|
| 29 |
+
|
| 30 |
+
op = getattr(operator, opname)
|
| 31 |
+
|
| 32 |
+
result = op(a, b)
|
| 33 |
+
expected = pd.array(exp, dtype=dtype)
|
| 34 |
+
tm.assert_extension_array_equal(result, expected)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@pytest.mark.parametrize("zero, negative", [(0, False), (0.0, False), (-0.0, True)])
|
| 38 |
+
def test_divide_by_zero(dtype, zero, negative):
|
| 39 |
+
# TODO pending NA/NaN discussion
|
| 40 |
+
# https://github.com/pandas-dev/pandas/issues/32265/
|
| 41 |
+
a = pd.array([0, 1, -1, None], dtype=dtype)
|
| 42 |
+
result = a / zero
|
| 43 |
+
expected = FloatingArray(
|
| 44 |
+
np.array([np.nan, np.inf, -np.inf, np.nan], dtype=dtype.numpy_dtype),
|
| 45 |
+
np.array([False, False, False, True]),
|
| 46 |
+
)
|
| 47 |
+
if negative:
|
| 48 |
+
expected *= -1
|
| 49 |
+
tm.assert_extension_array_equal(result, expected)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def test_pow_scalar(dtype):
|
| 53 |
+
a = pd.array([-1, 0, 1, None, 2], dtype=dtype)
|
| 54 |
+
result = a**0
|
| 55 |
+
expected = pd.array([1, 1, 1, 1, 1], dtype=dtype)
|
| 56 |
+
tm.assert_extension_array_equal(result, expected)
|
| 57 |
+
|
| 58 |
+
result = a**1
|
| 59 |
+
expected = pd.array([-1, 0, 1, None, 2], dtype=dtype)
|
| 60 |
+
tm.assert_extension_array_equal(result, expected)
|
| 61 |
+
|
| 62 |
+
result = a**pd.NA
|
| 63 |
+
expected = pd.array([None, None, 1, None, None], dtype=dtype)
|
| 64 |
+
tm.assert_extension_array_equal(result, expected)
|
| 65 |
+
|
| 66 |
+
result = a**np.nan
|
| 67 |
+
# TODO np.nan should be converted to pd.NA / missing before operation?
|
| 68 |
+
expected = FloatingArray(
|
| 69 |
+
np.array([np.nan, np.nan, 1, np.nan, np.nan], dtype=dtype.numpy_dtype),
|
| 70 |
+
mask=a._mask,
|
| 71 |
+
)
|
| 72 |
+
tm.assert_extension_array_equal(result, expected)
|
| 73 |
+
|
| 74 |
+
# reversed
|
| 75 |
+
a = a[1:] # Can't raise integers to negative powers.
|
| 76 |
+
|
| 77 |
+
result = 0**a
|
| 78 |
+
expected = pd.array([1, 0, None, 0], dtype=dtype)
|
| 79 |
+
tm.assert_extension_array_equal(result, expected)
|
| 80 |
+
|
| 81 |
+
result = 1**a
|
| 82 |
+
expected = pd.array([1, 1, 1, 1], dtype=dtype)
|
| 83 |
+
tm.assert_extension_array_equal(result, expected)
|
| 84 |
+
|
| 85 |
+
result = pd.NA**a
|
| 86 |
+
expected = pd.array([1, None, None, None], dtype=dtype)
|
| 87 |
+
tm.assert_extension_array_equal(result, expected)
|
| 88 |
+
|
| 89 |
+
result = np.nan**a
|
| 90 |
+
expected = FloatingArray(
|
| 91 |
+
np.array([1, np.nan, np.nan, np.nan], dtype=dtype.numpy_dtype), mask=a._mask
|
| 92 |
+
)
|
| 93 |
+
tm.assert_extension_array_equal(result, expected)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def test_pow_array(dtype):
|
| 97 |
+
a = pd.array([0, 0, 0, 1, 1, 1, None, None, None], dtype=dtype)
|
| 98 |
+
b = pd.array([0, 1, None, 0, 1, None, 0, 1, None], dtype=dtype)
|
| 99 |
+
result = a**b
|
| 100 |
+
expected = pd.array([1, 0, None, 1, 1, 1, 1, None, None], dtype=dtype)
|
| 101 |
+
tm.assert_extension_array_equal(result, expected)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def test_rpow_one_to_na():
|
| 105 |
+
# https://github.com/pandas-dev/pandas/issues/22022
|
| 106 |
+
# https://github.com/pandas-dev/pandas/issues/29997
|
| 107 |
+
arr = pd.array([np.nan, np.nan], dtype="Float64")
|
| 108 |
+
result = np.array([1.0, 2.0]) ** arr
|
| 109 |
+
expected = pd.array([1.0, np.nan], dtype="Float64")
|
| 110 |
+
tm.assert_extension_array_equal(result, expected)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
@pytest.mark.parametrize("other", [0, 0.5])
|
| 114 |
+
def test_arith_zero_dim_ndarray(other):
|
| 115 |
+
arr = pd.array([1, None, 2], dtype="Float64")
|
| 116 |
+
result = arr + np.array(other)
|
| 117 |
+
expected = arr + other
|
| 118 |
+
tm.assert_equal(result, expected)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
# Test generic characteristics / errors
|
| 122 |
+
# -----------------------------------------------------------------------------
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def test_error_invalid_values(data, all_arithmetic_operators, using_infer_string):
|
| 126 |
+
op = all_arithmetic_operators
|
| 127 |
+
s = pd.Series(data)
|
| 128 |
+
ops = getattr(s, op)
|
| 129 |
+
|
| 130 |
+
if using_infer_string:
|
| 131 |
+
import pyarrow as pa
|
| 132 |
+
|
| 133 |
+
errs = (TypeError, pa.lib.ArrowNotImplementedError, NotImplementedError)
|
| 134 |
+
else:
|
| 135 |
+
errs = TypeError
|
| 136 |
+
|
| 137 |
+
# invalid scalars
|
| 138 |
+
msg = "|".join(
|
| 139 |
+
[
|
| 140 |
+
r"can only perform ops with numeric values",
|
| 141 |
+
r"FloatingArray cannot perform the operation mod",
|
| 142 |
+
"unsupported operand type",
|
| 143 |
+
"not all arguments converted during string formatting",
|
| 144 |
+
"can't multiply sequence by non-int of type 'float'",
|
| 145 |
+
"ufunc 'subtract' cannot use operands with types dtype",
|
| 146 |
+
r"can only concatenate str \(not \"float\"\) to str",
|
| 147 |
+
"ufunc '.*' not supported for the input types, and the inputs could not",
|
| 148 |
+
"ufunc '.*' did not contain a loop with signature matching types",
|
| 149 |
+
"Concatenation operation is not implemented for NumPy arrays",
|
| 150 |
+
"has no kernel",
|
| 151 |
+
"not implemented",
|
| 152 |
+
]
|
| 153 |
+
)
|
| 154 |
+
with pytest.raises(errs, match=msg):
|
| 155 |
+
ops("foo")
|
| 156 |
+
with pytest.raises(errs, match=msg):
|
| 157 |
+
ops(pd.Timestamp("20180101"))
|
| 158 |
+
|
| 159 |
+
# invalid array-likes
|
| 160 |
+
with pytest.raises(errs, match=msg):
|
| 161 |
+
ops(pd.Series("foo", index=s.index))
|
| 162 |
+
|
| 163 |
+
msg = "|".join(
|
| 164 |
+
[
|
| 165 |
+
"can only perform ops with numeric values",
|
| 166 |
+
"cannot perform .* with this index type: DatetimeArray",
|
| 167 |
+
"Addition/subtraction of integers and integer-arrays "
|
| 168 |
+
"with DatetimeArray is no longer supported. *",
|
| 169 |
+
"unsupported operand type",
|
| 170 |
+
"not all arguments converted during string formatting",
|
| 171 |
+
"can't multiply sequence by non-int of type 'float'",
|
| 172 |
+
"ufunc 'subtract' cannot use operands with types dtype",
|
| 173 |
+
(
|
| 174 |
+
"ufunc 'add' cannot use operands with types "
|
| 175 |
+
rf"dtype\('{tm.ENDIAN}M8\[ns\]'\)"
|
| 176 |
+
),
|
| 177 |
+
r"ufunc 'add' cannot use operands with types dtype\('float\d{2}'\)",
|
| 178 |
+
"cannot subtract DatetimeArray from ndarray",
|
| 179 |
+
"has no kernel",
|
| 180 |
+
"not implemented",
|
| 181 |
+
]
|
| 182 |
+
)
|
| 183 |
+
with pytest.raises(errs, match=msg):
|
| 184 |
+
ops(pd.Series(pd.date_range("20180101", periods=len(s))))
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
# Various
|
| 188 |
+
# -----------------------------------------------------------------------------
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def test_cross_type_arithmetic():
|
| 192 |
+
df = pd.DataFrame(
|
| 193 |
+
{
|
| 194 |
+
"A": pd.array([1, 2, np.nan], dtype="Float64"),
|
| 195 |
+
"B": pd.array([1, np.nan, 3], dtype="Float32"),
|
| 196 |
+
"C": np.array([1, 2, 3], dtype="float64"),
|
| 197 |
+
}
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
result = df.A + df.C
|
| 201 |
+
expected = pd.Series([2, 4, np.nan], dtype="Float64")
|
| 202 |
+
tm.assert_series_equal(result, expected)
|
| 203 |
+
|
| 204 |
+
result = (df.A + df.C) * 3 == 12
|
| 205 |
+
expected = pd.Series([False, True, None], dtype="boolean")
|
| 206 |
+
tm.assert_series_equal(result, expected)
|
| 207 |
+
|
| 208 |
+
result = df.A + df.B
|
| 209 |
+
expected = pd.Series([2, np.nan, np.nan], dtype="Float64")
|
| 210 |
+
tm.assert_series_equal(result, expected)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
@pytest.mark.parametrize(
|
| 214 |
+
"source, neg_target, abs_target",
|
| 215 |
+
[
|
| 216 |
+
([1.1, 2.2, 3.3], [-1.1, -2.2, -3.3], [1.1, 2.2, 3.3]),
|
| 217 |
+
([1.1, 2.2, None], [-1.1, -2.2, None], [1.1, 2.2, None]),
|
| 218 |
+
([-1.1, 0.0, 1.1], [1.1, 0.0, -1.1], [1.1, 0.0, 1.1]),
|
| 219 |
+
],
|
| 220 |
+
)
|
| 221 |
+
def test_unary_float_operators(float_ea_dtype, source, neg_target, abs_target):
|
| 222 |
+
# GH38794
|
| 223 |
+
dtype = float_ea_dtype
|
| 224 |
+
arr = pd.array(source, dtype=dtype)
|
| 225 |
+
neg_result, pos_result, abs_result = -arr, +arr, abs(arr)
|
| 226 |
+
neg_target = pd.array(neg_target, dtype=dtype)
|
| 227 |
+
abs_target = pd.array(abs_target, dtype=dtype)
|
| 228 |
+
|
| 229 |
+
tm.assert_extension_array_equal(neg_result, neg_target)
|
| 230 |
+
tm.assert_extension_array_equal(pos_result, arr)
|
| 231 |
+
assert not tm.shares_memory(pos_result, arr)
|
| 232 |
+
tm.assert_extension_array_equal(abs_result, abs_target)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def test_bitwise(dtype):
|
| 236 |
+
left = pd.array([1, None, 3, 4], dtype=dtype)
|
| 237 |
+
right = pd.array([None, 3, 5, 4], dtype=dtype)
|
| 238 |
+
|
| 239 |
+
with pytest.raises(TypeError, match="unsupported operand type"):
|
| 240 |
+
left | right
|
| 241 |
+
with pytest.raises(TypeError, match="unsupported operand type"):
|
| 242 |
+
left & right
|
| 243 |
+
with pytest.raises(TypeError, match="unsupported operand type"):
|
| 244 |
+
left ^ right
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/test_astype.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import pandas._testing as tm
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_astype():
|
| 9 |
+
# with missing values
|
| 10 |
+
arr = pd.array([0.1, 0.2, None], dtype="Float64")
|
| 11 |
+
|
| 12 |
+
with pytest.raises(ValueError, match="cannot convert NA to integer"):
|
| 13 |
+
arr.astype("int64")
|
| 14 |
+
|
| 15 |
+
with pytest.raises(ValueError, match="cannot convert float NaN to bool"):
|
| 16 |
+
arr.astype("bool")
|
| 17 |
+
|
| 18 |
+
result = arr.astype("float64")
|
| 19 |
+
expected = np.array([0.1, 0.2, np.nan], dtype="float64")
|
| 20 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 21 |
+
|
| 22 |
+
# no missing values
|
| 23 |
+
arr = pd.array([0.0, 1.0, 0.5], dtype="Float64")
|
| 24 |
+
result = arr.astype("int64")
|
| 25 |
+
expected = np.array([0, 1, 0], dtype="int64")
|
| 26 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 27 |
+
|
| 28 |
+
result = arr.astype("bool")
|
| 29 |
+
expected = np.array([False, True, True], dtype="bool")
|
| 30 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def test_astype_to_floating_array():
|
| 34 |
+
# astype to FloatingArray
|
| 35 |
+
arr = pd.array([0.0, 1.0, None], dtype="Float64")
|
| 36 |
+
|
| 37 |
+
result = arr.astype("Float64")
|
| 38 |
+
tm.assert_extension_array_equal(result, arr)
|
| 39 |
+
result = arr.astype(pd.Float64Dtype())
|
| 40 |
+
tm.assert_extension_array_equal(result, arr)
|
| 41 |
+
result = arr.astype("Float32")
|
| 42 |
+
expected = pd.array([0.0, 1.0, None], dtype="Float32")
|
| 43 |
+
tm.assert_extension_array_equal(result, expected)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def test_astype_to_boolean_array():
|
| 47 |
+
# astype to BooleanArray
|
| 48 |
+
arr = pd.array([0.0, 1.0, None], dtype="Float64")
|
| 49 |
+
|
| 50 |
+
result = arr.astype("boolean")
|
| 51 |
+
expected = pd.array([False, True, None], dtype="boolean")
|
| 52 |
+
tm.assert_extension_array_equal(result, expected)
|
| 53 |
+
result = arr.astype(pd.BooleanDtype())
|
| 54 |
+
tm.assert_extension_array_equal(result, expected)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def test_astype_to_integer_array():
|
| 58 |
+
# astype to IntegerArray
|
| 59 |
+
arr = pd.array([0.0, 1.5, None], dtype="Float64")
|
| 60 |
+
|
| 61 |
+
result = arr.astype("Int64")
|
| 62 |
+
expected = pd.array([0, 1, None], dtype="Int64")
|
| 63 |
+
tm.assert_extension_array_equal(result, expected)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def test_astype_str():
|
| 67 |
+
a = pd.array([0.1, 0.2, None], dtype="Float64")
|
| 68 |
+
expected = np.array(["0.1", "0.2", "<NA>"], dtype="U32")
|
| 69 |
+
|
| 70 |
+
tm.assert_numpy_array_equal(a.astype(str), expected)
|
| 71 |
+
tm.assert_numpy_array_equal(a.astype("str"), expected)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def test_astype_copy():
|
| 75 |
+
arr = pd.array([0.1, 0.2, None], dtype="Float64")
|
| 76 |
+
orig = pd.array([0.1, 0.2, None], dtype="Float64")
|
| 77 |
+
|
| 78 |
+
# copy=True -> ensure both data and mask are actual copies
|
| 79 |
+
result = arr.astype("Float64", copy=True)
|
| 80 |
+
assert result is not arr
|
| 81 |
+
assert not tm.shares_memory(result, arr)
|
| 82 |
+
result[0] = 10
|
| 83 |
+
tm.assert_extension_array_equal(arr, orig)
|
| 84 |
+
result[0] = pd.NA
|
| 85 |
+
tm.assert_extension_array_equal(arr, orig)
|
| 86 |
+
|
| 87 |
+
# copy=False
|
| 88 |
+
result = arr.astype("Float64", copy=False)
|
| 89 |
+
assert result is arr
|
| 90 |
+
assert np.shares_memory(result._data, arr._data)
|
| 91 |
+
assert np.shares_memory(result._mask, arr._mask)
|
| 92 |
+
result[0] = 10
|
| 93 |
+
assert arr[0] == 10
|
| 94 |
+
result[0] = pd.NA
|
| 95 |
+
assert arr[0] is pd.NA
|
| 96 |
+
|
| 97 |
+
# astype to different dtype -> always needs a copy -> even with copy=False
|
| 98 |
+
# we need to ensure that also the mask is actually copied
|
| 99 |
+
arr = pd.array([0.1, 0.2, None], dtype="Float64")
|
| 100 |
+
orig = pd.array([0.1, 0.2, None], dtype="Float64")
|
| 101 |
+
|
| 102 |
+
result = arr.astype("Float32", copy=False)
|
| 103 |
+
assert not tm.shares_memory(result, arr)
|
| 104 |
+
result[0] = 10
|
| 105 |
+
tm.assert_extension_array_equal(arr, orig)
|
| 106 |
+
result[0] = pd.NA
|
| 107 |
+
tm.assert_extension_array_equal(arr, orig)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def test_astype_object(dtype):
|
| 111 |
+
arr = pd.array([1.0, pd.NA], dtype=dtype)
|
| 112 |
+
|
| 113 |
+
result = arr.astype(object)
|
| 114 |
+
expected = np.array([1.0, pd.NA], dtype=object)
|
| 115 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 116 |
+
# check exact element types
|
| 117 |
+
assert isinstance(result[0], float)
|
| 118 |
+
assert result[1] is pd.NA
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def test_Float64_conversion():
|
| 122 |
+
# GH#40729
|
| 123 |
+
testseries = pd.Series(["1", "2", "3", "4"], dtype="object")
|
| 124 |
+
result = testseries.astype(pd.Float64Dtype())
|
| 125 |
+
|
| 126 |
+
expected = pd.Series([1.0, 2.0, 3.0, 4.0], dtype=pd.Float64Dtype())
|
| 127 |
+
|
| 128 |
+
tm.assert_series_equal(result, expected)
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/test_comparison.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import pandas._testing as tm
|
| 6 |
+
from pandas.core.arrays import FloatingArray
|
| 7 |
+
from pandas.tests.arrays.masked_shared import (
|
| 8 |
+
ComparisonOps,
|
| 9 |
+
NumericOps,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class TestComparisonOps(NumericOps, ComparisonOps):
|
| 14 |
+
@pytest.mark.parametrize("other", [True, False, pd.NA, -1.0, 0.0, 1])
|
| 15 |
+
def test_scalar(self, other, comparison_op, dtype):
|
| 16 |
+
ComparisonOps.test_scalar(self, other, comparison_op, dtype)
|
| 17 |
+
|
| 18 |
+
def test_compare_with_integerarray(self, comparison_op):
|
| 19 |
+
op = comparison_op
|
| 20 |
+
a = pd.array([0, 1, None] * 3, dtype="Int64")
|
| 21 |
+
b = pd.array([0] * 3 + [1] * 3 + [None] * 3, dtype="Float64")
|
| 22 |
+
other = b.astype("Int64")
|
| 23 |
+
expected = op(a, other)
|
| 24 |
+
result = op(a, b)
|
| 25 |
+
tm.assert_extension_array_equal(result, expected)
|
| 26 |
+
expected = op(other, a)
|
| 27 |
+
result = op(b, a)
|
| 28 |
+
tm.assert_extension_array_equal(result, expected)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def test_equals():
|
| 32 |
+
# GH-30652
|
| 33 |
+
# equals is generally tested in /tests/extension/base/methods, but this
|
| 34 |
+
# specifically tests that two arrays of the same class but different dtype
|
| 35 |
+
# do not evaluate equal
|
| 36 |
+
a1 = pd.array([1, 2, None], dtype="Float64")
|
| 37 |
+
a2 = pd.array([1, 2, None], dtype="Float32")
|
| 38 |
+
assert a1.equals(a2) is False
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def test_equals_nan_vs_na():
|
| 42 |
+
# GH#44382
|
| 43 |
+
|
| 44 |
+
mask = np.zeros(3, dtype=bool)
|
| 45 |
+
data = np.array([1.0, np.nan, 3.0], dtype=np.float64)
|
| 46 |
+
|
| 47 |
+
left = FloatingArray(data, mask)
|
| 48 |
+
assert left.equals(left)
|
| 49 |
+
tm.assert_extension_array_equal(left, left)
|
| 50 |
+
|
| 51 |
+
assert left.equals(left.copy())
|
| 52 |
+
assert left.equals(FloatingArray(data.copy(), mask.copy()))
|
| 53 |
+
|
| 54 |
+
mask2 = np.array([False, True, False], dtype=bool)
|
| 55 |
+
data2 = np.array([1.0, 2.0, 3.0], dtype=np.float64)
|
| 56 |
+
right = FloatingArray(data2, mask2)
|
| 57 |
+
assert right.equals(right)
|
| 58 |
+
tm.assert_extension_array_equal(right, right)
|
| 59 |
+
|
| 60 |
+
assert not left.equals(right)
|
| 61 |
+
|
| 62 |
+
# with mask[1] = True, the only difference is data[1], which should
|
| 63 |
+
# not matter for equals
|
| 64 |
+
mask[1] = True
|
| 65 |
+
assert left.equals(right)
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/test_concat.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import pandas._testing as tm
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
@pytest.mark.parametrize(
|
| 8 |
+
"to_concat_dtypes, result_dtype",
|
| 9 |
+
[
|
| 10 |
+
(["Float64", "Float64"], "Float64"),
|
| 11 |
+
(["Float32", "Float64"], "Float64"),
|
| 12 |
+
(["Float32", "Float32"], "Float32"),
|
| 13 |
+
],
|
| 14 |
+
)
|
| 15 |
+
def test_concat_series(to_concat_dtypes, result_dtype):
|
| 16 |
+
result = pd.concat([pd.Series([1, 2, pd.NA], dtype=t) for t in to_concat_dtypes])
|
| 17 |
+
expected = pd.concat([pd.Series([1, 2, pd.NA], dtype=object)] * 2).astype(
|
| 18 |
+
result_dtype
|
| 19 |
+
)
|
| 20 |
+
tm.assert_series_equal(result, expected)
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/test_construction.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import pandas._testing as tm
|
| 6 |
+
from pandas.core.arrays import FloatingArray
|
| 7 |
+
from pandas.core.arrays.floating import (
|
| 8 |
+
Float32Dtype,
|
| 9 |
+
Float64Dtype,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def test_uses_pandas_na():
|
| 14 |
+
a = pd.array([1, None], dtype=Float64Dtype())
|
| 15 |
+
assert a[1] is pd.NA
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_floating_array_constructor():
|
| 19 |
+
values = np.array([1, 2, 3, 4], dtype="float64")
|
| 20 |
+
mask = np.array([False, False, False, True], dtype="bool")
|
| 21 |
+
|
| 22 |
+
result = FloatingArray(values, mask)
|
| 23 |
+
expected = pd.array([1, 2, 3, np.nan], dtype="Float64")
|
| 24 |
+
tm.assert_extension_array_equal(result, expected)
|
| 25 |
+
tm.assert_numpy_array_equal(result._data, values)
|
| 26 |
+
tm.assert_numpy_array_equal(result._mask, mask)
|
| 27 |
+
|
| 28 |
+
msg = r".* should be .* numpy array. Use the 'pd.array' function instead"
|
| 29 |
+
with pytest.raises(TypeError, match=msg):
|
| 30 |
+
FloatingArray(values.tolist(), mask)
|
| 31 |
+
|
| 32 |
+
with pytest.raises(TypeError, match=msg):
|
| 33 |
+
FloatingArray(values, mask.tolist())
|
| 34 |
+
|
| 35 |
+
with pytest.raises(TypeError, match=msg):
|
| 36 |
+
FloatingArray(values.astype(int), mask)
|
| 37 |
+
|
| 38 |
+
msg = r"__init__\(\) missing 1 required positional argument: 'mask'"
|
| 39 |
+
with pytest.raises(TypeError, match=msg):
|
| 40 |
+
FloatingArray(values)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_floating_array_disallows_float16():
|
| 44 |
+
# GH#44715
|
| 45 |
+
arr = np.array([1, 2], dtype=np.float16)
|
| 46 |
+
mask = np.array([False, False])
|
| 47 |
+
|
| 48 |
+
msg = "FloatingArray does not support np.float16 dtype"
|
| 49 |
+
with pytest.raises(TypeError, match=msg):
|
| 50 |
+
FloatingArray(arr, mask)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def test_floating_array_disallows_Float16_dtype(request):
|
| 54 |
+
# GH#44715
|
| 55 |
+
with pytest.raises(TypeError, match="data type 'Float16' not understood"):
|
| 56 |
+
pd.array([1.0, 2.0], dtype="Float16")
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def test_floating_array_constructor_copy():
|
| 60 |
+
values = np.array([1, 2, 3, 4], dtype="float64")
|
| 61 |
+
mask = np.array([False, False, False, True], dtype="bool")
|
| 62 |
+
|
| 63 |
+
result = FloatingArray(values, mask)
|
| 64 |
+
assert result._data is values
|
| 65 |
+
assert result._mask is mask
|
| 66 |
+
|
| 67 |
+
result = FloatingArray(values, mask, copy=True)
|
| 68 |
+
assert result._data is not values
|
| 69 |
+
assert result._mask is not mask
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def test_to_array():
|
| 73 |
+
result = pd.array([0.1, 0.2, 0.3, 0.4])
|
| 74 |
+
expected = pd.array([0.1, 0.2, 0.3, 0.4], dtype="Float64")
|
| 75 |
+
tm.assert_extension_array_equal(result, expected)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@pytest.mark.parametrize(
|
| 79 |
+
"a, b",
|
| 80 |
+
[
|
| 81 |
+
([1, None], [1, pd.NA]),
|
| 82 |
+
([None], [pd.NA]),
|
| 83 |
+
([None, np.nan], [pd.NA, pd.NA]),
|
| 84 |
+
([1, np.nan], [1, pd.NA]),
|
| 85 |
+
([np.nan], [pd.NA]),
|
| 86 |
+
],
|
| 87 |
+
)
|
| 88 |
+
def test_to_array_none_is_nan(a, b):
|
| 89 |
+
result = pd.array(a, dtype="Float64")
|
| 90 |
+
expected = pd.array(b, dtype="Float64")
|
| 91 |
+
tm.assert_extension_array_equal(result, expected)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def test_to_array_mixed_integer_float():
|
| 95 |
+
result = pd.array([1, 2.0])
|
| 96 |
+
expected = pd.array([1.0, 2.0], dtype="Float64")
|
| 97 |
+
tm.assert_extension_array_equal(result, expected)
|
| 98 |
+
|
| 99 |
+
result = pd.array([1, None, 2.0])
|
| 100 |
+
expected = pd.array([1.0, None, 2.0], dtype="Float64")
|
| 101 |
+
tm.assert_extension_array_equal(result, expected)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
@pytest.mark.parametrize(
|
| 105 |
+
"values",
|
| 106 |
+
[
|
| 107 |
+
["foo", "bar"],
|
| 108 |
+
"foo",
|
| 109 |
+
1,
|
| 110 |
+
1.0,
|
| 111 |
+
pd.date_range("20130101", periods=2),
|
| 112 |
+
np.array(["foo"]),
|
| 113 |
+
[[1, 2], [3, 4]],
|
| 114 |
+
[np.nan, {"a": 1}],
|
| 115 |
+
# GH#44514 all-NA case used to get quietly swapped out before checking ndim
|
| 116 |
+
np.array([pd.NA] * 6, dtype=object).reshape(3, 2),
|
| 117 |
+
],
|
| 118 |
+
)
|
| 119 |
+
def test_to_array_error(values):
|
| 120 |
+
# error in converting existing arrays to FloatingArray
|
| 121 |
+
msg = "|".join(
|
| 122 |
+
[
|
| 123 |
+
"cannot be converted to FloatingDtype",
|
| 124 |
+
"values must be a 1D list-like",
|
| 125 |
+
"Cannot pass scalar",
|
| 126 |
+
r"float\(\) argument must be a string or a (real )?number, not 'dict'",
|
| 127 |
+
"could not convert string to float: 'foo'",
|
| 128 |
+
r"could not convert string to float: np\.str_\('foo'\)",
|
| 129 |
+
]
|
| 130 |
+
)
|
| 131 |
+
with pytest.raises((TypeError, ValueError), match=msg):
|
| 132 |
+
pd.array(values, dtype="Float64")
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
@pytest.mark.parametrize("values", [["1", "2", None], ["1.5", "2", None]])
|
| 136 |
+
def test_construct_from_float_strings(values):
|
| 137 |
+
# see also test_to_integer_array_str
|
| 138 |
+
expected = pd.array([float(values[0]), 2, None], dtype="Float64")
|
| 139 |
+
|
| 140 |
+
res = pd.array(values, dtype="Float64")
|
| 141 |
+
tm.assert_extension_array_equal(res, expected)
|
| 142 |
+
|
| 143 |
+
res = FloatingArray._from_sequence(values)
|
| 144 |
+
tm.assert_extension_array_equal(res, expected)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def test_to_array_inferred_dtype():
|
| 148 |
+
# if values has dtype -> respect it
|
| 149 |
+
result = pd.array(np.array([1, 2], dtype="float32"))
|
| 150 |
+
assert result.dtype == Float32Dtype()
|
| 151 |
+
|
| 152 |
+
# if values have no dtype -> always float64
|
| 153 |
+
result = pd.array([1.0, 2.0])
|
| 154 |
+
assert result.dtype == Float64Dtype()
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def test_to_array_dtype_keyword():
|
| 158 |
+
result = pd.array([1, 2], dtype="Float32")
|
| 159 |
+
assert result.dtype == Float32Dtype()
|
| 160 |
+
|
| 161 |
+
# if values has dtype -> override it
|
| 162 |
+
result = pd.array(np.array([1, 2], dtype="float32"), dtype="Float64")
|
| 163 |
+
assert result.dtype == Float64Dtype()
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def test_to_array_integer():
|
| 167 |
+
result = pd.array([1, 2], dtype="Float64")
|
| 168 |
+
expected = pd.array([1.0, 2.0], dtype="Float64")
|
| 169 |
+
tm.assert_extension_array_equal(result, expected)
|
| 170 |
+
|
| 171 |
+
# for integer dtypes, the itemsize is not preserved
|
| 172 |
+
# TODO can we specify "floating" in general?
|
| 173 |
+
result = pd.array(np.array([1, 2], dtype="int32"), dtype="Float64")
|
| 174 |
+
assert result.dtype == Float64Dtype()
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
@pytest.mark.parametrize(
|
| 178 |
+
"bool_values, values, target_dtype, expected_dtype",
|
| 179 |
+
[
|
| 180 |
+
([False, True], [0, 1], Float64Dtype(), Float64Dtype()),
|
| 181 |
+
([False, True], [0, 1], "Float64", Float64Dtype()),
|
| 182 |
+
([False, True, np.nan], [0, 1, np.nan], Float64Dtype(), Float64Dtype()),
|
| 183 |
+
],
|
| 184 |
+
)
|
| 185 |
+
def test_to_array_bool(bool_values, values, target_dtype, expected_dtype):
|
| 186 |
+
result = pd.array(bool_values, dtype=target_dtype)
|
| 187 |
+
assert result.dtype == expected_dtype
|
| 188 |
+
expected = pd.array(values, dtype=target_dtype)
|
| 189 |
+
tm.assert_extension_array_equal(result, expected)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def test_series_from_float(data):
|
| 193 |
+
# construct from our dtype & string dtype
|
| 194 |
+
dtype = data.dtype
|
| 195 |
+
|
| 196 |
+
# from float
|
| 197 |
+
expected = pd.Series(data)
|
| 198 |
+
result = pd.Series(data.to_numpy(na_value=np.nan, dtype="float"), dtype=str(dtype))
|
| 199 |
+
tm.assert_series_equal(result, expected)
|
| 200 |
+
|
| 201 |
+
# from list
|
| 202 |
+
expected = pd.Series(data)
|
| 203 |
+
result = pd.Series(np.array(data).tolist(), dtype=str(dtype))
|
| 204 |
+
tm.assert_series_equal(result, expected)
|
llava_next/lib/python3.10/site-packages/pandas/tests/arrays/floating/test_contains.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
import pandas as pd
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def test_contains_nan():
|
| 7 |
+
# GH#52840
|
| 8 |
+
arr = pd.array(range(5)) / 0
|
| 9 |
+
|
| 10 |
+
assert np.isnan(arr._data[0])
|
| 11 |
+
assert not arr.isna()[0]
|
| 12 |
+
assert np.nan in arr
|