content
stringlengths
1
103k
path
stringlengths
8
216
filename
stringlengths
2
179
language
stringclasses
15 values
size_bytes
int64
2
189k
quality_score
float64
0.5
0.95
complexity
float64
0
1
documentation_ratio
float64
0
1
repository
stringclasses
5 values
stars
int64
0
1k
created_date
stringdate
2023-07-10 19:21:08
2025-07-09 19:11:45
license
stringclasses
4 values
is_test
bool
2 classes
file_hash
stringlengths
32
32
import operator\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.arrays import BooleanArray\nfrom pandas.core.ops.mask_ops import (\n kleene_and,\n kleene_or,\n kleene_xor,\n)\nfrom pandas.tests.extension.base import BaseOpsUtil\n\n\nclass TestLogicalOps(BaseOpsUtil):\n def test_numpy_scalars_ok(self, all_logical_operators):\n a = pd.array([True, False, None], dtype="boolean")\n op = getattr(a, all_logical_operators)\n\n tm.assert_extension_array_equal(op(True), op(np.bool_(True)))\n tm.assert_extension_array_equal(op(False), op(np.bool_(False)))\n\n def get_op_from_name(self, op_name):\n short_opname = op_name.strip("_")\n short_opname = short_opname if "xor" in short_opname else short_opname + "_"\n try:\n op = getattr(operator, short_opname)\n except AttributeError:\n # Assume it is the reverse operator\n rop = getattr(operator, short_opname[1:])\n op = lambda x, y: rop(y, x)\n\n return op\n\n def test_empty_ok(self, all_logical_operators):\n a = pd.array([], dtype="boolean")\n op_name = all_logical_operators\n result = getattr(a, op_name)(True)\n tm.assert_extension_array_equal(a, result)\n\n result = getattr(a, op_name)(False)\n tm.assert_extension_array_equal(a, result)\n\n result = getattr(a, op_name)(pd.NA)\n tm.assert_extension_array_equal(a, result)\n\n @pytest.mark.parametrize(\n "other", ["a", pd.Timestamp(2017, 1, 1, 12), np.timedelta64(4)]\n )\n def test_eq_mismatched_type(self, other):\n # GH-44499\n arr = pd.array([True, False])\n result = arr == other\n expected = pd.array([False, False])\n tm.assert_extension_array_equal(result, expected)\n\n result = arr != other\n expected = pd.array([True, True])\n tm.assert_extension_array_equal(result, expected)\n\n def test_logical_length_mismatch_raises(self, all_logical_operators):\n op_name = all_logical_operators\n a = pd.array([True, False, None], dtype="boolean")\n msg = "Lengths must match"\n\n with pytest.raises(ValueError, match=msg):\n getattr(a, op_name)([True, False])\n\n with pytest.raises(ValueError, match=msg):\n getattr(a, op_name)(np.array([True, False]))\n\n with pytest.raises(ValueError, match=msg):\n getattr(a, op_name)(pd.array([True, False], dtype="boolean"))\n\n def test_logical_nan_raises(self, all_logical_operators):\n op_name = all_logical_operators\n a = pd.array([True, False, None], dtype="boolean")\n msg = "Got float instead"\n\n with pytest.raises(TypeError, match=msg):\n getattr(a, op_name)(np.nan)\n\n @pytest.mark.parametrize("other", ["a", 1])\n def test_non_bool_or_na_other_raises(self, other, all_logical_operators):\n a = pd.array([True, False], dtype="boolean")\n with pytest.raises(TypeError, match=str(type(other).__name__)):\n getattr(a, all_logical_operators)(other)\n\n def test_kleene_or(self):\n # A clear test of behavior.\n a = pd.array([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean")\n b = pd.array([True, False, None] * 3, dtype="boolean")\n result = a | b\n expected = pd.array(\n [True, True, True, True, False, None, True, None, None], dtype="boolean"\n )\n tm.assert_extension_array_equal(result, expected)\n\n result = b | a\n tm.assert_extension_array_equal(result, expected)\n\n # ensure we haven't mutated anything inplace\n tm.assert_extension_array_equal(\n a, pd.array([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean")\n )\n tm.assert_extension_array_equal(\n b, pd.array([True, False, None] * 3, dtype="boolean")\n )\n\n @pytest.mark.parametrize(\n "other, expected",\n [\n (pd.NA, [True, None, None]),\n (True, [True, True, True]),\n (np.bool_(True), [True, True, True]),\n (False, [True, False, None]),\n (np.bool_(False), [True, False, None]),\n ],\n )\n def test_kleene_or_scalar(self, other, expected):\n # TODO: test True & False\n a = pd.array([True, False, None], dtype="boolean")\n result = a | other\n expected = pd.array(expected, dtype="boolean")\n tm.assert_extension_array_equal(result, expected)\n\n result = other | a\n tm.assert_extension_array_equal(result, expected)\n\n # ensure we haven't mutated anything inplace\n tm.assert_extension_array_equal(\n a, pd.array([True, False, None], dtype="boolean")\n )\n\n def test_kleene_and(self):\n # A clear test of behavior.\n a = pd.array([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean")\n b = pd.array([True, False, None] * 3, dtype="boolean")\n result = a & b\n expected = pd.array(\n [True, False, None, False, False, False, None, False, None], dtype="boolean"\n )\n tm.assert_extension_array_equal(result, expected)\n\n result = b & a\n tm.assert_extension_array_equal(result, expected)\n\n # ensure we haven't mutated anything inplace\n tm.assert_extension_array_equal(\n a, pd.array([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean")\n )\n tm.assert_extension_array_equal(\n b, pd.array([True, False, None] * 3, dtype="boolean")\n )\n\n @pytest.mark.parametrize(\n "other, expected",\n [\n (pd.NA, [None, False, None]),\n (True, [True, False, None]),\n (False, [False, False, False]),\n (np.bool_(True), [True, False, None]),\n (np.bool_(False), [False, False, False]),\n ],\n )\n def test_kleene_and_scalar(self, other, expected):\n a = pd.array([True, False, None], dtype="boolean")\n result = a & other\n expected = pd.array(expected, dtype="boolean")\n tm.assert_extension_array_equal(result, expected)\n\n result = other & a\n tm.assert_extension_array_equal(result, expected)\n\n # ensure we haven't mutated anything inplace\n tm.assert_extension_array_equal(\n a, pd.array([True, False, None], dtype="boolean")\n )\n\n def test_kleene_xor(self):\n a = pd.array([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean")\n b = pd.array([True, False, None] * 3, dtype="boolean")\n result = a ^ b\n expected = pd.array(\n [False, True, None, True, False, None, None, None, None], dtype="boolean"\n )\n tm.assert_extension_array_equal(result, expected)\n\n result = b ^ a\n tm.assert_extension_array_equal(result, expected)\n\n # ensure we haven't mutated anything inplace\n tm.assert_extension_array_equal(\n a, pd.array([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean")\n )\n tm.assert_extension_array_equal(\n b, pd.array([True, False, None] * 3, dtype="boolean")\n )\n\n @pytest.mark.parametrize(\n "other, expected",\n [\n (pd.NA, [None, None, None]),\n (True, [False, True, None]),\n (np.bool_(True), [False, True, None]),\n (np.bool_(False), [True, False, None]),\n ],\n )\n def test_kleene_xor_scalar(self, other, expected):\n a = pd.array([True, False, None], dtype="boolean")\n result = a ^ other\n expected = pd.array(expected, dtype="boolean")\n tm.assert_extension_array_equal(result, expected)\n\n result = other ^ a\n tm.assert_extension_array_equal(result, expected)\n\n # ensure we haven't mutated anything inplace\n tm.assert_extension_array_equal(\n a, pd.array([True, False, None], dtype="boolean")\n )\n\n @pytest.mark.parametrize("other", [True, False, pd.NA, [True, False, None] * 3])\n def test_no_masked_assumptions(self, other, all_logical_operators):\n # The logical operations should not assume that masked values are False!\n a = pd.arrays.BooleanArray(\n np.array([True, True, True, False, False, False, True, False, True]),\n np.array([False] * 6 + [True, True, True]),\n )\n b = pd.array([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean")\n if isinstance(other, list):\n other = pd.array(other, dtype="boolean")\n\n result = getattr(a, all_logical_operators)(other)\n expected = getattr(b, all_logical_operators)(other)\n tm.assert_extension_array_equal(result, expected)\n\n if isinstance(other, BooleanArray):\n other._data[other._mask] = True\n a._data[a._mask] = False\n\n result = getattr(a, all_logical_operators)(other)\n expected = getattr(b, all_logical_operators)(other)\n tm.assert_extension_array_equal(result, expected)\n\n\n@pytest.mark.parametrize("operation", [kleene_or, kleene_xor, kleene_and])\ndef test_error_both_scalar(operation):\n msg = r"Either `left` or `right` need to be a np\.ndarray."\n with pytest.raises(TypeError, match=msg):\n # masks need to be non-None, otherwise it ends up in an infinite recursion\n operation(True, True, np.zeros(1), np.zeros(1))\n
.venv\Lib\site-packages\pandas\tests\arrays\boolean\test_logical.py
test_logical.py
Python
9,335
0.95
0.07874
0.061611
react-lib
409
2025-03-10T02:38:50.743337
GPL-3.0
true
a4c233d07313c825990b84ffdc802ea8
import pandas as pd\nimport pandas._testing as tm\n\n\nclass TestUnaryOps:\n def test_invert(self):\n a = pd.array([True, False, None], dtype="boolean")\n expected = pd.array([False, True, None], dtype="boolean")\n tm.assert_extension_array_equal(~a, expected)\n\n expected = pd.Series(expected, index=["a", "b", "c"], name="name")\n result = ~pd.Series(a, index=["a", "b", "c"], name="name")\n tm.assert_series_equal(result, expected)\n\n df = pd.DataFrame({"A": a, "B": [True, False, False]}, index=["a", "b", "c"])\n result = ~df\n expected = pd.DataFrame(\n {"A": expected, "B": [False, True, True]}, index=["a", "b", "c"]\n )\n tm.assert_frame_equal(result, expected)\n\n def test_abs(self):\n # matching numpy behavior, abs is the identity function\n arr = pd.array([True, False, None], dtype="boolean")\n result = abs(arr)\n\n tm.assert_extension_array_equal(result, arr)\n
.venv\Lib\site-packages\pandas\tests\arrays\boolean\test_ops.py
test_ops.py
Python
975
0.95
0.148148
0.047619
awesome-app
577
2025-01-05T21:04:10.224028
Apache-2.0
true
408f7207d255ece1c2863223f08bb212
import numpy as np\nimport pytest\n\nimport pandas as pd\n\n\n@pytest.fixture\ndef data():\n """Fixture returning boolean array, with valid and missing values."""\n return pd.array(\n [True, False] * 4 + [np.nan] + [True, False] * 44 + [np.nan] + [True, False],\n dtype="boolean",\n )\n\n\n@pytest.mark.parametrize(\n "values, exp_any, exp_all, exp_any_noskip, exp_all_noskip",\n [\n ([True, pd.NA], True, True, True, pd.NA),\n ([False, pd.NA], False, False, pd.NA, False),\n ([pd.NA], False, True, pd.NA, pd.NA),\n ([], False, True, False, True),\n # GH-33253: all True / all False values buggy with skipna=False\n ([True, True], True, True, True, True),\n ([False, False], False, False, False, False),\n ],\n)\ndef test_any_all(values, exp_any, exp_all, exp_any_noskip, exp_all_noskip):\n # the methods return numpy scalars\n exp_any = pd.NA if exp_any is pd.NA else np.bool_(exp_any)\n exp_all = pd.NA if exp_all is pd.NA else np.bool_(exp_all)\n exp_any_noskip = pd.NA if exp_any_noskip is pd.NA else np.bool_(exp_any_noskip)\n exp_all_noskip = pd.NA if exp_all_noskip is pd.NA else np.bool_(exp_all_noskip)\n\n for con in [pd.array, pd.Series]:\n a = con(values, dtype="boolean")\n assert a.any() is exp_any\n assert a.all() is exp_all\n assert a.any(skipna=False) is exp_any_noskip\n assert a.all(skipna=False) is exp_all_noskip\n\n assert np.any(a.any()) is exp_any\n assert np.all(a.all()) is exp_all\n\n\n@pytest.mark.parametrize("dropna", [True, False])\ndef test_reductions_return_types(dropna, data, all_numeric_reductions):\n op = all_numeric_reductions\n s = pd.Series(data)\n if dropna:\n s = s.dropna()\n\n if op in ("sum", "prod"):\n assert isinstance(getattr(s, op)(), np.int_)\n elif op == "count":\n # Oddly on the 32 bit build (but not Windows), this is intc (!= intp)\n assert isinstance(getattr(s, op)(), np.integer)\n elif op in ("min", "max"):\n assert isinstance(getattr(s, op)(), np.bool_)\n else:\n # "mean", "std", "var", "median", "kurt", "skew"\n assert isinstance(getattr(s, op)(), np.float64)\n
.venv\Lib\site-packages\pandas\tests\arrays\boolean\test_reduction.py
test_reduction.py
Python
2,183
0.95
0.16129
0.076923
python-kit
558
2024-11-07T07:19:32.960324
MIT
true
2b1993282a887d80e278c3360e6938e1
import pandas as pd\n\n\ndef test_repr():\n df = pd.DataFrame({"A": pd.array([True, False, None], dtype="boolean")})\n expected = " A\n0 True\n1 False\n2 <NA>"\n assert repr(df) == expected\n\n expected = "0 True\n1 False\n2 <NA>\nName: A, dtype: boolean"\n assert repr(df.A) == expected\n\n expected = "<BooleanArray>\n[True, False, <NA>]\nLength: 3, dtype: boolean"\n assert repr(df.A.array) == expected\n
.venv\Lib\site-packages\pandas\tests\arrays\boolean\test_repr.py
test_repr.py
Python
437
0.85
0.076923
0
node-utils
907
2025-06-09T18:59:43.601317
GPL-3.0
true
06a0580746286590e2a74458d5a9a47e
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\boolean\__pycache__\test_arithmetic.cpython-313.pyc
test_arithmetic.cpython-313.pyc
Other
5,623
0.95
0.075949
0.013514
python-kit
823
2024-11-01T02:24:16.162274
MIT
true
482b429c27371e4817a19823455717eb
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\boolean\__pycache__\test_astype.cpython-313.pyc
test_astype.cpython-313.pyc
Other
3,219
0.8
0
0.025
vue-tools
234
2023-09-21T09:57:57.955606
Apache-2.0
true
6f42a6e9948b98bbd458cacaf9269545
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\boolean\__pycache__\test_comparison.cpython-313.pyc
test_comparison.cpython-313.pyc
Other
3,768
0.8
0
0.027027
python-kit
567
2024-11-02T00:36:49.102616
GPL-3.0
true
2828e4373e6b94bb14547b501d4ebef0
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\boolean\__pycache__\test_construction.cpython-313.pyc
test_construction.cpython-313.pyc
Other
17,749
0.8
0.007874
0
vue-tools
701
2024-03-12T02:53:55.408587
GPL-3.0
true
7dbd2a80999cba7cc58da9335666d7a1
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\boolean\__pycache__\test_function.cpython-313.pyc
test_function.cpython-313.pyc
Other
7,361
0.95
0
0.025641
python-kit
215
2025-02-21T10:53:59.743853
BSD-3-Clause
true
ad2147c518211bff6872b5136f279fd9
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\boolean\__pycache__\test_indexing.cpython-313.pyc
test_indexing.cpython-313.pyc
Other
921
0.8
0
0
react-lib
283
2024-08-09T08:09:22.346639
MIT
true
7e84e87cc958755fbe974fc764c48325
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\boolean\__pycache__\test_logical.cpython-313.pyc
test_logical.cpython-313.pyc
Other
13,243
0.8
0
0.013423
python-kit
545
2025-01-01T08:41:36.469745
Apache-2.0
true
0d7dd271fb32b3484c4aa94b2fc8aefb
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\boolean\__pycache__\test_ops.cpython-313.pyc
test_ops.cpython-313.pyc
Other
1,793
0.7
0
0
node-utils
887
2024-05-11T10:14:25.155058
BSD-3-Clause
true
340220e7809b266fde34adf86331990a
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\boolean\__pycache__\test_reduction.cpython-313.pyc
test_reduction.cpython-313.pyc
Other
3,792
0.7
0
0
react-lib
959
2025-04-19T18:47:13.515605
GPL-3.0
true
af13556bd6047ebf090f5069f64e35e0
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\boolean\__pycache__\test_repr.cpython-313.pyc
test_repr.cpython-313.pyc
Other
933
0.8
0
0
node-utils
812
2025-05-10T08:41:35.506480
BSD-3-Clause
true
4d5042d7711bcdb99f409003d6b3fa25
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\boolean\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
202
0.7
0
0
python-kit
558
2024-03-02T17:21:00.420355
Apache-2.0
true
8c13f85a25ddeacc813584d18a79f6a9
import numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\n\n\n@pytest.mark.parametrize("ordered", [True, False])\n@pytest.mark.parametrize("categories", [["b", "a", "c"], ["a", "b", "c", "d"]])\ndef test_factorize(categories, ordered):\n cat = pd.Categorical(\n ["b", "b", "a", "c", None], categories=categories, ordered=ordered\n )\n codes, uniques = pd.factorize(cat)\n expected_codes = np.array([0, 0, 1, 2, -1], dtype=np.intp)\n expected_uniques = pd.Categorical(\n ["b", "a", "c"], categories=categories, ordered=ordered\n )\n\n tm.assert_numpy_array_equal(codes, expected_codes)\n tm.assert_categorical_equal(uniques, expected_uniques)\n\n\ndef test_factorized_sort():\n cat = pd.Categorical(["b", "b", None, "a"])\n codes, uniques = pd.factorize(cat, sort=True)\n expected_codes = np.array([1, 1, -1, 0], dtype=np.intp)\n expected_uniques = pd.Categorical(["a", "b"])\n\n tm.assert_numpy_array_equal(codes, expected_codes)\n tm.assert_categorical_equal(uniques, expected_uniques)\n\n\ndef test_factorized_sort_ordered():\n cat = pd.Categorical(\n ["b", "b", None, "a"], categories=["c", "b", "a"], ordered=True\n )\n\n codes, uniques = pd.factorize(cat, sort=True)\n expected_codes = np.array([0, 0, -1, 1], dtype=np.intp)\n expected_uniques = pd.Categorical(\n ["b", "a"], categories=["c", "b", "a"], ordered=True\n )\n\n tm.assert_numpy_array_equal(codes, expected_codes)\n tm.assert_categorical_equal(uniques, expected_uniques)\n\n\ndef test_isin_cats():\n # GH2003\n cat = pd.Categorical(["a", "b", np.nan])\n\n result = cat.isin(["a", np.nan])\n expected = np.array([True, False, True], dtype=bool)\n tm.assert_numpy_array_equal(expected, result)\n\n result = cat.isin(["a", "c"])\n expected = np.array([True, False, False], dtype=bool)\n tm.assert_numpy_array_equal(expected, result)\n\n\n@pytest.mark.parametrize("value", [[""], [None, ""], [pd.NaT, ""]])\ndef test_isin_cats_corner_cases(value):\n # GH36550\n cat = pd.Categorical([""])\n result = cat.isin(value)\n expected = np.array([True], dtype=bool)\n tm.assert_numpy_array_equal(expected, result)\n\n\n@pytest.mark.parametrize("empty", [[], pd.Series(dtype=object), np.array([])])\ndef test_isin_empty(empty):\n s = pd.Categorical(["a", "b"])\n expected = np.array([False, False], dtype=bool)\n\n result = s.isin(empty)\n tm.assert_numpy_array_equal(expected, result)\n\n\ndef test_diff():\n ser = pd.Series([1, 2, 3], dtype="category")\n\n msg = "Convert to a suitable dtype"\n with pytest.raises(TypeError, match=msg):\n ser.diff()\n\n df = ser.to_frame(name="A")\n with pytest.raises(TypeError, match=msg):\n df.diff()\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\test_algos.py
test_algos.py
Python
2,710
0.95
0.078652
0.030769
vue-tools
424
2025-01-20T02:20:32.926924
BSD-3-Clause
true
d9154be50b6804c80c49d3d8517506c5
import re\nimport sys\n\nimport numpy as np\nimport pytest\n\nfrom pandas.compat import PYPY\n\nfrom pandas import (\n Categorical,\n CategoricalDtype,\n DataFrame,\n Index,\n NaT,\n Series,\n date_range,\n)\nimport pandas._testing as tm\nfrom pandas.api.types import is_scalar\n\n\nclass TestCategoricalAnalytics:\n @pytest.mark.parametrize("aggregation", ["min", "max"])\n def test_min_max_not_ordered_raises(self, aggregation):\n # unordered cats have no min/max\n cat = Categorical(["a", "b", "c", "d"], ordered=False)\n msg = f"Categorical is not ordered for operation {aggregation}"\n agg_func = getattr(cat, aggregation)\n\n with pytest.raises(TypeError, match=msg):\n agg_func()\n\n ufunc = np.minimum if aggregation == "min" else np.maximum\n with pytest.raises(TypeError, match=msg):\n ufunc.reduce(cat)\n\n def test_min_max_ordered(self, index_or_series_or_array):\n cat = Categorical(["a", "b", "c", "d"], ordered=True)\n obj = index_or_series_or_array(cat)\n _min = obj.min()\n _max = obj.max()\n assert _min == "a"\n assert _max == "d"\n\n assert np.minimum.reduce(obj) == "a"\n assert np.maximum.reduce(obj) == "d"\n # TODO: raises if we pass axis=0 (on Index and Categorical, not Series)\n\n cat = Categorical(\n ["a", "b", "c", "d"], categories=["d", "c", "b", "a"], ordered=True\n )\n obj = index_or_series_or_array(cat)\n _min = obj.min()\n _max = obj.max()\n assert _min == "d"\n assert _max == "a"\n assert np.minimum.reduce(obj) == "d"\n assert np.maximum.reduce(obj) == "a"\n\n def test_min_max_reduce(self):\n # GH52788\n cat = Categorical(["a", "b", "c", "d"], ordered=True)\n df = DataFrame(cat)\n\n result_max = df.agg("max")\n expected_max = Series(Categorical(["d"], dtype=cat.dtype))\n tm.assert_series_equal(result_max, expected_max)\n\n result_min = df.agg("min")\n expected_min = Series(Categorical(["a"], dtype=cat.dtype))\n tm.assert_series_equal(result_min, expected_min)\n\n @pytest.mark.parametrize(\n "categories,expected",\n [\n (list("ABC"), np.nan),\n ([1, 2, 3], np.nan),\n pytest.param(\n Series(date_range("2020-01-01", periods=3), dtype="category"),\n NaT,\n marks=pytest.mark.xfail(\n reason="https://github.com/pandas-dev/pandas/issues/29962"\n ),\n ),\n ],\n )\n @pytest.mark.parametrize("aggregation", ["min", "max"])\n def test_min_max_ordered_empty(self, categories, expected, aggregation):\n # GH 30227\n cat = Categorical([], categories=categories, ordered=True)\n\n agg_func = getattr(cat, aggregation)\n result = agg_func()\n assert result is expected\n\n @pytest.mark.parametrize(\n "values, categories",\n [(["a", "b", "c", np.nan], list("cba")), ([1, 2, 3, np.nan], [3, 2, 1])],\n )\n @pytest.mark.parametrize("skipna", [True, False])\n @pytest.mark.parametrize("function", ["min", "max"])\n def test_min_max_with_nan(self, values, categories, function, skipna):\n # GH 25303\n cat = Categorical(values, categories=categories, ordered=True)\n result = getattr(cat, function)(skipna=skipna)\n\n if skipna is False:\n assert result is np.nan\n else:\n expected = categories[0] if function == "min" else categories[2]\n assert result == expected\n\n @pytest.mark.parametrize("function", ["min", "max"])\n @pytest.mark.parametrize("skipna", [True, False])\n def test_min_max_only_nan(self, function, skipna):\n # https://github.com/pandas-dev/pandas/issues/33450\n cat = Categorical([np.nan], categories=[1, 2], ordered=True)\n result = getattr(cat, function)(skipna=skipna)\n assert result is np.nan\n\n @pytest.mark.parametrize("method", ["min", "max"])\n def test_numeric_only_min_max_raises(self, method):\n # GH 25303\n cat = Categorical(\n [np.nan, 1, 2, np.nan], categories=[5, 4, 3, 2, 1], ordered=True\n )\n with pytest.raises(TypeError, match=".* got an unexpected keyword"):\n getattr(cat, method)(numeric_only=True)\n\n @pytest.mark.parametrize("method", ["min", "max"])\n def test_numpy_min_max_raises(self, method):\n cat = Categorical(["a", "b", "c", "b"], ordered=False)\n msg = (\n f"Categorical is not ordered for operation {method}\n"\n "you can use .as_ordered() to change the Categorical to an ordered one"\n )\n method = getattr(np, method)\n with pytest.raises(TypeError, match=re.escape(msg)):\n method(cat)\n\n @pytest.mark.parametrize("kwarg", ["axis", "out", "keepdims"])\n @pytest.mark.parametrize("method", ["min", "max"])\n def test_numpy_min_max_unsupported_kwargs_raises(self, method, kwarg):\n cat = Categorical(["a", "b", "c", "b"], ordered=True)\n msg = (\n f"the '{kwarg}' parameter is not supported in the pandas implementation "\n f"of {method}"\n )\n if kwarg == "axis":\n msg = r"`axis` must be fewer than the number of dimensions \(1\)"\n kwargs = {kwarg: 42}\n method = getattr(np, method)\n with pytest.raises(ValueError, match=msg):\n method(cat, **kwargs)\n\n @pytest.mark.parametrize("method, expected", [("min", "a"), ("max", "c")])\n def test_numpy_min_max_axis_equals_none(self, method, expected):\n cat = Categorical(["a", "b", "c", "b"], ordered=True)\n method = getattr(np, method)\n result = method(cat, axis=None)\n assert result == expected\n\n @pytest.mark.parametrize(\n "values,categories,exp_mode",\n [\n ([1, 1, 2, 4, 5, 5, 5], [5, 4, 3, 2, 1], [5]),\n ([1, 1, 1, 4, 5, 5, 5], [5, 4, 3, 2, 1], [5, 1]),\n ([1, 2, 3, 4, 5], [5, 4, 3, 2, 1], [5, 4, 3, 2, 1]),\n ([np.nan, np.nan, np.nan, 4, 5], [5, 4, 3, 2, 1], [5, 4]),\n ([np.nan, np.nan, np.nan, 4, 5, 4], [5, 4, 3, 2, 1], [4]),\n ([np.nan, np.nan, 4, 5, 4], [5, 4, 3, 2, 1], [4]),\n ],\n )\n def test_mode(self, values, categories, exp_mode):\n cat = Categorical(values, categories=categories, ordered=True)\n res = Series(cat).mode()._values\n exp = Categorical(exp_mode, categories=categories, ordered=True)\n tm.assert_categorical_equal(res, exp)\n\n def test_searchsorted(self, ordered):\n # https://github.com/pandas-dev/pandas/issues/8420\n # https://github.com/pandas-dev/pandas/issues/14522\n\n cat = Categorical(\n ["cheese", "milk", "apple", "bread", "bread"],\n categories=["cheese", "milk", "apple", "bread"],\n ordered=ordered,\n )\n ser = Series(cat)\n\n # Searching for single item argument, side='left' (default)\n res_cat = cat.searchsorted("apple")\n assert res_cat == 2\n assert is_scalar(res_cat)\n\n res_ser = ser.searchsorted("apple")\n assert res_ser == 2\n assert is_scalar(res_ser)\n\n # Searching for single item array, side='left' (default)\n res_cat = cat.searchsorted(["bread"])\n res_ser = ser.searchsorted(["bread"])\n exp = np.array([3], dtype=np.intp)\n tm.assert_numpy_array_equal(res_cat, exp)\n tm.assert_numpy_array_equal(res_ser, exp)\n\n # Searching for several items array, side='right'\n res_cat = cat.searchsorted(["apple", "bread"], side="right")\n res_ser = ser.searchsorted(["apple", "bread"], side="right")\n exp = np.array([3, 5], dtype=np.intp)\n tm.assert_numpy_array_equal(res_cat, exp)\n tm.assert_numpy_array_equal(res_ser, exp)\n\n # Searching for a single value that is not from the Categorical\n with pytest.raises(TypeError, match="cucumber"):\n cat.searchsorted("cucumber")\n with pytest.raises(TypeError, match="cucumber"):\n ser.searchsorted("cucumber")\n\n # Searching for multiple values one of each is not from the Categorical\n msg = (\n "Cannot setitem on a Categorical with a new category, "\n "set the categories first"\n )\n with pytest.raises(TypeError, match=msg):\n cat.searchsorted(["bread", "cucumber"])\n with pytest.raises(TypeError, match=msg):\n ser.searchsorted(["bread", "cucumber"])\n\n def test_unique(self, ordered):\n # GH38140\n dtype = CategoricalDtype(["a", "b", "c"], ordered=ordered)\n\n # categories are reordered based on value when ordered=False\n cat = Categorical(["a", "b", "c"], dtype=dtype)\n res = cat.unique()\n tm.assert_categorical_equal(res, cat)\n\n cat = Categorical(["a", "b", "a", "a"], dtype=dtype)\n res = cat.unique()\n tm.assert_categorical_equal(res, Categorical(["a", "b"], dtype=dtype))\n\n cat = Categorical(["c", "a", "b", "a", "a"], dtype=dtype)\n res = cat.unique()\n exp_cat = Categorical(["c", "a", "b"], dtype=dtype)\n tm.assert_categorical_equal(res, exp_cat)\n\n # nan must be removed\n cat = Categorical(["b", np.nan, "b", np.nan, "a"], dtype=dtype)\n res = cat.unique()\n exp_cat = Categorical(["b", np.nan, "a"], dtype=dtype)\n tm.assert_categorical_equal(res, exp_cat)\n\n def test_unique_index_series(self, ordered):\n # GH38140\n dtype = CategoricalDtype([3, 2, 1], ordered=ordered)\n\n c = Categorical([3, 1, 2, 2, 1], dtype=dtype)\n # Categorical.unique sorts categories by appearance order\n # if ordered=False\n exp = Categorical([3, 1, 2], dtype=dtype)\n tm.assert_categorical_equal(c.unique(), exp)\n\n tm.assert_index_equal(Index(c).unique(), Index(exp))\n tm.assert_categorical_equal(Series(c).unique(), exp)\n\n c = Categorical([1, 1, 2, 2], dtype=dtype)\n exp = Categorical([1, 2], dtype=dtype)\n tm.assert_categorical_equal(c.unique(), exp)\n tm.assert_index_equal(Index(c).unique(), Index(exp))\n tm.assert_categorical_equal(Series(c).unique(), exp)\n\n def test_shift(self):\n # GH 9416\n cat = Categorical(["a", "b", "c", "d", "a"])\n\n # shift forward\n sp1 = cat.shift(1)\n xp1 = Categorical([np.nan, "a", "b", "c", "d"])\n tm.assert_categorical_equal(sp1, xp1)\n tm.assert_categorical_equal(cat[:-1], sp1[1:])\n\n # shift back\n sn2 = cat.shift(-2)\n xp2 = Categorical(\n ["c", "d", "a", np.nan, np.nan], categories=["a", "b", "c", "d"]\n )\n tm.assert_categorical_equal(sn2, xp2)\n tm.assert_categorical_equal(cat[2:], sn2[:-2])\n\n # shift by zero\n tm.assert_categorical_equal(cat, cat.shift(0))\n\n def test_nbytes(self):\n cat = Categorical([1, 2, 3])\n exp = 3 + 3 * 8 # 3 int8s for values + 3 int64s for categories\n assert cat.nbytes == exp\n\n def test_memory_usage(self, using_infer_string):\n cat = Categorical([1, 2, 3])\n\n # .categories is an index, so we include the hashtable\n assert 0 < cat.nbytes <= cat.memory_usage()\n assert 0 < cat.nbytes <= cat.memory_usage(deep=True)\n\n cat = Categorical(["foo", "foo", "bar"])\n if using_infer_string:\n if cat.categories.dtype.storage == "python":\n assert cat.memory_usage(deep=True) > cat.nbytes\n else:\n assert cat.memory_usage(deep=True) >= cat.nbytes\n else:\n assert cat.memory_usage(deep=True) > cat.nbytes\n\n if not PYPY:\n # sys.getsizeof will call the .memory_usage with\n # deep=True, and add on some GC overhead\n diff = cat.memory_usage(deep=True) - sys.getsizeof(cat)\n assert abs(diff) < 100\n\n def test_map(self):\n c = Categorical(list("ABABC"), categories=list("CBA"), ordered=True)\n result = c.map(lambda x: x.lower(), na_action=None)\n exp = Categorical(list("ababc"), categories=list("cba"), ordered=True)\n tm.assert_categorical_equal(result, exp)\n\n c = Categorical(list("ABABC"), categories=list("ABC"), ordered=False)\n result = c.map(lambda x: x.lower(), na_action=None)\n exp = Categorical(list("ababc"), categories=list("abc"), ordered=False)\n tm.assert_categorical_equal(result, exp)\n\n result = c.map(lambda x: 1, na_action=None)\n # GH 12766: Return an index not an array\n tm.assert_index_equal(result, Index(np.array([1] * 5, dtype=np.int64)))\n\n @pytest.mark.parametrize("value", [1, "True", [1, 2, 3], 5.0])\n def test_validate_inplace_raises(self, value):\n cat = Categorical(["A", "B", "B", "C", "A"])\n msg = (\n 'For argument "inplace" expected type bool, '\n f"received type {type(value).__name__}"\n )\n\n with pytest.raises(ValueError, match=msg):\n cat.sort_values(inplace=value)\n\n def test_quantile_empty(self):\n # make sure we have correct itemsize on resulting codes\n cat = Categorical(["A", "B"])\n idx = Index([0.0, 0.5])\n result = cat[:0]._quantile(idx, interpolation="linear")\n assert result._codes.dtype == np.int8\n\n expected = cat.take([-1, -1], allow_fill=True)\n tm.assert_extension_array_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\test_analytics.py
test_analytics.py
Python
13,486
0.95
0.129577
0.09699
react-lib
915
2023-12-31T06:32:08.109111
BSD-3-Clause
true
5bd6eea63aa92a978052ff73539c616a
import re\n\nimport numpy as np\nimport pytest\n\nfrom pandas.compat import PY311\n\nfrom pandas import (\n Categorical,\n CategoricalIndex,\n DataFrame,\n Index,\n Series,\n StringDtype,\n)\nimport pandas._testing as tm\nfrom pandas.core.arrays.categorical import recode_for_categories\n\n\nclass TestCategoricalAPI:\n def test_to_list_deprecated(self):\n # GH#51254\n cat1 = Categorical(list("acb"), ordered=False)\n msg = "Categorical.to_list is deprecated and will be removed"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n cat1.to_list()\n\n def test_ordered_api(self):\n # GH 9347\n cat1 = Categorical(list("acb"), ordered=False)\n tm.assert_index_equal(cat1.categories, Index(["a", "b", "c"]))\n assert not cat1.ordered\n\n cat2 = Categorical(list("acb"), categories=list("bca"), ordered=False)\n tm.assert_index_equal(cat2.categories, Index(["b", "c", "a"]))\n assert not cat2.ordered\n\n cat3 = Categorical(list("acb"), ordered=True)\n tm.assert_index_equal(cat3.categories, Index(["a", "b", "c"]))\n assert cat3.ordered\n\n cat4 = Categorical(list("acb"), categories=list("bca"), ordered=True)\n tm.assert_index_equal(cat4.categories, Index(["b", "c", "a"]))\n assert cat4.ordered\n\n def test_set_ordered(self):\n cat = Categorical(["a", "b", "c", "a"], ordered=True)\n cat2 = cat.as_unordered()\n assert not cat2.ordered\n cat2 = cat.as_ordered()\n assert cat2.ordered\n\n assert cat2.set_ordered(True).ordered\n assert not cat2.set_ordered(False).ordered\n\n # removed in 0.19.0\n msg = (\n "property 'ordered' of 'Categorical' object has no setter"\n if PY311\n else "can't set attribute"\n )\n with pytest.raises(AttributeError, match=msg):\n cat.ordered = True\n with pytest.raises(AttributeError, match=msg):\n cat.ordered = False\n\n def test_rename_categories(self):\n cat = Categorical(["a", "b", "c", "a"])\n\n # inplace=False: the old one must not be changed\n res = cat.rename_categories([1, 2, 3])\n tm.assert_numpy_array_equal(\n res.__array__(), np.array([1, 2, 3, 1], dtype=np.int64)\n )\n tm.assert_index_equal(res.categories, Index([1, 2, 3]))\n\n exp_cat = np.array(["a", "b", "c", "a"], dtype=np.object_)\n tm.assert_numpy_array_equal(cat.__array__(), exp_cat)\n\n exp_cat = Index(["a", "b", "c"])\n tm.assert_index_equal(cat.categories, exp_cat)\n\n # GH18862 (let rename_categories take callables)\n result = cat.rename_categories(lambda x: x.upper())\n expected = Categorical(["A", "B", "C", "A"])\n tm.assert_categorical_equal(result, expected)\n\n @pytest.mark.parametrize("new_categories", [[1, 2, 3, 4], [1, 2]])\n def test_rename_categories_wrong_length_raises(self, new_categories):\n cat = Categorical(["a", "b", "c", "a"])\n msg = (\n "new categories need to have the same number of items as the "\n "old categories!"\n )\n with pytest.raises(ValueError, match=msg):\n cat.rename_categories(new_categories)\n\n def test_rename_categories_series(self):\n # https://github.com/pandas-dev/pandas/issues/17981\n c = Categorical(["a", "b"])\n result = c.rename_categories(Series([0, 1], index=["a", "b"]))\n expected = Categorical([0, 1])\n tm.assert_categorical_equal(result, expected)\n\n def test_rename_categories_dict(self):\n # GH 17336\n cat = Categorical(["a", "b", "c", "d"])\n res = cat.rename_categories({"a": 4, "b": 3, "c": 2, "d": 1})\n expected = Index([4, 3, 2, 1])\n tm.assert_index_equal(res.categories, expected)\n\n # Test for dicts of smaller length\n cat = Categorical(["a", "b", "c", "d"])\n res = cat.rename_categories({"a": 1, "c": 3})\n\n expected = Index([1, "b", 3, "d"])\n tm.assert_index_equal(res.categories, expected)\n\n # Test for dicts with bigger length\n cat = Categorical(["a", "b", "c", "d"])\n res = cat.rename_categories({"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6})\n expected = Index([1, 2, 3, 4])\n tm.assert_index_equal(res.categories, expected)\n\n # Test for dicts with no items from old categories\n cat = Categorical(["a", "b", "c", "d"])\n res = cat.rename_categories({"f": 1, "g": 3})\n\n expected = Index(["a", "b", "c", "d"])\n tm.assert_index_equal(res.categories, expected)\n\n def test_reorder_categories(self):\n cat = Categorical(["a", "b", "c", "a"], ordered=True)\n old = cat.copy()\n new = Categorical(\n ["a", "b", "c", "a"], categories=["c", "b", "a"], ordered=True\n )\n\n res = cat.reorder_categories(["c", "b", "a"])\n # cat must be the same as before\n tm.assert_categorical_equal(cat, old)\n # only res is changed\n tm.assert_categorical_equal(res, new)\n\n @pytest.mark.parametrize(\n "new_categories",\n [\n ["a"], # not all "old" included in "new"\n ["a", "b", "d"], # still not all "old" in "new"\n ["a", "b", "c", "d"], # all "old" included in "new", but too long\n ],\n )\n def test_reorder_categories_raises(self, new_categories):\n cat = Categorical(["a", "b", "c", "a"], ordered=True)\n msg = "items in new_categories are not the same as in old categories"\n with pytest.raises(ValueError, match=msg):\n cat.reorder_categories(new_categories)\n\n def test_add_categories(self):\n cat = Categorical(["a", "b", "c", "a"], ordered=True)\n old = cat.copy()\n new = Categorical(\n ["a", "b", "c", "a"], categories=["a", "b", "c", "d"], ordered=True\n )\n\n res = cat.add_categories("d")\n tm.assert_categorical_equal(cat, old)\n tm.assert_categorical_equal(res, new)\n\n res = cat.add_categories(["d"])\n tm.assert_categorical_equal(cat, old)\n tm.assert_categorical_equal(res, new)\n\n # GH 9927\n cat = Categorical(list("abc"), ordered=True)\n expected = Categorical(list("abc"), categories=list("abcde"), ordered=True)\n # test with Series, np.array, index, list\n res = cat.add_categories(Series(["d", "e"]))\n tm.assert_categorical_equal(res, expected)\n res = cat.add_categories(np.array(["d", "e"]))\n tm.assert_categorical_equal(res, expected)\n res = cat.add_categories(Index(["d", "e"]))\n tm.assert_categorical_equal(res, expected)\n res = cat.add_categories(["d", "e"])\n tm.assert_categorical_equal(res, expected)\n\n def test_add_categories_existing_raises(self):\n # new is in old categories\n cat = Categorical(["a", "b", "c", "d"], ordered=True)\n msg = re.escape("new categories must not include old categories: {'d'}")\n with pytest.raises(ValueError, match=msg):\n cat.add_categories(["d"])\n\n def test_add_categories_losing_dtype_information(self):\n # GH#48812\n cat = Categorical(Series([1, 2], dtype="Int64"))\n ser = Series([4], dtype="Int64")\n result = cat.add_categories(ser)\n expected = Categorical(\n Series([1, 2], dtype="Int64"), categories=Series([1, 2, 4], dtype="Int64")\n )\n tm.assert_categorical_equal(result, expected)\n\n cat = Categorical(Series(["a", "b", "a"], dtype=StringDtype()))\n ser = Series(["d"], dtype=StringDtype())\n result = cat.add_categories(ser)\n expected = Categorical(\n Series(["a", "b", "a"], dtype=StringDtype()),\n categories=Series(["a", "b", "d"], dtype=StringDtype()),\n )\n tm.assert_categorical_equal(result, expected)\n\n def test_set_categories(self):\n cat = Categorical(["a", "b", "c", "a"], ordered=True)\n exp_categories = Index(["c", "b", "a"])\n exp_values = np.array(["a", "b", "c", "a"], dtype=np.object_)\n\n cat = cat.set_categories(["c", "b", "a"])\n res = cat.set_categories(["a", "b", "c"])\n # cat must be the same as before\n tm.assert_index_equal(cat.categories, exp_categories)\n tm.assert_numpy_array_equal(cat.__array__(), exp_values)\n # only res is changed\n exp_categories_back = Index(["a", "b", "c"])\n tm.assert_index_equal(res.categories, exp_categories_back)\n tm.assert_numpy_array_equal(res.__array__(), exp_values)\n\n # not all "old" included in "new" -> all not included ones are now\n # np.nan\n cat = Categorical(["a", "b", "c", "a"], ordered=True)\n res = cat.set_categories(["a"])\n tm.assert_numpy_array_equal(res.codes, np.array([0, -1, -1, 0], dtype=np.int8))\n\n # still not all "old" in "new"\n res = cat.set_categories(["a", "b", "d"])\n tm.assert_numpy_array_equal(res.codes, np.array([0, 1, -1, 0], dtype=np.int8))\n tm.assert_index_equal(res.categories, Index(["a", "b", "d"]))\n\n # all "old" included in "new"\n cat = cat.set_categories(["a", "b", "c", "d"])\n exp_categories = Index(["a", "b", "c", "d"])\n tm.assert_index_equal(cat.categories, exp_categories)\n\n # internals...\n c = Categorical([1, 2, 3, 4, 1], categories=[1, 2, 3, 4], ordered=True)\n tm.assert_numpy_array_equal(c._codes, np.array([0, 1, 2, 3, 0], dtype=np.int8))\n tm.assert_index_equal(c.categories, Index([1, 2, 3, 4]))\n\n exp = np.array([1, 2, 3, 4, 1], dtype=np.int64)\n tm.assert_numpy_array_equal(np.asarray(c), exp)\n\n # all "pointers" to '4' must be changed from 3 to 0,...\n c = c.set_categories([4, 3, 2, 1])\n\n # positions are changed\n tm.assert_numpy_array_equal(c._codes, np.array([3, 2, 1, 0, 3], dtype=np.int8))\n\n # categories are now in new order\n tm.assert_index_equal(c.categories, Index([4, 3, 2, 1]))\n\n # output is the same\n exp = np.array([1, 2, 3, 4, 1], dtype=np.int64)\n tm.assert_numpy_array_equal(np.asarray(c), exp)\n assert c.min() == 4\n assert c.max() == 1\n\n # set_categories should set the ordering if specified\n c2 = c.set_categories([4, 3, 2, 1], ordered=False)\n assert not c2.ordered\n\n tm.assert_numpy_array_equal(np.asarray(c), np.asarray(c2))\n\n # set_categories should pass thru the ordering\n c2 = c.set_ordered(False).set_categories([4, 3, 2, 1])\n assert not c2.ordered\n\n tm.assert_numpy_array_equal(np.asarray(c), np.asarray(c2))\n\n @pytest.mark.parametrize(\n "values, categories, new_categories",\n [\n # No NaNs, same cats, same order\n (["a", "b", "a"], ["a", "b"], ["a", "b"]),\n # No NaNs, same cats, different order\n (["a", "b", "a"], ["a", "b"], ["b", "a"]),\n # Same, unsorted\n (["b", "a", "a"], ["a", "b"], ["a", "b"]),\n # No NaNs, same cats, different order\n (["b", "a", "a"], ["a", "b"], ["b", "a"]),\n # NaNs\n (["a", "b", "c"], ["a", "b"], ["a", "b"]),\n (["a", "b", "c"], ["a", "b"], ["b", "a"]),\n (["b", "a", "c"], ["a", "b"], ["a", "b"]),\n (["b", "a", "c"], ["a", "b"], ["a", "b"]),\n # Introduce NaNs\n (["a", "b", "c"], ["a", "b"], ["a"]),\n (["a", "b", "c"], ["a", "b"], ["b"]),\n (["b", "a", "c"], ["a", "b"], ["a"]),\n (["b", "a", "c"], ["a", "b"], ["a"]),\n # No overlap\n (["a", "b", "c"], ["a", "b"], ["d", "e"]),\n ],\n )\n @pytest.mark.parametrize("ordered", [True, False])\n def test_set_categories_many(self, values, categories, new_categories, ordered):\n c = Categorical(values, categories)\n expected = Categorical(values, new_categories, ordered)\n result = c.set_categories(new_categories, ordered=ordered)\n tm.assert_categorical_equal(result, expected)\n\n def test_set_categories_rename_less(self):\n # GH 24675\n cat = Categorical(["A", "B"])\n result = cat.set_categories(["A"], rename=True)\n expected = Categorical(["A", np.nan])\n tm.assert_categorical_equal(result, expected)\n\n def test_set_categories_private(self):\n cat = Categorical(["a", "b", "c"], categories=["a", "b", "c", "d"])\n cat._set_categories(["a", "c", "d", "e"])\n expected = Categorical(["a", "c", "d"], categories=list("acde"))\n tm.assert_categorical_equal(cat, expected)\n\n # fastpath\n cat = Categorical(["a", "b", "c"], categories=["a", "b", "c", "d"])\n cat._set_categories(["a", "c", "d", "e"], fastpath=True)\n expected = Categorical(["a", "c", "d"], categories=list("acde"))\n tm.assert_categorical_equal(cat, expected)\n\n def test_remove_categories(self):\n cat = Categorical(["a", "b", "c", "a"], ordered=True)\n old = cat.copy()\n new = Categorical(["a", "b", np.nan, "a"], categories=["a", "b"], ordered=True)\n\n res = cat.remove_categories("c")\n tm.assert_categorical_equal(cat, old)\n tm.assert_categorical_equal(res, new)\n\n res = cat.remove_categories(["c"])\n tm.assert_categorical_equal(cat, old)\n tm.assert_categorical_equal(res, new)\n\n @pytest.mark.parametrize("removals", [["c"], ["c", np.nan], "c", ["c", "c"]])\n def test_remove_categories_raises(self, removals):\n cat = Categorical(["a", "b", "a"])\n message = re.escape("removals must all be in old categories: {'c'}")\n\n with pytest.raises(ValueError, match=message):\n cat.remove_categories(removals)\n\n def test_remove_unused_categories(self):\n c = Categorical(["a", "b", "c", "d", "a"], categories=["a", "b", "c", "d", "e"])\n exp_categories_all = Index(["a", "b", "c", "d", "e"])\n exp_categories_dropped = Index(["a", "b", "c", "d"])\n\n tm.assert_index_equal(c.categories, exp_categories_all)\n\n res = c.remove_unused_categories()\n tm.assert_index_equal(res.categories, exp_categories_dropped)\n tm.assert_index_equal(c.categories, exp_categories_all)\n\n # with NaN values (GH11599)\n c = Categorical(["a", "b", "c", np.nan], categories=["a", "b", "c", "d", "e"])\n res = c.remove_unused_categories()\n tm.assert_index_equal(res.categories, Index(np.array(["a", "b", "c"])))\n exp_codes = np.array([0, 1, 2, -1], dtype=np.int8)\n tm.assert_numpy_array_equal(res.codes, exp_codes)\n tm.assert_index_equal(c.categories, exp_categories_all)\n\n val = ["F", np.nan, "D", "B", "D", "F", np.nan]\n cat = Categorical(values=val, categories=list("ABCDEFG"))\n out = cat.remove_unused_categories()\n tm.assert_index_equal(out.categories, Index(["B", "D", "F"]))\n exp_codes = np.array([2, -1, 1, 0, 1, 2, -1], dtype=np.int8)\n tm.assert_numpy_array_equal(out.codes, exp_codes)\n assert out.tolist() == val\n\n alpha = list("abcdefghijklmnopqrstuvwxyz")\n val = np.random.default_rng(2).choice(alpha[::2], 10000).astype("object")\n val[np.random.default_rng(2).choice(len(val), 100)] = np.nan\n\n cat = Categorical(values=val, categories=alpha)\n out = cat.remove_unused_categories()\n assert out.tolist() == val.tolist()\n\n\nclass TestCategoricalAPIWithFactor:\n def test_describe(self):\n factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)\n # string type\n desc = factor.describe()\n assert factor.ordered\n exp_index = CategoricalIndex(\n ["a", "b", "c"], name="categories", ordered=factor.ordered\n )\n expected = DataFrame(\n {"counts": [3, 2, 3], "freqs": [3 / 8.0, 2 / 8.0, 3 / 8.0]}, index=exp_index\n )\n tm.assert_frame_equal(desc, expected)\n\n # check unused categories\n cat = factor.copy()\n cat = cat.set_categories(["a", "b", "c", "d"])\n desc = cat.describe()\n\n exp_index = CategoricalIndex(\n list("abcd"), ordered=factor.ordered, name="categories"\n )\n expected = DataFrame(\n {"counts": [3, 2, 3, 0], "freqs": [3 / 8.0, 2 / 8.0, 3 / 8.0, 0]},\n index=exp_index,\n )\n tm.assert_frame_equal(desc, expected)\n\n # check an integer one\n cat = Categorical([1, 2, 3, 1, 2, 3, 3, 2, 1, 1, 1])\n desc = cat.describe()\n exp_index = CategoricalIndex([1, 2, 3], ordered=cat.ordered, name="categories")\n expected = DataFrame(\n {"counts": [5, 3, 3], "freqs": [5 / 11.0, 3 / 11.0, 3 / 11.0]},\n index=exp_index,\n )\n tm.assert_frame_equal(desc, expected)\n\n # https://github.com/pandas-dev/pandas/issues/3678\n # describe should work with NaN\n cat = Categorical([np.nan, 1, 2, 2])\n desc = cat.describe()\n expected = DataFrame(\n {"counts": [1, 2, 1], "freqs": [1 / 4.0, 2 / 4.0, 1 / 4.0]},\n index=CategoricalIndex(\n [1, 2, np.nan], categories=[1, 2], name="categories"\n ),\n )\n tm.assert_frame_equal(desc, expected)\n\n\nclass TestPrivateCategoricalAPI:\n def test_codes_immutable(self):\n # Codes should be read only\n c = Categorical(["a", "b", "c", "a", np.nan])\n exp = np.array([0, 1, 2, 0, -1], dtype="int8")\n tm.assert_numpy_array_equal(c.codes, exp)\n\n # Assignments to codes should raise\n msg = (\n "property 'codes' of 'Categorical' object has no setter"\n if PY311\n else "can't set attribute"\n )\n with pytest.raises(AttributeError, match=msg):\n c.codes = np.array([0, 1, 2, 0, 1], dtype="int8")\n\n # changes in the codes array should raise\n codes = c.codes\n\n with pytest.raises(ValueError, match="assignment destination is read-only"):\n codes[4] = 1\n\n # But even after getting the codes, the original array should still be\n # writeable!\n c[4] = "a"\n exp = np.array([0, 1, 2, 0, 0], dtype="int8")\n tm.assert_numpy_array_equal(c.codes, exp)\n c._codes[4] = 2\n exp = np.array([0, 1, 2, 0, 2], dtype="int8")\n tm.assert_numpy_array_equal(c.codes, exp)\n\n @pytest.mark.parametrize(\n "codes, old, new, expected",\n [\n ([0, 1], ["a", "b"], ["a", "b"], [0, 1]),\n ([0, 1], ["b", "a"], ["b", "a"], [0, 1]),\n ([0, 1], ["a", "b"], ["b", "a"], [1, 0]),\n ([0, 1], ["b", "a"], ["a", "b"], [1, 0]),\n ([0, 1, 0, 1], ["a", "b"], ["a", "b", "c"], [0, 1, 0, 1]),\n ([0, 1, 2, 2], ["a", "b", "c"], ["a", "b"], [0, 1, -1, -1]),\n ([0, 1, -1], ["a", "b", "c"], ["a", "b", "c"], [0, 1, -1]),\n ([0, 1, -1], ["a", "b", "c"], ["b"], [-1, 0, -1]),\n ([0, 1, -1], ["a", "b", "c"], ["d"], [-1, -1, -1]),\n ([0, 1, -1], ["a", "b", "c"], [], [-1, -1, -1]),\n ([-1, -1], [], ["a", "b"], [-1, -1]),\n ([1, 0], ["b", "a"], ["a", "b"], [0, 1]),\n ],\n )\n def test_recode_to_categories(self, codes, old, new, expected):\n codes = np.asanyarray(codes, dtype=np.int8)\n expected = np.asanyarray(expected, dtype=np.int8)\n old = Index(old)\n new = Index(new)\n result = recode_for_categories(codes, old, new)\n tm.assert_numpy_array_equal(result, expected)\n\n def test_recode_to_categories_large(self):\n N = 1000\n codes = np.arange(N)\n old = Index(codes)\n expected = np.arange(N - 1, -1, -1, dtype=np.int16)\n new = Index(expected)\n result = recode_for_categories(codes, old, new)\n tm.assert_numpy_array_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\test_api.py
test_api.py
Python
19,879
0.95
0.063872
0.11639
node-utils
890
2025-02-24T11:01:46.364028
BSD-3-Clause
true
1cb88b6aba02f8cecc20667dd8e2ff35
import numpy as np\nimport pytest\n\nfrom pandas import (\n Categorical,\n CategoricalDtype,\n CategoricalIndex,\n DatetimeIndex,\n Interval,\n NaT,\n Period,\n Timestamp,\n array,\n to_datetime,\n)\nimport pandas._testing as tm\n\n\nclass TestAstype:\n @pytest.mark.parametrize("cls", [Categorical, CategoricalIndex])\n @pytest.mark.parametrize("values", [[1, np.nan], [Timestamp("2000"), NaT]])\n def test_astype_nan_to_int(self, cls, values):\n # GH#28406\n obj = cls(values)\n\n msg = "Cannot (cast|convert)"\n with pytest.raises((ValueError, TypeError), match=msg):\n obj.astype(int)\n\n @pytest.mark.parametrize(\n "expected",\n [\n array(["2019", "2020"], dtype="datetime64[ns, UTC]"),\n array([0, 0], dtype="timedelta64[ns]"),\n array([Period("2019"), Period("2020")], dtype="period[Y-DEC]"),\n array([Interval(0, 1), Interval(1, 2)], dtype="interval"),\n array([1, np.nan], dtype="Int64"),\n ],\n )\n def test_astype_category_to_extension_dtype(self, expected):\n # GH#28668\n result = expected.astype("category").astype(expected.dtype)\n\n tm.assert_extension_array_equal(result, expected)\n\n @pytest.mark.parametrize(\n "dtype, expected",\n [\n (\n "datetime64[ns]",\n np.array(["2015-01-01T00:00:00.000000000"], dtype="datetime64[ns]"),\n ),\n (\n "datetime64[ns, MET]",\n DatetimeIndex([Timestamp("2015-01-01 00:00:00+0100", tz="MET")]).array,\n ),\n ],\n )\n def test_astype_to_datetime64(self, dtype, expected):\n # GH#28448\n result = Categorical(["2015-01-01"]).astype(dtype)\n assert result == expected\n\n def test_astype_str_int_categories_to_nullable_int(self):\n # GH#39616\n dtype = CategoricalDtype([str(i) for i in range(5)])\n codes = np.random.default_rng(2).integers(5, size=20)\n arr = Categorical.from_codes(codes, dtype=dtype)\n\n res = arr.astype("Int64")\n expected = array(codes, dtype="Int64")\n tm.assert_extension_array_equal(res, expected)\n\n def test_astype_str_int_categories_to_nullable_float(self):\n # GH#39616\n dtype = CategoricalDtype([str(i / 2) for i in range(5)])\n codes = np.random.default_rng(2).integers(5, size=20)\n arr = Categorical.from_codes(codes, dtype=dtype)\n\n res = arr.astype("Float64")\n expected = array(codes, dtype="Float64") / 2\n tm.assert_extension_array_equal(res, expected)\n\n @pytest.mark.parametrize("ordered", [True, False])\n def test_astype(self, ordered):\n # string\n cat = Categorical(list("abbaaccc"), ordered=ordered)\n result = cat.astype(object)\n expected = np.array(cat)\n tm.assert_numpy_array_equal(result, expected)\n\n msg = r"Cannot cast object|str dtype to float64"\n with pytest.raises(ValueError, match=msg):\n cat.astype(float)\n\n # numeric\n cat = Categorical([0, 1, 2, 2, 1, 0, 1, 0, 2], ordered=ordered)\n result = cat.astype(object)\n expected = np.array(cat, dtype=object)\n tm.assert_numpy_array_equal(result, expected)\n\n result = cat.astype(int)\n expected = np.array(cat, dtype="int")\n tm.assert_numpy_array_equal(result, expected)\n\n result = cat.astype(float)\n expected = np.array(cat, dtype=float)\n tm.assert_numpy_array_equal(result, expected)\n\n @pytest.mark.parametrize("dtype_ordered", [True, False])\n @pytest.mark.parametrize("cat_ordered", [True, False])\n def test_astype_category(self, dtype_ordered, cat_ordered):\n # GH#10696/GH#18593\n data = list("abcaacbab")\n cat = Categorical(data, categories=list("bac"), ordered=cat_ordered)\n\n # standard categories\n dtype = CategoricalDtype(ordered=dtype_ordered)\n result = cat.astype(dtype)\n expected = Categorical(data, categories=cat.categories, ordered=dtype_ordered)\n tm.assert_categorical_equal(result, expected)\n\n # non-standard categories\n dtype = CategoricalDtype(list("adc"), dtype_ordered)\n result = cat.astype(dtype)\n expected = Categorical(data, dtype=dtype)\n tm.assert_categorical_equal(result, expected)\n\n if dtype_ordered is False:\n # dtype='category' can't specify ordered, so only test once\n result = cat.astype("category")\n expected = cat\n tm.assert_categorical_equal(result, expected)\n\n def test_astype_object_datetime_categories(self):\n # GH#40754\n cat = Categorical(to_datetime(["2021-03-27", NaT]))\n result = cat.astype(object)\n expected = np.array([Timestamp("2021-03-27 00:00:00"), NaT], dtype="object")\n tm.assert_numpy_array_equal(result, expected)\n\n def test_astype_object_timestamp_categories(self):\n # GH#18024\n cat = Categorical([Timestamp("2014-01-01")])\n result = cat.astype(object)\n expected = np.array([Timestamp("2014-01-01 00:00:00")], dtype="object")\n tm.assert_numpy_array_equal(result, expected)\n\n def test_astype_category_readonly_mask_values(self):\n # GH#53658\n arr = array([0, 1, 2], dtype="Int64")\n arr._mask.flags["WRITEABLE"] = False\n result = arr.astype("category")\n expected = array([0, 1, 2], dtype="Int64").astype("category")\n tm.assert_extension_array_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\test_astype.py
test_astype.py
Python
5,543
0.95
0.090323
0.106061
vue-tools
138
2024-10-17T13:43:47.640708
GPL-3.0
true
f3b767590aacc7319f069547862e3626
from datetime import (\n date,\n datetime,\n)\n\nimport numpy as np\nimport pytest\n\nfrom pandas._config import using_string_dtype\n\nfrom pandas.compat import HAS_PYARROW\n\nfrom pandas.core.dtypes.common import (\n is_float_dtype,\n is_integer_dtype,\n)\nfrom pandas.core.dtypes.dtypes import CategoricalDtype\n\nimport pandas as pd\nfrom pandas import (\n Categorical,\n CategoricalIndex,\n DatetimeIndex,\n Index,\n Interval,\n IntervalIndex,\n MultiIndex,\n NaT,\n Series,\n Timestamp,\n date_range,\n period_range,\n timedelta_range,\n)\nimport pandas._testing as tm\n\n\nclass TestCategoricalConstructors:\n def test_fastpath_deprecated(self):\n codes = np.array([1, 2, 3])\n dtype = CategoricalDtype(categories=["a", "b", "c", "d"], ordered=False)\n msg = "The 'fastpath' keyword in Categorical is deprecated"\n with tm.assert_produces_warning(DeprecationWarning, match=msg):\n Categorical(codes, dtype=dtype, fastpath=True)\n\n def test_categorical_from_cat_and_dtype_str_preserve_ordered(self):\n # GH#49309 we should preserve orderedness in `res`\n cat = Categorical([3, 1], categories=[3, 2, 1], ordered=True)\n\n res = Categorical(cat, dtype="category")\n assert res.dtype.ordered\n\n def test_categorical_disallows_scalar(self):\n # GH#38433\n with pytest.raises(TypeError, match="Categorical input must be list-like"):\n Categorical("A", categories=["A", "B"])\n\n def test_categorical_1d_only(self):\n # ndim > 1\n msg = "> 1 ndim Categorical are not supported at this time"\n with pytest.raises(NotImplementedError, match=msg):\n Categorical(np.array([list("abcd")]))\n\n def test_validate_ordered(self):\n # see gh-14058\n exp_msg = "'ordered' must either be 'True' or 'False'"\n exp_err = TypeError\n\n # This should be a boolean.\n ordered = np.array([0, 1, 2])\n\n with pytest.raises(exp_err, match=exp_msg):\n Categorical([1, 2, 3], ordered=ordered)\n\n with pytest.raises(exp_err, match=exp_msg):\n Categorical.from_codes(\n [0, 0, 1], categories=["a", "b", "c"], ordered=ordered\n )\n\n def test_constructor_empty(self):\n # GH 17248\n c = Categorical([])\n expected = Index([])\n tm.assert_index_equal(c.categories, expected)\n\n c = Categorical([], categories=[1, 2, 3])\n expected = Index([1, 2, 3], dtype=np.int64)\n tm.assert_index_equal(c.categories, expected)\n\n def test_constructor_empty_boolean(self):\n # see gh-22702\n cat = Categorical([], categories=[True, False])\n categories = sorted(cat.categories.tolist())\n assert categories == [False, True]\n\n def test_constructor_tuples(self):\n values = np.array([(1,), (1, 2), (1,), (1, 2)], dtype=object)\n result = Categorical(values)\n expected = Index([(1,), (1, 2)], tupleize_cols=False)\n tm.assert_index_equal(result.categories, expected)\n assert result.ordered is False\n\n def test_constructor_tuples_datetimes(self):\n # numpy will auto reshape when all of the tuples are the\n # same len, so add an extra one with 2 items and slice it off\n values = np.array(\n [\n (Timestamp("2010-01-01"),),\n (Timestamp("2010-01-02"),),\n (Timestamp("2010-01-01"),),\n (Timestamp("2010-01-02"),),\n ("a", "b"),\n ],\n dtype=object,\n )[:-1]\n result = Categorical(values)\n expected = Index(\n [(Timestamp("2010-01-01"),), (Timestamp("2010-01-02"),)],\n tupleize_cols=False,\n )\n tm.assert_index_equal(result.categories, expected)\n\n def test_constructor_unsortable(self):\n # it works!\n arr = np.array([1, 2, 3, datetime.now()], dtype="O")\n factor = Categorical(arr, ordered=False)\n assert not factor.ordered\n\n # this however will raise as cannot be sorted\n msg = (\n "'values' is not ordered, please explicitly specify the "\n "categories order by passing in a categories argument."\n )\n with pytest.raises(TypeError, match=msg):\n Categorical(arr, ordered=True)\n\n def test_constructor_interval(self):\n result = Categorical(\n [Interval(1, 2), Interval(2, 3), Interval(3, 6)], ordered=True\n )\n ii = IntervalIndex([Interval(1, 2), Interval(2, 3), Interval(3, 6)])\n exp = Categorical(ii, ordered=True)\n tm.assert_categorical_equal(result, exp)\n tm.assert_index_equal(result.categories, ii)\n\n def test_constructor(self):\n exp_arr = np.array(["a", "b", "c", "a", "b", "c"], dtype=np.object_)\n c1 = Categorical(exp_arr)\n tm.assert_numpy_array_equal(c1.__array__(), exp_arr)\n c2 = Categorical(exp_arr, categories=["a", "b", "c"])\n tm.assert_numpy_array_equal(c2.__array__(), exp_arr)\n c2 = Categorical(exp_arr, categories=["c", "b", "a"])\n tm.assert_numpy_array_equal(c2.__array__(), exp_arr)\n\n # categories must be unique\n msg = "Categorical categories must be unique"\n with pytest.raises(ValueError, match=msg):\n Categorical([1, 2], [1, 2, 2])\n\n with pytest.raises(ValueError, match=msg):\n Categorical(["a", "b"], ["a", "b", "b"])\n\n # The default should be unordered\n c1 = Categorical(["a", "b", "c", "a"])\n assert not c1.ordered\n\n # Categorical as input\n c1 = Categorical(["a", "b", "c", "a"])\n c2 = Categorical(c1)\n tm.assert_categorical_equal(c1, c2)\n\n c1 = Categorical(["a", "b", "c", "a"], categories=["a", "b", "c", "d"])\n c2 = Categorical(c1)\n tm.assert_categorical_equal(c1, c2)\n\n c1 = Categorical(["a", "b", "c", "a"], categories=["a", "c", "b"])\n c2 = Categorical(c1)\n tm.assert_categorical_equal(c1, c2)\n\n c1 = Categorical(["a", "b", "c", "a"], categories=["a", "c", "b"])\n c2 = Categorical(c1, categories=["a", "b", "c"])\n tm.assert_numpy_array_equal(c1.__array__(), c2.__array__())\n tm.assert_index_equal(c2.categories, Index(["a", "b", "c"]))\n\n # Series of dtype category\n c1 = Categorical(["a", "b", "c", "a"], categories=["a", "b", "c", "d"])\n c2 = Categorical(Series(c1))\n tm.assert_categorical_equal(c1, c2)\n\n c1 = Categorical(["a", "b", "c", "a"], categories=["a", "c", "b"])\n c2 = Categorical(Series(c1))\n tm.assert_categorical_equal(c1, c2)\n\n # Series\n c1 = Categorical(["a", "b", "c", "a"])\n c2 = Categorical(Series(["a", "b", "c", "a"]))\n tm.assert_categorical_equal(c1, c2)\n\n c1 = Categorical(["a", "b", "c", "a"], categories=["a", "b", "c", "d"])\n c2 = Categorical(Series(["a", "b", "c", "a"]), categories=["a", "b", "c", "d"])\n tm.assert_categorical_equal(c1, c2)\n\n # This should result in integer categories, not float!\n cat = Categorical([1, 2, 3, np.nan], categories=[1, 2, 3])\n assert is_integer_dtype(cat.categories)\n\n # https://github.com/pandas-dev/pandas/issues/3678\n cat = Categorical([np.nan, 1, 2, 3])\n assert is_integer_dtype(cat.categories)\n\n # this should result in floats\n cat = Categorical([np.nan, 1, 2.0, 3])\n assert is_float_dtype(cat.categories)\n\n cat = Categorical([np.nan, 1.0, 2.0, 3.0])\n assert is_float_dtype(cat.categories)\n\n # This doesn't work -> this would probably need some kind of "remember\n # the original type" feature to try to cast the array interface result\n # to...\n\n # vals = np.asarray(cat[cat.notna()])\n # assert is_integer_dtype(vals)\n\n # corner cases\n cat = Categorical([1])\n assert len(cat.categories) == 1\n assert cat.categories[0] == 1\n assert len(cat.codes) == 1\n assert cat.codes[0] == 0\n\n cat = Categorical(["a"])\n assert len(cat.categories) == 1\n assert cat.categories[0] == "a"\n assert len(cat.codes) == 1\n assert cat.codes[0] == 0\n\n # two arrays\n # - when the first is an integer dtype and the second is not\n # - when the resulting codes are all -1/NaN\n with tm.assert_produces_warning(None):\n Categorical([0, 1, 2, 0, 1, 2], categories=["a", "b", "c"])\n\n with tm.assert_produces_warning(None):\n Categorical([0, 1, 2, 0, 1, 2], categories=[3, 4, 5])\n\n # the next one are from the old docs\n with tm.assert_produces_warning(None):\n Categorical([0, 1, 2, 0, 1, 2], [1, 2, 3])\n cat = Categorical([1, 2], categories=[1, 2, 3])\n\n # this is a legitimate constructor\n with tm.assert_produces_warning(None):\n Categorical(np.array([], dtype="int64"), categories=[3, 2, 1], ordered=True)\n\n def test_constructor_with_existing_categories(self):\n # GH25318: constructing with pd.Series used to bogusly skip recoding\n # categories\n c0 = Categorical(["a", "b", "c", "a"])\n c1 = Categorical(["a", "b", "c", "a"], categories=["b", "c"])\n\n c2 = Categorical(c0, categories=c1.categories)\n tm.assert_categorical_equal(c1, c2)\n\n c3 = Categorical(Series(c0), categories=c1.categories)\n tm.assert_categorical_equal(c1, c3)\n\n def test_constructor_not_sequence(self):\n # https://github.com/pandas-dev/pandas/issues/16022\n msg = r"^Parameter 'categories' must be list-like, was"\n with pytest.raises(TypeError, match=msg):\n Categorical(["a", "b"], categories="a")\n\n def test_constructor_with_null(self):\n # Cannot have NaN in categories\n msg = "Categorical categories cannot be null"\n with pytest.raises(ValueError, match=msg):\n Categorical([np.nan, "a", "b", "c"], categories=[np.nan, "a", "b", "c"])\n\n with pytest.raises(ValueError, match=msg):\n Categorical([None, "a", "b", "c"], categories=[None, "a", "b", "c"])\n\n with pytest.raises(ValueError, match=msg):\n Categorical(\n DatetimeIndex(["nat", "20160101"]),\n categories=[NaT, Timestamp("20160101")],\n )\n\n def test_constructor_with_index(self):\n ci = CategoricalIndex(list("aabbca"), categories=list("cab"))\n tm.assert_categorical_equal(ci.values, Categorical(ci))\n\n ci = CategoricalIndex(list("aabbca"), categories=list("cab"))\n tm.assert_categorical_equal(\n ci.values, Categorical(ci.astype(object), categories=ci.categories)\n )\n\n def test_constructor_with_generator(self):\n # This was raising an Error in isna(single_val).any() because isna\n # returned a scalar for a generator\n\n exp = Categorical([0, 1, 2])\n cat = Categorical(x for x in [0, 1, 2])\n tm.assert_categorical_equal(cat, exp)\n cat = Categorical(range(3))\n tm.assert_categorical_equal(cat, exp)\n\n MultiIndex.from_product([range(5), ["a", "b", "c"]])\n\n # check that categories accept generators and sequences\n cat = Categorical([0, 1, 2], categories=(x for x in [0, 1, 2]))\n tm.assert_categorical_equal(cat, exp)\n cat = Categorical([0, 1, 2], categories=range(3))\n tm.assert_categorical_equal(cat, exp)\n\n def test_constructor_with_rangeindex(self):\n # RangeIndex is preserved in Categories\n rng = Index(range(3))\n\n cat = Categorical(rng)\n tm.assert_index_equal(cat.categories, rng, exact=True)\n\n cat = Categorical([1, 2, 0], categories=rng)\n tm.assert_index_equal(cat.categories, rng, exact=True)\n\n @pytest.mark.parametrize(\n "dtl",\n [\n date_range("1995-01-01 00:00:00", periods=5, freq="s"),\n date_range("1995-01-01 00:00:00", periods=5, freq="s", tz="US/Eastern"),\n timedelta_range("1 day", periods=5, freq="s"),\n ],\n )\n def test_constructor_with_datetimelike(self, dtl):\n # see gh-12077\n # constructor with a datetimelike and NaT\n\n s = Series(dtl)\n c = Categorical(s)\n\n expected = type(dtl)(s)\n expected._data.freq = None\n\n tm.assert_index_equal(c.categories, expected)\n tm.assert_numpy_array_equal(c.codes, np.arange(5, dtype="int8"))\n\n # with NaT\n s2 = s.copy()\n s2.iloc[-1] = NaT\n c = Categorical(s2)\n\n expected = type(dtl)(s2.dropna())\n expected._data.freq = None\n\n tm.assert_index_equal(c.categories, expected)\n\n exp = np.array([0, 1, 2, 3, -1], dtype=np.int8)\n tm.assert_numpy_array_equal(c.codes, exp)\n\n result = repr(c)\n assert "NaT" in result\n\n def test_constructor_from_index_series_datetimetz(self):\n idx = date_range("2015-01-01 10:00", freq="D", periods=3, tz="US/Eastern")\n idx = idx._with_freq(None) # freq not preserved in result.categories\n result = Categorical(idx)\n tm.assert_index_equal(result.categories, idx)\n\n result = Categorical(Series(idx))\n tm.assert_index_equal(result.categories, idx)\n\n def test_constructor_date_objects(self):\n # we dont cast date objects to timestamps, matching Index constructor\n v = date.today()\n\n cat = Categorical([v, v])\n assert cat.categories.dtype == object\n assert type(cat.categories[0]) is date\n\n def test_constructor_from_index_series_timedelta(self):\n idx = timedelta_range("1 days", freq="D", periods=3)\n idx = idx._with_freq(None) # freq not preserved in result.categories\n result = Categorical(idx)\n tm.assert_index_equal(result.categories, idx)\n\n result = Categorical(Series(idx))\n tm.assert_index_equal(result.categories, idx)\n\n def test_constructor_from_index_series_period(self):\n idx = period_range("2015-01-01", freq="D", periods=3)\n result = Categorical(idx)\n tm.assert_index_equal(result.categories, idx)\n\n result = Categorical(Series(idx))\n tm.assert_index_equal(result.categories, idx)\n\n @pytest.mark.parametrize(\n "values",\n [\n np.array([1.0, 1.2, 1.8, np.nan]),\n np.array([1, 2, 3], dtype="int64"),\n ["a", "b", "c", np.nan],\n [pd.Period("2014-01"), pd.Period("2014-02"), NaT],\n [Timestamp("2014-01-01"), Timestamp("2014-01-02"), NaT],\n [\n Timestamp("2014-01-01", tz="US/Eastern"),\n Timestamp("2014-01-02", tz="US/Eastern"),\n NaT,\n ],\n ],\n )\n def test_constructor_invariant(self, values):\n # GH 14190\n c = Categorical(values)\n c2 = Categorical(c)\n tm.assert_categorical_equal(c, c2)\n\n @pytest.mark.parametrize("ordered", [True, False])\n def test_constructor_with_dtype(self, ordered):\n categories = ["b", "a", "c"]\n dtype = CategoricalDtype(categories, ordered=ordered)\n result = Categorical(["a", "b", "a", "c"], dtype=dtype)\n expected = Categorical(\n ["a", "b", "a", "c"], categories=categories, ordered=ordered\n )\n tm.assert_categorical_equal(result, expected)\n assert result.ordered is ordered\n\n def test_constructor_dtype_and_others_raises(self):\n dtype = CategoricalDtype(["a", "b"], ordered=True)\n msg = "Cannot specify `categories` or `ordered` together with `dtype`."\n with pytest.raises(ValueError, match=msg):\n Categorical(["a", "b"], categories=["a", "b"], dtype=dtype)\n\n with pytest.raises(ValueError, match=msg):\n Categorical(["a", "b"], ordered=True, dtype=dtype)\n\n with pytest.raises(ValueError, match=msg):\n Categorical(["a", "b"], ordered=False, dtype=dtype)\n\n @pytest.mark.parametrize("categories", [None, ["a", "b"], ["a", "c"]])\n @pytest.mark.parametrize("ordered", [True, False])\n def test_constructor_str_category(self, categories, ordered):\n result = Categorical(\n ["a", "b"], categories=categories, ordered=ordered, dtype="category"\n )\n expected = Categorical(["a", "b"], categories=categories, ordered=ordered)\n tm.assert_categorical_equal(result, expected)\n\n def test_constructor_str_unknown(self):\n with pytest.raises(ValueError, match="Unknown dtype"):\n Categorical([1, 2], dtype="foo")\n\n @pytest.mark.xfail(\n using_string_dtype() and HAS_PYARROW, reason="Can't be NumPy strings"\n )\n def test_constructor_np_strs(self):\n # GH#31499 Hashtable.map_locations needs to work on np.str_ objects\n cat = Categorical(["1", "0", "1"], [np.str_("0"), np.str_("1")])\n assert all(isinstance(x, np.str_) for x in cat.categories)\n\n def test_constructor_from_categorical_with_dtype(self):\n dtype = CategoricalDtype(["a", "b", "c"], ordered=True)\n values = Categorical(["a", "b", "d"])\n result = Categorical(values, dtype=dtype)\n # We use dtype.categories, not values.categories\n expected = Categorical(\n ["a", "b", "d"], categories=["a", "b", "c"], ordered=True\n )\n tm.assert_categorical_equal(result, expected)\n\n def test_constructor_from_categorical_with_unknown_dtype(self):\n dtype = CategoricalDtype(None, ordered=True)\n values = Categorical(["a", "b", "d"])\n result = Categorical(values, dtype=dtype)\n # We use values.categories, not dtype.categories\n expected = Categorical(\n ["a", "b", "d"], categories=["a", "b", "d"], ordered=True\n )\n tm.assert_categorical_equal(result, expected)\n\n def test_constructor_from_categorical_string(self):\n values = Categorical(["a", "b", "d"])\n # use categories, ordered\n result = Categorical(\n values, categories=["a", "b", "c"], ordered=True, dtype="category"\n )\n expected = Categorical(\n ["a", "b", "d"], categories=["a", "b", "c"], ordered=True\n )\n tm.assert_categorical_equal(result, expected)\n\n # No string\n result = Categorical(values, categories=["a", "b", "c"], ordered=True)\n tm.assert_categorical_equal(result, expected)\n\n def test_constructor_with_categorical_categories(self):\n # GH17884\n expected = Categorical(["a", "b"], categories=["a", "b", "c"])\n\n result = Categorical(["a", "b"], categories=Categorical(["a", "b", "c"]))\n tm.assert_categorical_equal(result, expected)\n\n result = Categorical(["a", "b"], categories=CategoricalIndex(["a", "b", "c"]))\n tm.assert_categorical_equal(result, expected)\n\n @pytest.mark.parametrize("klass", [lambda x: np.array(x, dtype=object), list])\n def test_construction_with_null(self, klass, nulls_fixture):\n # https://github.com/pandas-dev/pandas/issues/31927\n values = klass(["a", nulls_fixture, "b"])\n result = Categorical(values)\n\n dtype = CategoricalDtype(["a", "b"])\n codes = [0, -1, 1]\n expected = Categorical.from_codes(codes=codes, dtype=dtype)\n\n tm.assert_categorical_equal(result, expected)\n\n @pytest.mark.parametrize("validate", [True, False])\n def test_from_codes_nullable_int_categories(self, any_numeric_ea_dtype, validate):\n # GH#39649\n cats = pd.array(range(5), dtype=any_numeric_ea_dtype)\n codes = np.random.default_rng(2).integers(5, size=3)\n dtype = CategoricalDtype(cats)\n arr = Categorical.from_codes(codes, dtype=dtype, validate=validate)\n assert arr.categories.dtype == cats.dtype\n tm.assert_index_equal(arr.categories, Index(cats))\n\n def test_from_codes_empty(self):\n cat = ["a", "b", "c"]\n result = Categorical.from_codes([], categories=cat)\n expected = Categorical([], categories=cat)\n\n tm.assert_categorical_equal(result, expected)\n\n @pytest.mark.parametrize("validate", [True, False])\n def test_from_codes_validate(self, validate):\n # GH53122\n dtype = CategoricalDtype(["a", "b"])\n if validate:\n with pytest.raises(ValueError, match="codes need to be between "):\n Categorical.from_codes([4, 5], dtype=dtype, validate=validate)\n else:\n # passes, though has incorrect codes, but that's the user responsibility\n Categorical.from_codes([4, 5], dtype=dtype, validate=validate)\n\n def test_from_codes_too_few_categories(self):\n dtype = CategoricalDtype(categories=[1, 2])\n msg = "codes need to be between "\n with pytest.raises(ValueError, match=msg):\n Categorical.from_codes([1, 2], categories=dtype.categories)\n with pytest.raises(ValueError, match=msg):\n Categorical.from_codes([1, 2], dtype=dtype)\n\n def test_from_codes_non_int_codes(self):\n dtype = CategoricalDtype(categories=[1, 2])\n msg = "codes need to be array-like integers"\n with pytest.raises(ValueError, match=msg):\n Categorical.from_codes(["a"], categories=dtype.categories)\n with pytest.raises(ValueError, match=msg):\n Categorical.from_codes(["a"], dtype=dtype)\n\n def test_from_codes_non_unique_categories(self):\n with pytest.raises(ValueError, match="Categorical categories must be unique"):\n Categorical.from_codes([0, 1, 2], categories=["a", "a", "b"])\n\n def test_from_codes_nan_cat_included(self):\n with pytest.raises(ValueError, match="Categorical categories cannot be null"):\n Categorical.from_codes([0, 1, 2], categories=["a", "b", np.nan])\n\n def test_from_codes_too_negative(self):\n dtype = CategoricalDtype(categories=["a", "b", "c"])\n msg = r"codes need to be between -1 and len\(categories\)-1"\n with pytest.raises(ValueError, match=msg):\n Categorical.from_codes([-2, 1, 2], categories=dtype.categories)\n with pytest.raises(ValueError, match=msg):\n Categorical.from_codes([-2, 1, 2], dtype=dtype)\n\n def test_from_codes(self):\n dtype = CategoricalDtype(categories=["a", "b", "c"])\n exp = Categorical(["a", "b", "c"], ordered=False)\n res = Categorical.from_codes([0, 1, 2], categories=dtype.categories)\n tm.assert_categorical_equal(exp, res)\n\n res = Categorical.from_codes([0, 1, 2], dtype=dtype)\n tm.assert_categorical_equal(exp, res)\n\n @pytest.mark.parametrize("klass", [Categorical, CategoricalIndex])\n def test_from_codes_with_categorical_categories(self, klass):\n # GH17884\n expected = Categorical(["a", "b"], categories=["a", "b", "c"])\n\n result = Categorical.from_codes([0, 1], categories=klass(["a", "b", "c"]))\n tm.assert_categorical_equal(result, expected)\n\n @pytest.mark.parametrize("klass", [Categorical, CategoricalIndex])\n def test_from_codes_with_non_unique_categorical_categories(self, klass):\n with pytest.raises(ValueError, match="Categorical categories must be unique"):\n Categorical.from_codes([0, 1], klass(["a", "b", "a"]))\n\n def test_from_codes_with_nan_code(self):\n # GH21767\n codes = [1, 2, np.nan]\n dtype = CategoricalDtype(categories=["a", "b", "c"])\n with pytest.raises(ValueError, match="codes need to be array-like integers"):\n Categorical.from_codes(codes, categories=dtype.categories)\n with pytest.raises(ValueError, match="codes need to be array-like integers"):\n Categorical.from_codes(codes, dtype=dtype)\n\n @pytest.mark.parametrize("codes", [[1.0, 2.0, 0], [1.1, 2.0, 0]])\n def test_from_codes_with_float(self, codes):\n # GH21767\n # float codes should raise even if values are equal to integers\n dtype = CategoricalDtype(categories=["a", "b", "c"])\n\n msg = "codes need to be array-like integers"\n with pytest.raises(ValueError, match=msg):\n Categorical.from_codes(codes, dtype.categories)\n with pytest.raises(ValueError, match=msg):\n Categorical.from_codes(codes, dtype=dtype)\n\n def test_from_codes_with_dtype_raises(self):\n msg = "Cannot specify"\n with pytest.raises(ValueError, match=msg):\n Categorical.from_codes(\n [0, 1], categories=["a", "b"], dtype=CategoricalDtype(["a", "b"])\n )\n\n with pytest.raises(ValueError, match=msg):\n Categorical.from_codes(\n [0, 1], ordered=True, dtype=CategoricalDtype(["a", "b"])\n )\n\n def test_from_codes_neither(self):\n msg = "Both were None"\n with pytest.raises(ValueError, match=msg):\n Categorical.from_codes([0, 1])\n\n def test_from_codes_with_nullable_int(self):\n codes = pd.array([0, 1], dtype="Int64")\n categories = ["a", "b"]\n\n result = Categorical.from_codes(codes, categories=categories)\n expected = Categorical.from_codes(codes.to_numpy(int), categories=categories)\n\n tm.assert_categorical_equal(result, expected)\n\n def test_from_codes_with_nullable_int_na_raises(self):\n codes = pd.array([0, None], dtype="Int64")\n categories = ["a", "b"]\n\n msg = "codes cannot contain NA values"\n with pytest.raises(ValueError, match=msg):\n Categorical.from_codes(codes, categories=categories)\n\n @pytest.mark.parametrize("dtype", [None, "category"])\n def test_from_inferred_categories(self, dtype):\n cats = ["a", "b"]\n codes = np.array([0, 0, 1, 1], dtype="i8")\n result = Categorical._from_inferred_categories(cats, codes, dtype)\n expected = Categorical.from_codes(codes, cats)\n tm.assert_categorical_equal(result, expected)\n\n @pytest.mark.parametrize("dtype", [None, "category"])\n def test_from_inferred_categories_sorts(self, dtype):\n cats = ["b", "a"]\n codes = np.array([0, 1, 1, 1], dtype="i8")\n result = Categorical._from_inferred_categories(cats, codes, dtype)\n expected = Categorical.from_codes([1, 0, 0, 0], ["a", "b"])\n tm.assert_categorical_equal(result, expected)\n\n def test_from_inferred_categories_dtype(self):\n cats = ["a", "b", "d"]\n codes = np.array([0, 1, 0, 2], dtype="i8")\n dtype = CategoricalDtype(["c", "b", "a"], ordered=True)\n result = Categorical._from_inferred_categories(cats, codes, dtype)\n expected = Categorical(\n ["a", "b", "a", "d"], categories=["c", "b", "a"], ordered=True\n )\n tm.assert_categorical_equal(result, expected)\n\n def test_from_inferred_categories_coerces(self):\n cats = ["1", "2", "bad"]\n codes = np.array([0, 0, 1, 2], dtype="i8")\n dtype = CategoricalDtype([1, 2])\n result = Categorical._from_inferred_categories(cats, codes, dtype)\n expected = Categorical([1, 1, 2, np.nan])\n tm.assert_categorical_equal(result, expected)\n\n @pytest.mark.parametrize("ordered", [None, True, False])\n def test_construction_with_ordered(self, ordered):\n # GH 9347, 9190\n cat = Categorical([0, 1, 2], ordered=ordered)\n assert cat.ordered == bool(ordered)\n\n def test_constructor_imaginary(self):\n values = [1, 2, 3 + 1j]\n c1 = Categorical(values)\n tm.assert_index_equal(c1.categories, Index(values))\n tm.assert_numpy_array_equal(np.array(c1), np.array(values))\n\n def test_constructor_string_and_tuples(self):\n # GH 21416\n c = Categorical(np.array(["c", ("a", "b"), ("b", "a"), "c"], dtype=object))\n expected_index = Index([("a", "b"), ("b", "a"), "c"])\n assert c.categories.equals(expected_index)\n\n def test_interval(self):\n idx = pd.interval_range(0, 10, periods=10)\n cat = Categorical(idx, categories=idx)\n expected_codes = np.arange(10, dtype="int8")\n tm.assert_numpy_array_equal(cat.codes, expected_codes)\n tm.assert_index_equal(cat.categories, idx)\n\n # infer categories\n cat = Categorical(idx)\n tm.assert_numpy_array_equal(cat.codes, expected_codes)\n tm.assert_index_equal(cat.categories, idx)\n\n # list values\n cat = Categorical(list(idx))\n tm.assert_numpy_array_equal(cat.codes, expected_codes)\n tm.assert_index_equal(cat.categories, idx)\n\n # list values, categories\n cat = Categorical(list(idx), categories=list(idx))\n tm.assert_numpy_array_equal(cat.codes, expected_codes)\n tm.assert_index_equal(cat.categories, idx)\n\n # shuffled\n values = idx.take([1, 2, 0])\n cat = Categorical(values, categories=idx)\n tm.assert_numpy_array_equal(cat.codes, np.array([1, 2, 0], dtype="int8"))\n tm.assert_index_equal(cat.categories, idx)\n\n # extra\n values = pd.interval_range(8, 11, periods=3)\n cat = Categorical(values, categories=idx)\n expected_codes = np.array([8, 9, -1], dtype="int8")\n tm.assert_numpy_array_equal(cat.codes, expected_codes)\n tm.assert_index_equal(cat.categories, idx)\n\n # overlapping\n idx = IntervalIndex([Interval(0, 2), Interval(0, 1)])\n cat = Categorical(idx, categories=idx)\n expected_codes = np.array([0, 1], dtype="int8")\n tm.assert_numpy_array_equal(cat.codes, expected_codes)\n tm.assert_index_equal(cat.categories, idx)\n\n def test_categorical_extension_array_nullable(self, nulls_fixture):\n # GH:\n arr = pd.arrays.StringArray._from_sequence(\n [nulls_fixture] * 2, dtype=pd.StringDtype()\n )\n result = Categorical(arr)\n assert arr.dtype == result.categories.dtype\n expected = Categorical(Series([pd.NA, pd.NA], dtype=arr.dtype))\n tm.assert_categorical_equal(result, expected)\n\n def test_from_sequence_copy(self):\n cat = Categorical(np.arange(5).repeat(2))\n result = Categorical._from_sequence(cat, dtype=cat.dtype, copy=False)\n\n # more generally, we'd be OK with a view\n assert result._codes is cat._codes\n\n result = Categorical._from_sequence(cat, dtype=cat.dtype, copy=True)\n\n assert not tm.shares_memory(result, cat)\n\n def test_constructor_datetime64_non_nano(self):\n categories = np.arange(10).view("M8[D]")\n values = categories[::2].copy()\n\n cat = Categorical(values, categories=categories)\n assert (cat == values).all()\n\n def test_constructor_preserves_freq(self):\n # GH33830 freq retention in categorical\n dti = date_range("2016-01-01", periods=5)\n\n expected = dti.freq\n\n cat = Categorical(dti)\n result = cat.categories.freq\n\n assert expected == result\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\test_constructors.py
test_constructors.py
Python
30,758
0.95
0.090216
0.106416
vue-tools
981
2024-01-05T18:38:41.797098
BSD-3-Clause
true
0c10e18da163a63548b91161449fd753
import numpy as np\nimport pytest\n\nfrom pandas.core.dtypes.dtypes import CategoricalDtype\n\nfrom pandas import (\n Categorical,\n CategoricalIndex,\n Index,\n IntervalIndex,\n Series,\n Timestamp,\n)\nimport pandas._testing as tm\n\n\nclass TestCategoricalDtypes:\n def test_categories_match_up_to_permutation(self):\n # test dtype comparisons between cats\n\n c1 = Categorical(list("aabca"), categories=list("abc"), ordered=False)\n c2 = Categorical(list("aabca"), categories=list("cab"), ordered=False)\n c3 = Categorical(list("aabca"), categories=list("cab"), ordered=True)\n assert c1._categories_match_up_to_permutation(c1)\n assert c2._categories_match_up_to_permutation(c2)\n assert c3._categories_match_up_to_permutation(c3)\n assert c1._categories_match_up_to_permutation(c2)\n assert not c1._categories_match_up_to_permutation(c3)\n assert not c1._categories_match_up_to_permutation(Index(list("aabca")))\n assert not c1._categories_match_up_to_permutation(c1.astype(object))\n assert c1._categories_match_up_to_permutation(CategoricalIndex(c1))\n assert c1._categories_match_up_to_permutation(\n CategoricalIndex(c1, categories=list("cab"))\n )\n assert not c1._categories_match_up_to_permutation(\n CategoricalIndex(c1, ordered=True)\n )\n\n # GH 16659\n s1 = Series(c1)\n s2 = Series(c2)\n s3 = Series(c3)\n assert c1._categories_match_up_to_permutation(s1)\n assert c2._categories_match_up_to_permutation(s2)\n assert c3._categories_match_up_to_permutation(s3)\n assert c1._categories_match_up_to_permutation(s2)\n assert not c1._categories_match_up_to_permutation(s3)\n assert not c1._categories_match_up_to_permutation(s1.astype(object))\n\n def test_set_dtype_same(self):\n c = Categorical(["a", "b", "c"])\n result = c._set_dtype(CategoricalDtype(["a", "b", "c"]))\n tm.assert_categorical_equal(result, c)\n\n def test_set_dtype_new_categories(self):\n c = Categorical(["a", "b", "c"])\n result = c._set_dtype(CategoricalDtype(list("abcd")))\n tm.assert_numpy_array_equal(result.codes, c.codes)\n tm.assert_index_equal(result.dtype.categories, Index(list("abcd")))\n\n @pytest.mark.parametrize(\n "values, categories, new_categories",\n [\n # No NaNs, same cats, same order\n (["a", "b", "a"], ["a", "b"], ["a", "b"]),\n # No NaNs, same cats, different order\n (["a", "b", "a"], ["a", "b"], ["b", "a"]),\n # Same, unsorted\n (["b", "a", "a"], ["a", "b"], ["a", "b"]),\n # No NaNs, same cats, different order\n (["b", "a", "a"], ["a", "b"], ["b", "a"]),\n # NaNs\n (["a", "b", "c"], ["a", "b"], ["a", "b"]),\n (["a", "b", "c"], ["a", "b"], ["b", "a"]),\n (["b", "a", "c"], ["a", "b"], ["a", "b"]),\n (["b", "a", "c"], ["a", "b"], ["a", "b"]),\n # Introduce NaNs\n (["a", "b", "c"], ["a", "b"], ["a"]),\n (["a", "b", "c"], ["a", "b"], ["b"]),\n (["b", "a", "c"], ["a", "b"], ["a"]),\n (["b", "a", "c"], ["a", "b"], ["a"]),\n # No overlap\n (["a", "b", "c"], ["a", "b"], ["d", "e"]),\n ],\n )\n @pytest.mark.parametrize("ordered", [True, False])\n def test_set_dtype_many(self, values, categories, new_categories, ordered):\n c = Categorical(values, categories)\n expected = Categorical(values, new_categories, ordered)\n result = c._set_dtype(expected.dtype)\n tm.assert_categorical_equal(result, expected)\n\n def test_set_dtype_no_overlap(self):\n c = Categorical(["a", "b", "c"], ["d", "e"])\n result = c._set_dtype(CategoricalDtype(["a", "b"]))\n expected = Categorical([None, None, None], categories=["a", "b"])\n tm.assert_categorical_equal(result, expected)\n\n def test_codes_dtypes(self):\n # GH 8453\n result = Categorical(["foo", "bar", "baz"])\n assert result.codes.dtype == "int8"\n\n result = Categorical([f"foo{i:05d}" for i in range(400)])\n assert result.codes.dtype == "int16"\n\n result = Categorical([f"foo{i:05d}" for i in range(40000)])\n assert result.codes.dtype == "int32"\n\n # adding cats\n result = Categorical(["foo", "bar", "baz"])\n assert result.codes.dtype == "int8"\n result = result.add_categories([f"foo{i:05d}" for i in range(400)])\n assert result.codes.dtype == "int16"\n\n # removing cats\n result = result.remove_categories([f"foo{i:05d}" for i in range(300)])\n assert result.codes.dtype == "int8"\n\n def test_iter_python_types(self):\n # GH-19909\n cat = Categorical([1, 2])\n assert isinstance(next(iter(cat)), int)\n assert isinstance(cat.tolist()[0], int)\n\n def test_iter_python_types_datetime(self):\n cat = Categorical([Timestamp("2017-01-01"), Timestamp("2017-01-02")])\n assert isinstance(next(iter(cat)), Timestamp)\n assert isinstance(cat.tolist()[0], Timestamp)\n\n def test_interval_index_category(self):\n # GH 38316\n index = IntervalIndex.from_breaks(np.arange(3, dtype="uint64"))\n\n result = CategoricalIndex(index).dtype.categories\n expected = IntervalIndex.from_arrays(\n [0, 1], [1, 2], dtype="interval[uint64, right]"\n )\n tm.assert_index_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\test_dtypes.py
test_dtypes.py
Python
5,523
0.95
0.100719
0.116667
python-kit
716
2024-04-22T08:04:21.331610
MIT
true
0dd7271a143be222afd56883ea094cc6
import math\n\nimport numpy as np\nimport pytest\n\nfrom pandas import (\n NA,\n Categorical,\n CategoricalIndex,\n Index,\n Interval,\n IntervalIndex,\n NaT,\n PeriodIndex,\n Series,\n Timedelta,\n Timestamp,\n)\nimport pandas._testing as tm\nimport pandas.core.common as com\n\n\nclass TestCategoricalIndexingWithFactor:\n def test_getitem(self):\n factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)\n assert factor[0] == "a"\n assert factor[-1] == "c"\n\n subf = factor[[0, 1, 2]]\n tm.assert_numpy_array_equal(subf._codes, np.array([0, 1, 1], dtype=np.int8))\n\n subf = factor[np.asarray(factor) == "c"]\n tm.assert_numpy_array_equal(subf._codes, np.array([2, 2, 2], dtype=np.int8))\n\n def test_setitem(self):\n factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)\n # int/positional\n c = factor.copy()\n c[0] = "b"\n assert c[0] == "b"\n c[-1] = "a"\n assert c[-1] == "a"\n\n # boolean\n c = factor.copy()\n indexer = np.zeros(len(c), dtype="bool")\n indexer[0] = True\n indexer[-1] = True\n c[indexer] = "c"\n expected = Categorical(["c", "b", "b", "a", "a", "c", "c", "c"], ordered=True)\n\n tm.assert_categorical_equal(c, expected)\n\n @pytest.mark.parametrize(\n "other",\n [Categorical(["b", "a"]), Categorical(["b", "a"], categories=["b", "a"])],\n )\n def test_setitem_same_but_unordered(self, other):\n # GH-24142\n target = Categorical(["a", "b"], categories=["a", "b"])\n mask = np.array([True, False])\n target[mask] = other[mask]\n expected = Categorical(["b", "b"], categories=["a", "b"])\n tm.assert_categorical_equal(target, expected)\n\n @pytest.mark.parametrize(\n "other",\n [\n Categorical(["b", "a"], categories=["b", "a", "c"]),\n Categorical(["b", "a"], categories=["a", "b", "c"]),\n Categorical(["a", "a"], categories=["a"]),\n Categorical(["b", "b"], categories=["b"]),\n ],\n )\n def test_setitem_different_unordered_raises(self, other):\n # GH-24142\n target = Categorical(["a", "b"], categories=["a", "b"])\n mask = np.array([True, False])\n msg = "Cannot set a Categorical with another, without identical categories"\n with pytest.raises(TypeError, match=msg):\n target[mask] = other[mask]\n\n @pytest.mark.parametrize(\n "other",\n [\n Categorical(["b", "a"]),\n Categorical(["b", "a"], categories=["b", "a"], ordered=True),\n Categorical(["b", "a"], categories=["a", "b", "c"], ordered=True),\n ],\n )\n def test_setitem_same_ordered_raises(self, other):\n # Gh-24142\n target = Categorical(["a", "b"], categories=["a", "b"], ordered=True)\n mask = np.array([True, False])\n msg = "Cannot set a Categorical with another, without identical categories"\n with pytest.raises(TypeError, match=msg):\n target[mask] = other[mask]\n\n def test_setitem_tuple(self):\n # GH#20439\n cat = Categorical([(0, 1), (0, 2), (0, 1)])\n\n # This should not raise\n cat[1] = cat[0]\n assert cat[1] == (0, 1)\n\n def test_setitem_listlike(self):\n # GH#9469\n # properly coerce the input indexers\n\n cat = Categorical(\n np.random.default_rng(2).integers(0, 5, size=150000).astype(np.int8)\n ).add_categories([-1000])\n indexer = np.array([100000]).astype(np.int64)\n cat[indexer] = -1000\n\n # we are asserting the code result here\n # which maps to the -1000 category\n result = cat.codes[np.array([100000]).astype(np.int64)]\n tm.assert_numpy_array_equal(result, np.array([5], dtype="int8"))\n\n\nclass TestCategoricalIndexing:\n def test_getitem_slice(self):\n cat = Categorical(["a", "b", "c", "d", "a", "b", "c"])\n sliced = cat[3]\n assert sliced == "d"\n\n sliced = cat[3:5]\n expected = Categorical(["d", "a"], categories=["a", "b", "c", "d"])\n tm.assert_categorical_equal(sliced, expected)\n\n def test_getitem_listlike(self):\n # GH 9469\n # properly coerce the input indexers\n\n c = Categorical(\n np.random.default_rng(2).integers(0, 5, size=150000).astype(np.int8)\n )\n result = c.codes[np.array([100000]).astype(np.int64)]\n expected = c[np.array([100000]).astype(np.int64)].codes\n tm.assert_numpy_array_equal(result, expected)\n\n def test_periodindex(self):\n idx1 = PeriodIndex(\n ["2014-01", "2014-01", "2014-02", "2014-02", "2014-03", "2014-03"],\n freq="M",\n )\n\n cat1 = Categorical(idx1)\n str(cat1)\n exp_arr = np.array([0, 0, 1, 1, 2, 2], dtype=np.int8)\n exp_idx = PeriodIndex(["2014-01", "2014-02", "2014-03"], freq="M")\n tm.assert_numpy_array_equal(cat1._codes, exp_arr)\n tm.assert_index_equal(cat1.categories, exp_idx)\n\n idx2 = PeriodIndex(\n ["2014-03", "2014-03", "2014-02", "2014-01", "2014-03", "2014-01"],\n freq="M",\n )\n cat2 = Categorical(idx2, ordered=True)\n str(cat2)\n exp_arr = np.array([2, 2, 1, 0, 2, 0], dtype=np.int8)\n exp_idx2 = PeriodIndex(["2014-01", "2014-02", "2014-03"], freq="M")\n tm.assert_numpy_array_equal(cat2._codes, exp_arr)\n tm.assert_index_equal(cat2.categories, exp_idx2)\n\n idx3 = PeriodIndex(\n [\n "2013-12",\n "2013-11",\n "2013-10",\n "2013-09",\n "2013-08",\n "2013-07",\n "2013-05",\n ],\n freq="M",\n )\n cat3 = Categorical(idx3, ordered=True)\n exp_arr = np.array([6, 5, 4, 3, 2, 1, 0], dtype=np.int8)\n exp_idx = PeriodIndex(\n [\n "2013-05",\n "2013-07",\n "2013-08",\n "2013-09",\n "2013-10",\n "2013-11",\n "2013-12",\n ],\n freq="M",\n )\n tm.assert_numpy_array_equal(cat3._codes, exp_arr)\n tm.assert_index_equal(cat3.categories, exp_idx)\n\n @pytest.mark.parametrize(\n "null_val",\n [None, np.nan, NaT, NA, math.nan, "NaT", "nat", "NAT", "nan", "NaN", "NAN"],\n )\n def test_periodindex_on_null_types(self, null_val):\n # GH 46673\n result = PeriodIndex(["2022-04-06", "2022-04-07", null_val], freq="D")\n expected = PeriodIndex(["2022-04-06", "2022-04-07", "NaT"], dtype="period[D]")\n assert result[2] is NaT\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize("new_categories", [[1, 2, 3, 4], [1, 2]])\n def test_categories_assignments_wrong_length_raises(self, new_categories):\n cat = Categorical(["a", "b", "c", "a"])\n msg = (\n "new categories need to have the same number of items "\n "as the old categories!"\n )\n with pytest.raises(ValueError, match=msg):\n cat.rename_categories(new_categories)\n\n # Combinations of sorted/unique:\n @pytest.mark.parametrize(\n "idx_values", [[1, 2, 3, 4], [1, 3, 2, 4], [1, 3, 3, 4], [1, 2, 2, 4]]\n )\n # Combinations of missing/unique\n @pytest.mark.parametrize("key_values", [[1, 2], [1, 5], [1, 1], [5, 5]])\n @pytest.mark.parametrize("key_class", [Categorical, CategoricalIndex])\n @pytest.mark.parametrize("dtype", [None, "category", "key"])\n def test_get_indexer_non_unique(self, idx_values, key_values, key_class, dtype):\n # GH 21448\n key = key_class(key_values, categories=range(1, 5))\n\n if dtype == "key":\n dtype = key.dtype\n\n # Test for flat index and CategoricalIndex with same/different cats:\n idx = Index(idx_values, dtype=dtype)\n expected, exp_miss = idx.get_indexer_non_unique(key_values)\n result, res_miss = idx.get_indexer_non_unique(key)\n\n tm.assert_numpy_array_equal(expected, result)\n tm.assert_numpy_array_equal(exp_miss, res_miss)\n\n exp_unique = idx.unique().get_indexer(key_values)\n res_unique = idx.unique().get_indexer(key)\n tm.assert_numpy_array_equal(res_unique, exp_unique)\n\n def test_where_unobserved_nan(self):\n ser = Series(Categorical(["a", "b"]))\n result = ser.where([True, False])\n expected = Series(Categorical(["a", None], categories=["a", "b"]))\n tm.assert_series_equal(result, expected)\n\n # all NA\n ser = Series(Categorical(["a", "b"]))\n result = ser.where([False, False])\n expected = Series(Categorical([None, None], categories=["a", "b"]))\n tm.assert_series_equal(result, expected)\n\n def test_where_unobserved_categories(self):\n ser = Series(Categorical(["a", "b", "c"], categories=["d", "c", "b", "a"]))\n result = ser.where([True, True, False], other="b")\n expected = Series(Categorical(["a", "b", "b"], categories=ser.cat.categories))\n tm.assert_series_equal(result, expected)\n\n def test_where_other_categorical(self):\n ser = Series(Categorical(["a", "b", "c"], categories=["d", "c", "b", "a"]))\n other = Categorical(["b", "c", "a"], categories=["a", "c", "b", "d"])\n result = ser.where([True, False, True], other)\n expected = Series(Categorical(["a", "c", "c"], dtype=ser.dtype))\n tm.assert_series_equal(result, expected)\n\n def test_where_new_category_raises(self):\n ser = Series(Categorical(["a", "b", "c"]))\n msg = "Cannot setitem on a Categorical with a new category"\n with pytest.raises(TypeError, match=msg):\n ser.where([True, False, True], "d")\n\n def test_where_ordered_differs_rasies(self):\n ser = Series(\n Categorical(["a", "b", "c"], categories=["d", "c", "b", "a"], ordered=True)\n )\n other = Categorical(\n ["b", "c", "a"], categories=["a", "c", "b", "d"], ordered=True\n )\n with pytest.raises(TypeError, match="without identical categories"):\n ser.where([True, False, True], other)\n\n\nclass TestContains:\n def test_contains(self):\n # GH#21508\n cat = Categorical(list("aabbca"), categories=list("cab"))\n\n assert "b" in cat\n assert "z" not in cat\n assert np.nan not in cat\n with pytest.raises(TypeError, match="unhashable type: 'list'"):\n assert [1] in cat\n\n # assert codes NOT in index\n assert 0 not in cat\n assert 1 not in cat\n\n cat = Categorical(list("aabbca") + [np.nan], categories=list("cab"))\n assert np.nan in cat\n\n @pytest.mark.parametrize(\n "item, expected",\n [\n (Interval(0, 1), True),\n (1.5, True),\n (Interval(0.5, 1.5), False),\n ("a", False),\n (Timestamp(1), False),\n (Timedelta(1), False),\n ],\n ids=str,\n )\n def test_contains_interval(self, item, expected):\n # GH#23705\n cat = Categorical(IntervalIndex.from_breaks(range(3)))\n result = item in cat\n assert result is expected\n\n def test_contains_list(self):\n # GH#21729\n cat = Categorical([1, 2, 3])\n\n assert "a" not in cat\n\n with pytest.raises(TypeError, match="unhashable type"):\n ["a"] in cat\n\n with pytest.raises(TypeError, match="unhashable type"):\n ["a", "b"] in cat\n\n\n@pytest.mark.parametrize("index", [True, False])\ndef test_mask_with_boolean(index):\n ser = Series(range(3))\n idx = Categorical([True, False, True])\n if index:\n idx = CategoricalIndex(idx)\n\n assert com.is_bool_indexer(idx)\n result = ser[idx]\n expected = ser[idx.astype("object")]\n tm.assert_series_equal(result, expected)\n\n\n@pytest.mark.parametrize("index", [True, False])\ndef test_mask_with_boolean_na_treated_as_false(index):\n # https://github.com/pandas-dev/pandas/issues/31503\n ser = Series(range(3))\n idx = Categorical([True, False, None])\n if index:\n idx = CategoricalIndex(idx)\n\n result = ser[idx]\n expected = ser[idx.fillna(False)]\n\n tm.assert_series_equal(result, expected)\n\n\n@pytest.fixture\ndef non_coercible_categorical(monkeypatch):\n """\n Monkeypatch Categorical.__array__ to ensure no implicit conversion.\n\n Raises\n ------\n ValueError\n When Categorical.__array__ is called.\n """\n\n # TODO(Categorical): identify other places where this may be\n # useful and move to a conftest.py\n def array(self, dtype=None):\n raise ValueError("I cannot be converted.")\n\n with monkeypatch.context() as m:\n m.setattr(Categorical, "__array__", array)\n yield\n\n\ndef test_series_at():\n arr = Categorical(["a", "b", "c"])\n ser = Series(arr)\n result = ser.at[0]\n assert result == "a"\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\test_indexing.py
test_indexing.py
Python
12,972
0.95
0.085052
0.08
awesome-app
435
2023-08-27T08:11:12.662883
GPL-3.0
true
e4ec9e20cd21e5e6f20520b2377c319a
import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n Categorical,\n Index,\n Series,\n)\nimport pandas._testing as tm\n\n\n@pytest.fixture(params=[None, "ignore"])\ndef na_action(request):\n return request.param\n\n\n@pytest.mark.parametrize(\n "data, categories",\n [\n (list("abcbca"), list("cab")),\n (pd.interval_range(0, 3).repeat(3), pd.interval_range(0, 3)),\n ],\n ids=["string", "interval"],\n)\ndef test_map_str(data, categories, ordered, na_action):\n # GH 31202 - override base class since we want to maintain categorical/ordered\n cat = Categorical(data, categories=categories, ordered=ordered)\n result = cat.map(str, na_action=na_action)\n expected = Categorical(\n map(str, data), categories=map(str, categories), ordered=ordered\n )\n tm.assert_categorical_equal(result, expected)\n\n\ndef test_map(na_action):\n cat = Categorical(list("ABABC"), categories=list("CBA"), ordered=True)\n result = cat.map(lambda x: x.lower(), na_action=na_action)\n exp = Categorical(list("ababc"), categories=list("cba"), ordered=True)\n tm.assert_categorical_equal(result, exp)\n\n cat = Categorical(list("ABABC"), categories=list("BAC"), ordered=False)\n result = cat.map(lambda x: x.lower(), na_action=na_action)\n exp = Categorical(list("ababc"), categories=list("bac"), ordered=False)\n tm.assert_categorical_equal(result, exp)\n\n # GH 12766: Return an index not an array\n result = cat.map(lambda x: 1, na_action=na_action)\n exp = Index(np.array([1] * 5, dtype=np.int64))\n tm.assert_index_equal(result, exp)\n\n # change categories dtype\n cat = Categorical(list("ABABC"), categories=list("BAC"), ordered=False)\n\n def f(x):\n return {"A": 10, "B": 20, "C": 30}.get(x)\n\n result = cat.map(f, na_action=na_action)\n exp = Categorical([10, 20, 10, 20, 30], categories=[20, 10, 30], ordered=False)\n tm.assert_categorical_equal(result, exp)\n\n mapper = Series([10, 20, 30], index=["A", "B", "C"])\n result = cat.map(mapper, na_action=na_action)\n tm.assert_categorical_equal(result, exp)\n\n result = cat.map({"A": 10, "B": 20, "C": 30}, na_action=na_action)\n tm.assert_categorical_equal(result, exp)\n\n\n@pytest.mark.parametrize(\n ("data", "f", "expected"),\n (\n ([1, 1, np.nan], pd.isna, Index([False, False, True])),\n ([1, 2, np.nan], pd.isna, Index([False, False, True])),\n ([1, 1, np.nan], {1: False}, Categorical([False, False, np.nan])),\n ([1, 2, np.nan], {1: False, 2: False}, Index([False, False, np.nan])),\n (\n [1, 1, np.nan],\n Series([False, False]),\n Categorical([False, False, np.nan]),\n ),\n (\n [1, 2, np.nan],\n Series([False] * 3),\n Index([False, False, np.nan]),\n ),\n ),\n)\ndef test_map_with_nan_none(data, f, expected): # GH 24241\n values = Categorical(data)\n result = values.map(f, na_action=None)\n if isinstance(expected, Categorical):\n tm.assert_categorical_equal(result, expected)\n else:\n tm.assert_index_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n ("data", "f", "expected"),\n (\n ([1, 1, np.nan], pd.isna, Categorical([False, False, np.nan])),\n ([1, 2, np.nan], pd.isna, Index([False, False, np.nan])),\n ([1, 1, np.nan], {1: False}, Categorical([False, False, np.nan])),\n ([1, 2, np.nan], {1: False, 2: False}, Index([False, False, np.nan])),\n (\n [1, 1, np.nan],\n Series([False, False]),\n Categorical([False, False, np.nan]),\n ),\n (\n [1, 2, np.nan],\n Series([False, False, False]),\n Index([False, False, np.nan]),\n ),\n ),\n)\ndef test_map_with_nan_ignore(data, f, expected): # GH 24241\n values = Categorical(data)\n result = values.map(f, na_action="ignore")\n if data[1] == 1:\n tm.assert_categorical_equal(result, expected)\n else:\n tm.assert_index_equal(result, expected)\n\n\ndef test_map_with_dict_or_series(na_action):\n orig_values = ["a", "B", 1, "a"]\n new_values = ["one", 2, 3.0, "one"]\n cat = Categorical(orig_values)\n\n mapper = Series(new_values[:-1], index=orig_values[:-1])\n result = cat.map(mapper, na_action=na_action)\n\n # Order of categories in result can be different\n expected = Categorical(new_values, categories=[3.0, 2, "one"])\n tm.assert_categorical_equal(result, expected)\n\n mapper = dict(zip(orig_values[:-1], new_values[:-1]))\n result = cat.map(mapper, na_action=na_action)\n # Order of categories in result can be different\n tm.assert_categorical_equal(result, expected)\n\n\ndef test_map_na_action_no_default_deprecated():\n # GH51645\n cat = Categorical(["a", "b", "c"])\n msg = (\n "The default value of 'ignore' for the `na_action` parameter in "\n "pandas.Categorical.map is deprecated and will be "\n "changed to 'None' in a future version. Please set na_action to the "\n "desired value to avoid seeing this warning"\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n cat.map(lambda x: x)\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\test_map.py
test_map.py
Python
5,152
0.95
0.077922
0.046512
awesome-app
183
2025-06-28T23:53:31.882905
GPL-3.0
true
4873c2d7803bcbf4ba199eac9fb56fb8
import collections\n\nimport numpy as np\nimport pytest\n\nfrom pandas.core.dtypes.dtypes import CategoricalDtype\n\nimport pandas as pd\nfrom pandas import (\n Categorical,\n DataFrame,\n Index,\n Series,\n isna,\n)\nimport pandas._testing as tm\n\n\nclass TestCategoricalMissing:\n def test_isna(self):\n exp = np.array([False, False, True])\n cat = Categorical(["a", "b", np.nan])\n res = cat.isna()\n\n tm.assert_numpy_array_equal(res, exp)\n\n def test_na_flags_int_categories(self):\n # #1457\n\n categories = list(range(10))\n labels = np.random.default_rng(2).integers(0, 10, 20)\n labels[::5] = -1\n\n cat = Categorical(labels, categories)\n repr(cat)\n\n tm.assert_numpy_array_equal(isna(cat), labels == -1)\n\n def test_nan_handling(self):\n # Nans are represented as -1 in codes\n c = Categorical(["a", "b", np.nan, "a"])\n tm.assert_index_equal(c.categories, Index(["a", "b"]))\n tm.assert_numpy_array_equal(c._codes, np.array([0, 1, -1, 0], dtype=np.int8))\n c[1] = np.nan\n tm.assert_index_equal(c.categories, Index(["a", "b"]))\n tm.assert_numpy_array_equal(c._codes, np.array([0, -1, -1, 0], dtype=np.int8))\n\n # Adding nan to categories should make assigned nan point to the\n # category!\n c = Categorical(["a", "b", np.nan, "a"])\n tm.assert_index_equal(c.categories, Index(["a", "b"]))\n tm.assert_numpy_array_equal(c._codes, np.array([0, 1, -1, 0], dtype=np.int8))\n\n def test_set_dtype_nans(self):\n c = Categorical(["a", "b", np.nan])\n result = c._set_dtype(CategoricalDtype(["a", "c"]))\n tm.assert_numpy_array_equal(result.codes, np.array([0, -1, -1], dtype="int8"))\n\n def test_set_item_nan(self):\n cat = Categorical([1, 2, 3])\n cat[1] = np.nan\n\n exp = Categorical([1, np.nan, 3], categories=[1, 2, 3])\n tm.assert_categorical_equal(cat, exp)\n\n @pytest.mark.parametrize(\n "fillna_kwargs, msg",\n [\n (\n {"value": 1, "method": "ffill"},\n "Cannot specify both 'value' and 'method'.",\n ),\n ({}, "Must specify a fill 'value' or 'method'."),\n ({"method": "bad"}, "Invalid fill method. Expecting .* bad"),\n (\n {"value": Series([1, 2, 3, 4, "a"])},\n "Cannot setitem on a Categorical with a new category",\n ),\n ],\n )\n def test_fillna_raises(self, fillna_kwargs, msg):\n # https://github.com/pandas-dev/pandas/issues/19682\n # https://github.com/pandas-dev/pandas/issues/13628\n cat = Categorical([1, 2, 3, None, None])\n\n if len(fillna_kwargs) == 1 and "value" in fillna_kwargs:\n err = TypeError\n else:\n err = ValueError\n\n with pytest.raises(err, match=msg):\n cat.fillna(**fillna_kwargs)\n\n @pytest.mark.parametrize("named", [True, False])\n def test_fillna_iterable_category(self, named):\n # https://github.com/pandas-dev/pandas/issues/21097\n if named:\n Point = collections.namedtuple("Point", "x y")\n else:\n Point = lambda *args: args # tuple\n cat = Categorical(np.array([Point(0, 0), Point(0, 1), None], dtype=object))\n result = cat.fillna(Point(0, 0))\n expected = Categorical([Point(0, 0), Point(0, 1), Point(0, 0)])\n\n tm.assert_categorical_equal(result, expected)\n\n # Case where the Point is not among our categories; we want ValueError,\n # not NotImplementedError GH#41914\n cat = Categorical(np.array([Point(1, 0), Point(0, 1), None], dtype=object))\n msg = "Cannot setitem on a Categorical with a new category"\n with pytest.raises(TypeError, match=msg):\n cat.fillna(Point(0, 0))\n\n def test_fillna_array(self):\n # accept Categorical or ndarray value if it holds appropriate values\n cat = Categorical(["A", "B", "C", None, None])\n\n other = cat.fillna("C")\n result = cat.fillna(other)\n tm.assert_categorical_equal(result, other)\n assert isna(cat[-1]) # didn't modify original inplace\n\n other = np.array(["A", "B", "C", "B", "A"])\n result = cat.fillna(other)\n expected = Categorical(["A", "B", "C", "B", "A"], dtype=cat.dtype)\n tm.assert_categorical_equal(result, expected)\n assert isna(cat[-1]) # didn't modify original inplace\n\n @pytest.mark.parametrize(\n "values, expected",\n [\n ([1, 2, 3], np.array([False, False, False])),\n ([1, 2, np.nan], np.array([False, False, True])),\n ([1, 2, np.inf], np.array([False, False, True])),\n ([1, 2, pd.NA], np.array([False, False, True])),\n ],\n )\n def test_use_inf_as_na(self, values, expected):\n # https://github.com/pandas-dev/pandas/issues/33594\n msg = "use_inf_as_na option is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n with pd.option_context("mode.use_inf_as_na", True):\n cat = Categorical(values)\n result = cat.isna()\n tm.assert_numpy_array_equal(result, expected)\n\n result = Series(cat).isna()\n expected = Series(expected)\n tm.assert_series_equal(result, expected)\n\n result = DataFrame(cat).isna()\n expected = DataFrame(expected)\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "values, expected",\n [\n ([1, 2, 3], np.array([False, False, False])),\n ([1, 2, np.nan], np.array([False, False, True])),\n ([1, 2, np.inf], np.array([False, False, True])),\n ([1, 2, pd.NA], np.array([False, False, True])),\n ],\n )\n def test_use_inf_as_na_outside_context(self, values, expected):\n # https://github.com/pandas-dev/pandas/issues/33594\n # Using isna directly for Categorical will fail in general here\n cat = Categorical(values)\n\n msg = "use_inf_as_na option is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n with pd.option_context("mode.use_inf_as_na", True):\n result = isna(cat)\n tm.assert_numpy_array_equal(result, expected)\n\n result = isna(Series(cat))\n expected = Series(expected)\n tm.assert_series_equal(result, expected)\n\n result = isna(DataFrame(cat))\n expected = DataFrame(expected)\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "a1, a2, categories",\n [\n (["a", "b", "c"], [np.nan, "a", "b"], ["a", "b", "c"]),\n ([1, 2, 3], [np.nan, 1, 2], [1, 2, 3]),\n ],\n )\n def test_compare_categorical_with_missing(self, a1, a2, categories):\n # GH 28384\n cat_type = CategoricalDtype(categories)\n\n # !=\n result = Series(a1, dtype=cat_type) != Series(a2, dtype=cat_type)\n expected = Series(a1) != Series(a2)\n tm.assert_series_equal(result, expected)\n\n # ==\n result = Series(a1, dtype=cat_type) == Series(a2, dtype=cat_type)\n expected = Series(a1) == Series(a2)\n tm.assert_series_equal(result, expected)\n\n @pytest.mark.parametrize(\n "na_value, dtype",\n [\n (pd.NaT, "datetime64[ns]"),\n (None, "float64"),\n (np.nan, "float64"),\n (pd.NA, "float64"),\n ],\n )\n def test_categorical_only_missing_values_no_cast(self, na_value, dtype):\n # GH#44900\n result = Categorical([na_value, na_value])\n tm.assert_index_equal(result.categories, Index([], dtype=dtype))\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\test_missing.py
test_missing.py
Python
7,814
0.95
0.078704
0.093923
vue-tools
130
2025-04-01T19:01:14.409035
BSD-3-Clause
true
6abdf76912679002915b28f343019907
import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n Categorical,\n DataFrame,\n Series,\n Timestamp,\n date_range,\n)\nimport pandas._testing as tm\n\n\nclass TestCategoricalOpsWithFactor:\n def test_categories_none_comparisons(self):\n factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)\n tm.assert_categorical_equal(factor, factor)\n\n def test_comparisons(self):\n factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)\n result = factor[factor == "a"]\n expected = factor[np.asarray(factor) == "a"]\n tm.assert_categorical_equal(result, expected)\n\n result = factor[factor != "a"]\n expected = factor[np.asarray(factor) != "a"]\n tm.assert_categorical_equal(result, expected)\n\n result = factor[factor < "c"]\n expected = factor[np.asarray(factor) < "c"]\n tm.assert_categorical_equal(result, expected)\n\n result = factor[factor > "a"]\n expected = factor[np.asarray(factor) > "a"]\n tm.assert_categorical_equal(result, expected)\n\n result = factor[factor >= "b"]\n expected = factor[np.asarray(factor) >= "b"]\n tm.assert_categorical_equal(result, expected)\n\n result = factor[factor <= "b"]\n expected = factor[np.asarray(factor) <= "b"]\n tm.assert_categorical_equal(result, expected)\n\n n = len(factor)\n\n other = factor[np.random.default_rng(2).permutation(n)]\n result = factor == other\n expected = np.asarray(factor) == np.asarray(other)\n tm.assert_numpy_array_equal(result, expected)\n\n result = factor == "d"\n expected = np.zeros(len(factor), dtype=bool)\n tm.assert_numpy_array_equal(result, expected)\n\n # comparisons with categoricals\n cat_rev = Categorical(["a", "b", "c"], categories=["c", "b", "a"], ordered=True)\n cat_rev_base = Categorical(\n ["b", "b", "b"], categories=["c", "b", "a"], ordered=True\n )\n cat = Categorical(["a", "b", "c"], ordered=True)\n cat_base = Categorical(["b", "b", "b"], categories=cat.categories, ordered=True)\n\n # comparisons need to take categories ordering into account\n res_rev = cat_rev > cat_rev_base\n exp_rev = np.array([True, False, False])\n tm.assert_numpy_array_equal(res_rev, exp_rev)\n\n res_rev = cat_rev < cat_rev_base\n exp_rev = np.array([False, False, True])\n tm.assert_numpy_array_equal(res_rev, exp_rev)\n\n res = cat > cat_base\n exp = np.array([False, False, True])\n tm.assert_numpy_array_equal(res, exp)\n\n # Only categories with same categories can be compared\n msg = "Categoricals can only be compared if 'categories' are the same"\n with pytest.raises(TypeError, match=msg):\n cat > cat_rev\n\n cat_rev_base2 = Categorical(["b", "b", "b"], categories=["c", "b", "a", "d"])\n\n with pytest.raises(TypeError, match=msg):\n cat_rev > cat_rev_base2\n\n # Only categories with same ordering information can be compared\n cat_unordered = cat.set_ordered(False)\n assert not (cat > cat).any()\n\n with pytest.raises(TypeError, match=msg):\n cat > cat_unordered\n\n # comparison (in both directions) with Series will raise\n s = Series(["b", "b", "b"], dtype=object)\n msg = (\n "Cannot compare a Categorical for op __gt__ with type "\n r"<class 'numpy\.ndarray'>"\n )\n with pytest.raises(TypeError, match=msg):\n cat > s\n with pytest.raises(TypeError, match=msg):\n cat_rev > s\n with pytest.raises(TypeError, match=msg):\n s < cat\n with pytest.raises(TypeError, match=msg):\n s < cat_rev\n\n # comparison with numpy.array will raise in both direction, but only on\n # newer numpy versions\n a = np.array(["b", "b", "b"], dtype=object)\n with pytest.raises(TypeError, match=msg):\n cat > a\n with pytest.raises(TypeError, match=msg):\n cat_rev > a\n\n # Make sure that unequal comparison take the categories order in\n # account\n cat_rev = Categorical(list("abc"), categories=list("cba"), ordered=True)\n exp = np.array([True, False, False])\n res = cat_rev > "b"\n tm.assert_numpy_array_equal(res, exp)\n\n # check that zero-dim array gets unboxed\n res = cat_rev > np.array("b")\n tm.assert_numpy_array_equal(res, exp)\n\n\nclass TestCategoricalOps:\n @pytest.mark.parametrize(\n "categories",\n [["a", "b"], [0, 1], [Timestamp("2019"), Timestamp("2020")]],\n )\n def test_not_equal_with_na(self, categories):\n # https://github.com/pandas-dev/pandas/issues/32276\n c1 = Categorical.from_codes([-1, 0], categories=categories)\n c2 = Categorical.from_codes([0, 1], categories=categories)\n\n result = c1 != c2\n\n assert result.all()\n\n def test_compare_frame(self):\n # GH#24282 check that Categorical.__cmp__(DataFrame) defers to frame\n data = ["a", "b", 2, "a"]\n cat = Categorical(data)\n\n df = DataFrame(cat)\n\n result = cat == df.T\n expected = DataFrame([[True, True, True, True]])\n tm.assert_frame_equal(result, expected)\n\n result = cat[::-1] != df.T\n expected = DataFrame([[False, True, True, False]])\n tm.assert_frame_equal(result, expected)\n\n def test_compare_frame_raises(self, comparison_op):\n # alignment raises unless we transpose\n op = comparison_op\n cat = Categorical(["a", "b", 2, "a"])\n df = DataFrame(cat)\n msg = "Unable to coerce to Series, length must be 1: given 4"\n with pytest.raises(ValueError, match=msg):\n op(cat, df)\n\n def test_datetime_categorical_comparison(self):\n dt_cat = Categorical(date_range("2014-01-01", periods=3), ordered=True)\n tm.assert_numpy_array_equal(dt_cat > dt_cat[0], np.array([False, True, True]))\n tm.assert_numpy_array_equal(dt_cat[0] < dt_cat, np.array([False, True, True]))\n\n def test_reflected_comparison_with_scalars(self):\n # GH8658\n cat = Categorical([1, 2, 3], ordered=True)\n tm.assert_numpy_array_equal(cat > cat[0], np.array([False, True, True]))\n tm.assert_numpy_array_equal(cat[0] < cat, np.array([False, True, True]))\n\n def test_comparison_with_unknown_scalars(self):\n # https://github.com/pandas-dev/pandas/issues/9836#issuecomment-92123057\n # and following comparisons with scalars not in categories should raise\n # for unequal comps, but not for equal/not equal\n cat = Categorical([1, 2, 3], ordered=True)\n\n msg = "Invalid comparison between dtype=category and int"\n with pytest.raises(TypeError, match=msg):\n cat < 4\n with pytest.raises(TypeError, match=msg):\n cat > 4\n with pytest.raises(TypeError, match=msg):\n 4 < cat\n with pytest.raises(TypeError, match=msg):\n 4 > cat\n\n tm.assert_numpy_array_equal(cat == 4, np.array([False, False, False]))\n tm.assert_numpy_array_equal(cat != 4, np.array([True, True, True]))\n\n def test_comparison_with_tuple(self):\n cat = Categorical(np.array(["foo", (0, 1), 3, (0, 1)], dtype=object))\n\n result = cat == "foo"\n expected = np.array([True, False, False, False], dtype=bool)\n tm.assert_numpy_array_equal(result, expected)\n\n result = cat == (0, 1)\n expected = np.array([False, True, False, True], dtype=bool)\n tm.assert_numpy_array_equal(result, expected)\n\n result = cat != (0, 1)\n tm.assert_numpy_array_equal(result, ~expected)\n\n @pytest.mark.filterwarnings("ignore::RuntimeWarning")\n def test_comparison_of_ordered_categorical_with_nan_to_scalar(\n self, compare_operators_no_eq_ne\n ):\n # https://github.com/pandas-dev/pandas/issues/26504\n # BUG: fix ordered categorical comparison with missing values (#26504 )\n # and following comparisons with scalars in categories with missing\n # values should be evaluated as False\n\n cat = Categorical([1, 2, 3, None], categories=[1, 2, 3], ordered=True)\n scalar = 2\n expected = getattr(np.array(cat), compare_operators_no_eq_ne)(scalar)\n actual = getattr(cat, compare_operators_no_eq_ne)(scalar)\n tm.assert_numpy_array_equal(actual, expected)\n\n @pytest.mark.filterwarnings("ignore::RuntimeWarning")\n def test_comparison_of_ordered_categorical_with_nan_to_listlike(\n self, compare_operators_no_eq_ne\n ):\n # https://github.com/pandas-dev/pandas/issues/26504\n # and following comparisons of missing values in ordered Categorical\n # with listlike should be evaluated as False\n\n cat = Categorical([1, 2, 3, None], categories=[1, 2, 3], ordered=True)\n other = Categorical([2, 2, 2, 2], categories=[1, 2, 3], ordered=True)\n expected = getattr(np.array(cat), compare_operators_no_eq_ne)(2)\n actual = getattr(cat, compare_operators_no_eq_ne)(other)\n tm.assert_numpy_array_equal(actual, expected)\n\n @pytest.mark.parametrize(\n "data,reverse,base",\n [(list("abc"), list("cba"), list("bbb")), ([1, 2, 3], [3, 2, 1], [2, 2, 2])],\n )\n def test_comparisons(self, data, reverse, base):\n cat_rev = Series(Categorical(data, categories=reverse, ordered=True))\n cat_rev_base = Series(Categorical(base, categories=reverse, ordered=True))\n cat = Series(Categorical(data, ordered=True))\n cat_base = Series(\n Categorical(base, categories=cat.cat.categories, ordered=True)\n )\n s = Series(base, dtype=object if base == list("bbb") else None)\n a = np.array(base)\n\n # comparisons need to take categories ordering into account\n res_rev = cat_rev > cat_rev_base\n exp_rev = Series([True, False, False])\n tm.assert_series_equal(res_rev, exp_rev)\n\n res_rev = cat_rev < cat_rev_base\n exp_rev = Series([False, False, True])\n tm.assert_series_equal(res_rev, exp_rev)\n\n res = cat > cat_base\n exp = Series([False, False, True])\n tm.assert_series_equal(res, exp)\n\n scalar = base[1]\n res = cat > scalar\n exp = Series([False, False, True])\n exp2 = cat.values > scalar\n tm.assert_series_equal(res, exp)\n tm.assert_numpy_array_equal(res.values, exp2)\n res_rev = cat_rev > scalar\n exp_rev = Series([True, False, False])\n exp_rev2 = cat_rev.values > scalar\n tm.assert_series_equal(res_rev, exp_rev)\n tm.assert_numpy_array_equal(res_rev.values, exp_rev2)\n\n # Only categories with same categories can be compared\n msg = "Categoricals can only be compared if 'categories' are the same"\n with pytest.raises(TypeError, match=msg):\n cat > cat_rev\n\n # categorical cannot be compared to Series or numpy array, and also\n # not the other way around\n msg = (\n "Cannot compare a Categorical for op __gt__ with type "\n r"<class 'numpy\.ndarray'>"\n )\n with pytest.raises(TypeError, match=msg):\n cat > s\n with pytest.raises(TypeError, match=msg):\n cat_rev > s\n with pytest.raises(TypeError, match=msg):\n cat > a\n with pytest.raises(TypeError, match=msg):\n cat_rev > a\n\n with pytest.raises(TypeError, match=msg):\n s < cat\n with pytest.raises(TypeError, match=msg):\n s < cat_rev\n\n with pytest.raises(TypeError, match=msg):\n a < cat\n with pytest.raises(TypeError, match=msg):\n a < cat_rev\n\n @pytest.mark.parametrize(\n "ctor",\n [\n lambda *args, **kwargs: Categorical(*args, **kwargs),\n lambda *args, **kwargs: Series(Categorical(*args, **kwargs)),\n ],\n )\n def test_unordered_different_order_equal(self, ctor):\n # https://github.com/pandas-dev/pandas/issues/16014\n c1 = ctor(["a", "b"], categories=["a", "b"], ordered=False)\n c2 = ctor(["a", "b"], categories=["b", "a"], ordered=False)\n assert (c1 == c2).all()\n\n c1 = ctor(["a", "b"], categories=["a", "b"], ordered=False)\n c2 = ctor(["b", "a"], categories=["b", "a"], ordered=False)\n assert (c1 != c2).all()\n\n c1 = ctor(["a", "a"], categories=["a", "b"], ordered=False)\n c2 = ctor(["b", "b"], categories=["b", "a"], ordered=False)\n assert (c1 != c2).all()\n\n c1 = ctor(["a", "a"], categories=["a", "b"], ordered=False)\n c2 = ctor(["a", "b"], categories=["b", "a"], ordered=False)\n result = c1 == c2\n tm.assert_numpy_array_equal(np.array(result), np.array([True, False]))\n\n def test_unordered_different_categories_raises(self):\n c1 = Categorical(["a", "b"], categories=["a", "b"], ordered=False)\n c2 = Categorical(["a", "c"], categories=["c", "a"], ordered=False)\n\n with pytest.raises(TypeError, match=("Categoricals can only be compared")):\n c1 == c2\n\n def test_compare_different_lengths(self):\n c1 = Categorical([], categories=["a", "b"])\n c2 = Categorical([], categories=["a"])\n\n msg = "Categoricals can only be compared if 'categories' are the same."\n with pytest.raises(TypeError, match=msg):\n c1 == c2\n\n def test_compare_unordered_different_order(self):\n # https://github.com/pandas-dev/pandas/issues/16603#issuecomment-\n # 349290078\n a = Categorical(["a"], categories=["a", "b"])\n b = Categorical(["b"], categories=["b", "a"])\n assert not a.equals(b)\n\n def test_numeric_like_ops(self):\n df = DataFrame({"value": np.random.default_rng(2).integers(0, 10000, 100)})\n labels = [f"{i} - {i + 499}" for i in range(0, 10000, 500)]\n cat_labels = Categorical(labels, labels)\n\n df = df.sort_values(by=["value"], ascending=True)\n df["value_group"] = pd.cut(\n df.value, range(0, 10500, 500), right=False, labels=cat_labels\n )\n\n # numeric ops should not succeed\n for op, str_rep in [\n ("__add__", r"\+"),\n ("__sub__", "-"),\n ("__mul__", r"\*"),\n ("__truediv__", "/"),\n ]:\n msg = f"Series cannot perform the operation {str_rep}|unsupported operand"\n with pytest.raises(TypeError, match=msg):\n getattr(df, op)(df)\n\n # reduction ops should not succeed (unless specifically defined, e.g.\n # min/max)\n s = df["value_group"]\n for op in ["kurt", "skew", "var", "std", "mean", "sum", "median"]:\n msg = f"does not support reduction '{op}'"\n with pytest.raises(TypeError, match=msg):\n getattr(s, op)(numeric_only=False)\n\n def test_numeric_like_ops_series(self):\n # numpy ops\n s = Series(Categorical([1, 2, 3, 4]))\n with pytest.raises(TypeError, match="does not support reduction 'sum'"):\n np.sum(s)\n\n @pytest.mark.parametrize(\n "op, str_rep",\n [\n ("__add__", r"\+"),\n ("__sub__", "-"),\n ("__mul__", r"\*"),\n ("__truediv__", "/"),\n ],\n )\n def test_numeric_like_ops_series_arith(self, op, str_rep):\n # numeric ops on a Series\n s = Series(Categorical([1, 2, 3, 4]))\n msg = f"Series cannot perform the operation {str_rep}|unsupported operand"\n with pytest.raises(TypeError, match=msg):\n getattr(s, op)(2)\n\n def test_numeric_like_ops_series_invalid(self):\n # invalid ufunc\n s = Series(Categorical([1, 2, 3, 4]))\n msg = "Object with dtype category cannot perform the numpy op log"\n with pytest.raises(TypeError, match=msg):\n np.log(s)\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\test_operators.py
test_operators.py
Python
15,968
0.95
0.084541
0.108187
awesome-app
130
2024-08-04T19:19:00.838272
Apache-2.0
true
16f1b9516f4389524ddc86d67e8ef7c7
import pytest\n\nimport pandas as pd\nfrom pandas import Categorical\nimport pandas._testing as tm\n\n\n@pytest.mark.parametrize(\n "to_replace,value,expected,flip_categories",\n [\n # one-to-one\n (1, 2, [2, 2, 3], False),\n (1, 4, [4, 2, 3], False),\n (4, 1, [1, 2, 3], False),\n (5, 6, [1, 2, 3], False),\n # many-to-one\n ([1], 2, [2, 2, 3], False),\n ([1, 2], 3, [3, 3, 3], False),\n ([1, 2], 4, [4, 4, 3], False),\n ((1, 2, 4), 5, [5, 5, 3], False),\n ((5, 6), 2, [1, 2, 3], False),\n ([1], [2], [2, 2, 3], False),\n ([1, 4], [5, 2], [5, 2, 3], False),\n # GH49404: overlap between to_replace and value\n ([1, 2, 3], [2, 3, 4], [2, 3, 4], False),\n # GH50872, GH46884: replace with null\n (1, None, [None, 2, 3], False),\n (1, pd.NA, [None, 2, 3], False),\n # check_categorical sorts categories, which crashes on mixed dtypes\n (3, "4", [1, 2, "4"], False),\n ([1, 2, "3"], "5", ["5", "5", 3], True),\n ],\n)\n@pytest.mark.filterwarnings(\n "ignore:.*with CategoricalDtype is deprecated:FutureWarning"\n)\ndef test_replace_categorical_series(to_replace, value, expected, flip_categories):\n # GH 31720\n\n ser = pd.Series([1, 2, 3], dtype="category")\n result = ser.replace(to_replace, value)\n expected = pd.Series(expected, dtype="category")\n ser.replace(to_replace, value, inplace=True)\n\n if flip_categories:\n expected = expected.cat.set_categories(expected.cat.categories[::-1])\n\n tm.assert_series_equal(expected, result, check_category_order=False)\n tm.assert_series_equal(expected, ser, check_category_order=False)\n\n\n@pytest.mark.parametrize(\n "to_replace, value, result, expected_error_msg",\n [\n ("b", "c", ["a", "c"], "Categorical.categories are different"),\n ("c", "d", ["a", "b"], None),\n # https://github.com/pandas-dev/pandas/issues/33288\n ("a", "a", ["a", "b"], None),\n ("b", None, ["a", None], "Categorical.categories length are different"),\n ],\n)\ndef test_replace_categorical(to_replace, value, result, expected_error_msg):\n # GH#26988\n cat = Categorical(["a", "b"])\n expected = Categorical(result)\n msg = (\n r"The behavior of Series\.replace \(and DataFrame.replace\) "\n "with CategoricalDtype"\n )\n warn = FutureWarning if expected_error_msg is not None else None\n with tm.assert_produces_warning(warn, match=msg):\n result = pd.Series(cat, copy=False).replace(to_replace, value)._values\n\n tm.assert_categorical_equal(result, expected)\n if to_replace == "b": # the "c" test is supposed to be unchanged\n with pytest.raises(AssertionError, match=expected_error_msg):\n # ensure non-inplace call does not affect original\n tm.assert_categorical_equal(cat, expected)\n\n ser = pd.Series(cat, copy=False)\n with tm.assert_produces_warning(warn, match=msg):\n ser.replace(to_replace, value, inplace=True)\n tm.assert_categorical_equal(cat, expected)\n\n\ndef test_replace_categorical_ea_dtype():\n # GH49404\n cat = Categorical(pd.array(["a", "b"], dtype="string"))\n msg = (\n r"The behavior of Series\.replace \(and DataFrame.replace\) "\n "with CategoricalDtype"\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = pd.Series(cat).replace(["a", "b"], ["c", pd.NA])._values\n expected = Categorical(pd.array(["c", pd.NA], dtype="string"))\n tm.assert_categorical_equal(result, expected)\n\n\ndef test_replace_maintain_ordering():\n # GH51016\n dtype = pd.CategoricalDtype([0, 1, 2], ordered=True)\n ser = pd.Series([0, 1, 2], dtype=dtype)\n msg = (\n r"The behavior of Series\.replace \(and DataFrame.replace\) "\n "with CategoricalDtype"\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = ser.replace(0, 2)\n expected_dtype = pd.CategoricalDtype([1, 2], ordered=True)\n expected = pd.Series([2, 1, 2], dtype=expected_dtype)\n tm.assert_series_equal(expected, result, check_category_order=True)\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\test_replace.py
test_replace.py
Python
4,102
0.95
0.063063
0.113402
awesome-app
648
2024-03-13T21:32:30.295335
BSD-3-Clause
true
1f3e0737313b914a7b8f2b67fd395538
import numpy as np\nimport pytest\n\nfrom pandas._config import using_string_dtype\n\nfrom pandas import (\n Categorical,\n CategoricalDtype,\n CategoricalIndex,\n Index,\n Series,\n date_range,\n option_context,\n period_range,\n timedelta_range,\n)\n\n\nclass TestCategoricalReprWithFactor:\n def test_print(self, using_infer_string):\n factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)\n if using_infer_string:\n expected = [\n "['a', 'b', 'b', 'a', 'a', 'c', 'c', 'c']",\n "Categories (3, str): [a < b < c]",\n ]\n else:\n expected = [\n "['a', 'b', 'b', 'a', 'a', 'c', 'c', 'c']",\n "Categories (3, object): ['a' < 'b' < 'c']",\n ]\n expected = "\n".join(expected)\n actual = repr(factor)\n assert actual == expected\n\n\nclass TestCategoricalRepr:\n def test_big_print(self):\n codes = np.array([0, 1, 2, 0, 1, 2] * 100)\n dtype = CategoricalDtype(categories=Index(["a", "b", "c"], dtype=object))\n factor = Categorical.from_codes(codes, dtype=dtype)\n expected = [\n "['a', 'b', 'c', 'a', 'b', ..., 'b', 'c', 'a', 'b', 'c']",\n "Length: 600",\n "Categories (3, object): ['a', 'b', 'c']",\n ]\n expected = "\n".join(expected)\n\n actual = repr(factor)\n\n assert actual == expected\n\n def test_empty_print(self):\n factor = Categorical([], Index(["a", "b", "c"], dtype=object))\n expected = "[], Categories (3, object): ['a', 'b', 'c']"\n actual = repr(factor)\n assert actual == expected\n\n assert expected == actual\n factor = Categorical([], Index(["a", "b", "c"], dtype=object), ordered=True)\n expected = "[], Categories (3, object): ['a' < 'b' < 'c']"\n actual = repr(factor)\n assert expected == actual\n\n factor = Categorical([], [])\n expected = "[], Categories (0, object): []"\n assert expected == repr(factor)\n\n def test_print_none_width(self):\n # GH10087\n a = Series(Categorical([1, 2, 3, 4]))\n exp = (\n "0 1\n1 2\n2 3\n3 4\n"\n "dtype: category\nCategories (4, int64): [1, 2, 3, 4]"\n )\n\n with option_context("display.width", None):\n assert exp == repr(a)\n\n @pytest.mark.skipif(\n using_string_dtype(),\n reason="Change once infer_string is set to True by default",\n )\n def test_unicode_print(self):\n c = Categorical(["aaaaa", "bb", "cccc"] * 20)\n expected = """\\n['aaaaa', 'bb', 'cccc', 'aaaaa', 'bb', ..., 'bb', 'cccc', 'aaaaa', 'bb', 'cccc']\nLength: 60\nCategories (3, object): ['aaaaa', 'bb', 'cccc']"""\n\n assert repr(c) == expected\n\n c = Categorical(["ああああ", "いいいいい", "ううううううう"] * 20)\n expected = """\\n['ああああ', 'いいいいい', 'ううううううう', 'ああああ', 'いいいいい', ..., 'いいいいい', 'ううううううう', 'ああああ', 'いいいいい', 'ううううううう']\nLength: 60\nCategories (3, object): ['ああああ', 'いいいいい', 'ううううううう']""" # noqa: E501\n\n assert repr(c) == expected\n\n # unicode option should not affect to Categorical, as it doesn't care\n # the repr width\n with option_context("display.unicode.east_asian_width", True):\n c = Categorical(["ああああ", "いいいいい", "ううううううう"] * 20)\n expected = """['ああああ', 'いいいいい', 'ううううううう', 'ああああ', 'いいいいい', ..., 'いいいいい', 'ううううううう', 'ああああ', 'いいいいい', 'ううううううう']\nLength: 60\nCategories (3, object): ['ああああ', 'いいいいい', 'ううううううう']""" # noqa: E501\n\n assert repr(c) == expected\n\n def test_categorical_repr(self):\n c = Categorical([1, 2, 3])\n exp = """[1, 2, 3]\nCategories (3, int64): [1, 2, 3]"""\n\n assert repr(c) == exp\n\n c = Categorical([1, 2, 3, 1, 2, 3], categories=[1, 2, 3])\n exp = """[1, 2, 3, 1, 2, 3]\nCategories (3, int64): [1, 2, 3]"""\n\n assert repr(c) == exp\n\n c = Categorical([1, 2, 3, 4, 5] * 10)\n exp = """[1, 2, 3, 4, 5, ..., 1, 2, 3, 4, 5]\nLength: 50\nCategories (5, int64): [1, 2, 3, 4, 5]"""\n\n assert repr(c) == exp\n\n c = Categorical(np.arange(20, dtype=np.int64))\n exp = """[0, 1, 2, 3, 4, ..., 15, 16, 17, 18, 19]\nLength: 20\nCategories (20, int64): [0, 1, 2, 3, ..., 16, 17, 18, 19]"""\n\n assert repr(c) == exp\n\n def test_categorical_repr_ordered(self):\n c = Categorical([1, 2, 3], ordered=True)\n exp = """[1, 2, 3]\nCategories (3, int64): [1 < 2 < 3]"""\n\n assert repr(c) == exp\n\n c = Categorical([1, 2, 3, 1, 2, 3], categories=[1, 2, 3], ordered=True)\n exp = """[1, 2, 3, 1, 2, 3]\nCategories (3, int64): [1 < 2 < 3]"""\n\n assert repr(c) == exp\n\n c = Categorical([1, 2, 3, 4, 5] * 10, ordered=True)\n exp = """[1, 2, 3, 4, 5, ..., 1, 2, 3, 4, 5]\nLength: 50\nCategories (5, int64): [1 < 2 < 3 < 4 < 5]"""\n\n assert repr(c) == exp\n\n c = Categorical(np.arange(20, dtype=np.int64), ordered=True)\n exp = """[0, 1, 2, 3, 4, ..., 15, 16, 17, 18, 19]\nLength: 20\nCategories (20, int64): [0 < 1 < 2 < 3 ... 16 < 17 < 18 < 19]"""\n\n assert repr(c) == exp\n\n def test_categorical_repr_datetime(self):\n idx = date_range("2011-01-01 09:00", freq="h", periods=5)\n c = Categorical(idx)\n\n exp = (\n "[2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, "\n "2011-01-01 12:00:00, 2011-01-01 13:00:00]\n"\n "Categories (5, datetime64[ns]): [2011-01-01 09:00:00, "\n "2011-01-01 10:00:00, 2011-01-01 11:00:00,\n"\n " 2011-01-01 12:00:00, "\n "2011-01-01 13:00:00]"\n ""\n )\n assert repr(c) == exp\n\n c = Categorical(idx.append(idx), categories=idx)\n exp = (\n "[2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, "\n "2011-01-01 12:00:00, 2011-01-01 13:00:00, 2011-01-01 09:00:00, "\n "2011-01-01 10:00:00, 2011-01-01 11:00:00, 2011-01-01 12:00:00, "\n "2011-01-01 13:00:00]\n"\n "Categories (5, datetime64[ns]): [2011-01-01 09:00:00, "\n "2011-01-01 10:00:00, 2011-01-01 11:00:00,\n"\n " 2011-01-01 12:00:00, "\n "2011-01-01 13:00:00]"\n )\n\n assert repr(c) == exp\n\n idx = date_range("2011-01-01 09:00", freq="h", periods=5, tz="US/Eastern")\n c = Categorical(idx)\n exp = (\n "[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, "\n "2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, "\n "2011-01-01 13:00:00-05:00]\n"\n "Categories (5, datetime64[ns, US/Eastern]): "\n "[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00,\n"\n " "\n "2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00,\n"\n " "\n "2011-01-01 13:00:00-05:00]"\n )\n\n assert repr(c) == exp\n\n c = Categorical(idx.append(idx), categories=idx)\n exp = (\n "[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, "\n "2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, "\n "2011-01-01 13:00:00-05:00, 2011-01-01 09:00:00-05:00, "\n "2011-01-01 10:00:00-05:00, 2011-01-01 11:00:00-05:00, "\n "2011-01-01 12:00:00-05:00, 2011-01-01 13:00:00-05:00]\n"\n "Categories (5, datetime64[ns, US/Eastern]): "\n "[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00,\n"\n " "\n "2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00,\n"\n " "\n "2011-01-01 13:00:00-05:00]"\n )\n\n assert repr(c) == exp\n\n def test_categorical_repr_datetime_ordered(self):\n idx = date_range("2011-01-01 09:00", freq="h", periods=5)\n c = Categorical(idx, ordered=True)\n 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]\nCategories (5, datetime64[ns]): [2011-01-01 09:00:00 < 2011-01-01 10:00:00 < 2011-01-01 11:00:00 <\n 2011-01-01 12:00:00 < 2011-01-01 13:00:00]""" # noqa: E501\n\n assert repr(c) == exp\n\n c = Categorical(idx.append(idx), categories=idx, ordered=True)\n 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]\nCategories (5, datetime64[ns]): [2011-01-01 09:00:00 < 2011-01-01 10:00:00 < 2011-01-01 11:00:00 <\n 2011-01-01 12:00:00 < 2011-01-01 13:00:00]""" # noqa: E501\n\n assert repr(c) == exp\n\n idx = date_range("2011-01-01 09:00", freq="h", periods=5, tz="US/Eastern")\n c = Categorical(idx, ordered=True)\n 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]\nCategories (5, datetime64[ns, US/Eastern]): [2011-01-01 09:00:00-05:00 < 2011-01-01 10:00:00-05:00 <\n 2011-01-01 11:00:00-05:00 < 2011-01-01 12:00:00-05:00 <\n 2011-01-01 13:00:00-05:00]""" # noqa: E501\n\n assert repr(c) == exp\n\n c = Categorical(idx.append(idx), categories=idx, ordered=True)\n 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]\nCategories (5, datetime64[ns, US/Eastern]): [2011-01-01 09:00:00-05:00 < 2011-01-01 10:00:00-05:00 <\n 2011-01-01 11:00:00-05:00 < 2011-01-01 12:00:00-05:00 <\n 2011-01-01 13:00:00-05:00]""" # noqa: E501\n\n assert repr(c) == exp\n\n def test_categorical_repr_int_with_nan(self):\n c = Categorical([1, 2, np.nan])\n c_exp = """[1, 2, NaN]\nCategories (2, int64): [1, 2]"""\n assert repr(c) == c_exp\n\n s = Series([1, 2, np.nan], dtype="object").astype("category")\n s_exp = """0 1\n1 2\n2 NaN\ndtype: category\nCategories (2, int64): [1, 2]"""\n assert repr(s) == s_exp\n\n def test_categorical_repr_period(self):\n idx = period_range("2011-01-01 09:00", freq="h", periods=5)\n c = Categorical(idx)\n 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]\nCategories (5, period[h]): [2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00,\n 2011-01-01 13:00]""" # noqa: E501\n\n assert repr(c) == exp\n\n c = Categorical(idx.append(idx), categories=idx)\n 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]\nCategories (5, period[h]): [2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00,\n 2011-01-01 13:00]""" # noqa: E501\n\n assert repr(c) == exp\n\n idx = period_range("2011-01", freq="M", periods=5)\n c = Categorical(idx)\n exp = """[2011-01, 2011-02, 2011-03, 2011-04, 2011-05]\nCategories (5, period[M]): [2011-01, 2011-02, 2011-03, 2011-04, 2011-05]"""\n\n assert repr(c) == exp\n\n c = Categorical(idx.append(idx), categories=idx)\n exp = """[2011-01, 2011-02, 2011-03, 2011-04, 2011-05, 2011-01, 2011-02, 2011-03, 2011-04, 2011-05]\nCategories (5, period[M]): [2011-01, 2011-02, 2011-03, 2011-04, 2011-05]""" # noqa: E501\n\n assert repr(c) == exp\n\n def test_categorical_repr_period_ordered(self):\n idx = period_range("2011-01-01 09:00", freq="h", periods=5)\n c = Categorical(idx, ordered=True)\n 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]\nCategories (5, period[h]): [2011-01-01 09:00 < 2011-01-01 10:00 < 2011-01-01 11:00 < 2011-01-01 12:00 <\n 2011-01-01 13:00]""" # noqa: E501\n\n assert repr(c) == exp\n\n c = Categorical(idx.append(idx), categories=idx, ordered=True)\n 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]\nCategories (5, period[h]): [2011-01-01 09:00 < 2011-01-01 10:00 < 2011-01-01 11:00 < 2011-01-01 12:00 <\n 2011-01-01 13:00]""" # noqa: E501\n\n assert repr(c) == exp\n\n idx = period_range("2011-01", freq="M", periods=5)\n c = Categorical(idx, ordered=True)\n exp = """[2011-01, 2011-02, 2011-03, 2011-04, 2011-05]\nCategories (5, period[M]): [2011-01 < 2011-02 < 2011-03 < 2011-04 < 2011-05]"""\n\n assert repr(c) == exp\n\n c = Categorical(idx.append(idx), categories=idx, ordered=True)\n exp = """[2011-01, 2011-02, 2011-03, 2011-04, 2011-05, 2011-01, 2011-02, 2011-03, 2011-04, 2011-05]\nCategories (5, period[M]): [2011-01 < 2011-02 < 2011-03 < 2011-04 < 2011-05]""" # noqa: E501\n\n assert repr(c) == exp\n\n def test_categorical_repr_timedelta(self):\n idx = timedelta_range("1 days", periods=5)\n c = Categorical(idx)\n exp = """[1 days, 2 days, 3 days, 4 days, 5 days]\nCategories (5, timedelta64[ns]): [1 days, 2 days, 3 days, 4 days, 5 days]"""\n\n assert repr(c) == exp\n\n c = Categorical(idx.append(idx), categories=idx)\n exp = """[1 days, 2 days, 3 days, 4 days, 5 days, 1 days, 2 days, 3 days, 4 days, 5 days]\nCategories (5, timedelta64[ns]): [1 days, 2 days, 3 days, 4 days, 5 days]""" # noqa: E501\n\n assert repr(c) == exp\n\n idx = timedelta_range("1 hours", periods=20)\n c = Categorical(idx)\n 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]\nLength: 20\nCategories (20, timedelta64[ns]): [0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00,\n 3 days 01:00:00, ..., 16 days 01:00:00, 17 days 01:00:00,\n 18 days 01:00:00, 19 days 01:00:00]""" # noqa: E501\n\n assert repr(c) == exp\n\n c = Categorical(idx.append(idx), categories=idx)\n 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]\nLength: 40\nCategories (20, timedelta64[ns]): [0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00,\n 3 days 01:00:00, ..., 16 days 01:00:00, 17 days 01:00:00,\n 18 days 01:00:00, 19 days 01:00:00]""" # noqa: E501\n\n assert repr(c) == exp\n\n def test_categorical_repr_timedelta_ordered(self):\n idx = timedelta_range("1 days", periods=5)\n c = Categorical(idx, ordered=True)\n exp = """[1 days, 2 days, 3 days, 4 days, 5 days]\nCategories (5, timedelta64[ns]): [1 days < 2 days < 3 days < 4 days < 5 days]"""\n\n assert repr(c) == exp\n\n c = Categorical(idx.append(idx), categories=idx, ordered=True)\n exp = """[1 days, 2 days, 3 days, 4 days, 5 days, 1 days, 2 days, 3 days, 4 days, 5 days]\nCategories (5, timedelta64[ns]): [1 days < 2 days < 3 days < 4 days < 5 days]""" # noqa: E501\n\n assert repr(c) == exp\n\n idx = timedelta_range("1 hours", periods=20)\n c = Categorical(idx, ordered=True)\n 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]\nLength: 20\nCategories (20, timedelta64[ns]): [0 days 01:00:00 < 1 days 01:00:00 < 2 days 01:00:00 <\n 3 days 01:00:00 ... 16 days 01:00:00 < 17 days 01:00:00 <\n 18 days 01:00:00 < 19 days 01:00:00]""" # noqa: E501\n\n assert repr(c) == exp\n\n c = Categorical(idx.append(idx), categories=idx, ordered=True)\n 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]\nLength: 40\nCategories (20, timedelta64[ns]): [0 days 01:00:00 < 1 days 01:00:00 < 2 days 01:00:00 <\n 3 days 01:00:00 ... 16 days 01:00:00 < 17 days 01:00:00 <\n 18 days 01:00:00 < 19 days 01:00:00]""" # noqa: E501\n\n assert repr(c) == exp\n\n def test_categorical_index_repr(self):\n idx = CategoricalIndex(Categorical([1, 2, 3]))\n exp = """CategoricalIndex([1, 2, 3], categories=[1, 2, 3], ordered=False, dtype='category')""" # noqa: E501\n assert repr(idx) == exp\n\n i = CategoricalIndex(Categorical(np.arange(10, dtype=np.int64)))\n 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\n assert repr(i) == exp\n\n def test_categorical_index_repr_ordered(self):\n i = CategoricalIndex(Categorical([1, 2, 3], ordered=True))\n exp = """CategoricalIndex([1, 2, 3], categories=[1, 2, 3], ordered=True, dtype='category')""" # noqa: E501\n assert repr(i) == exp\n\n i = CategoricalIndex(Categorical(np.arange(10, dtype=np.int64), ordered=True))\n 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\n assert repr(i) == exp\n\n def test_categorical_index_repr_datetime(self):\n idx = date_range("2011-01-01 09:00", freq="h", periods=5)\n i = CategoricalIndex(Categorical(idx))\n exp = """CategoricalIndex(['2011-01-01 09:00:00', '2011-01-01 10:00:00',\n '2011-01-01 11:00:00', '2011-01-01 12:00:00',\n '2011-01-01 13:00:00'],\n 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\n\n assert repr(i) == exp\n\n idx = date_range("2011-01-01 09:00", freq="h", periods=5, tz="US/Eastern")\n i = CategoricalIndex(Categorical(idx))\n exp = """CategoricalIndex(['2011-01-01 09:00:00-05:00', '2011-01-01 10:00:00-05:00',\n '2011-01-01 11:00:00-05:00', '2011-01-01 12:00:00-05:00',\n '2011-01-01 13:00:00-05:00'],\n 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\n\n assert repr(i) == exp\n\n def test_categorical_index_repr_datetime_ordered(self):\n idx = date_range("2011-01-01 09:00", freq="h", periods=5)\n i = CategoricalIndex(Categorical(idx, ordered=True))\n exp = """CategoricalIndex(['2011-01-01 09:00:00', '2011-01-01 10:00:00',\n '2011-01-01 11:00:00', '2011-01-01 12:00:00',\n '2011-01-01 13:00:00'],\n 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\n\n assert repr(i) == exp\n\n idx = date_range("2011-01-01 09:00", freq="h", periods=5, tz="US/Eastern")\n i = CategoricalIndex(Categorical(idx, ordered=True))\n exp = """CategoricalIndex(['2011-01-01 09:00:00-05:00', '2011-01-01 10:00:00-05:00',\n '2011-01-01 11:00:00-05:00', '2011-01-01 12:00:00-05:00',\n '2011-01-01 13:00:00-05:00'],\n 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\n\n assert repr(i) == exp\n\n i = CategoricalIndex(Categorical(idx.append(idx), ordered=True))\n exp = """CategoricalIndex(['2011-01-01 09:00:00-05:00', '2011-01-01 10:00:00-05:00',\n '2011-01-01 11:00:00-05:00', '2011-01-01 12:00:00-05:00',\n '2011-01-01 13:00:00-05:00', '2011-01-01 09:00:00-05:00',\n '2011-01-01 10:00:00-05:00', '2011-01-01 11:00:00-05:00',\n '2011-01-01 12:00:00-05:00', '2011-01-01 13:00:00-05:00'],\n 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\n\n assert repr(i) == exp\n\n def test_categorical_index_repr_period(self):\n # test all length\n idx = period_range("2011-01-01 09:00", freq="h", periods=1)\n i = CategoricalIndex(Categorical(idx))\n exp = """CategoricalIndex(['2011-01-01 09:00'], categories=[2011-01-01 09:00], ordered=False, dtype='category')""" # noqa: E501\n assert repr(i) == exp\n\n idx = period_range("2011-01-01 09:00", freq="h", periods=2)\n i = CategoricalIndex(Categorical(idx))\n 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\n assert repr(i) == exp\n\n idx = period_range("2011-01-01 09:00", freq="h", periods=3)\n i = CategoricalIndex(Categorical(idx))\n 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\n assert repr(i) == exp\n\n idx = period_range("2011-01-01 09:00", freq="h", periods=5)\n i = CategoricalIndex(Categorical(idx))\n exp = """CategoricalIndex(['2011-01-01 09:00', '2011-01-01 10:00', '2011-01-01 11:00',\n '2011-01-01 12:00', '2011-01-01 13:00'],\n 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\n\n assert repr(i) == exp\n\n i = CategoricalIndex(Categorical(idx.append(idx)))\n exp = """CategoricalIndex(['2011-01-01 09:00', '2011-01-01 10:00', '2011-01-01 11:00',\n '2011-01-01 12:00', '2011-01-01 13:00', '2011-01-01 09:00',\n '2011-01-01 10:00', '2011-01-01 11:00', '2011-01-01 12:00',\n '2011-01-01 13:00'],\n 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\n\n assert repr(i) == exp\n\n idx = period_range("2011-01", freq="M", periods=5)\n i = CategoricalIndex(Categorical(idx))\n 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\n assert repr(i) == exp\n\n def test_categorical_index_repr_period_ordered(self):\n idx = period_range("2011-01-01 09:00", freq="h", periods=5)\n i = CategoricalIndex(Categorical(idx, ordered=True))\n exp = """CategoricalIndex(['2011-01-01 09:00', '2011-01-01 10:00', '2011-01-01 11:00',\n '2011-01-01 12:00', '2011-01-01 13:00'],\n 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\n\n assert repr(i) == exp\n\n idx = period_range("2011-01", freq="M", periods=5)\n i = CategoricalIndex(Categorical(idx, ordered=True))\n 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\n assert repr(i) == exp\n\n def test_categorical_index_repr_timedelta(self):\n idx = timedelta_range("1 days", periods=5)\n i = CategoricalIndex(Categorical(idx))\n 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\n assert repr(i) == exp\n\n idx = timedelta_range("1 hours", periods=10)\n i = CategoricalIndex(Categorical(idx))\n exp = """CategoricalIndex(['0 days 01:00:00', '1 days 01:00:00', '2 days 01:00:00',\n '3 days 01:00:00', '4 days 01:00:00', '5 days 01:00:00',\n '6 days 01:00:00', '7 days 01:00:00', '8 days 01:00:00',\n '9 days 01:00:00'],\n 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\n\n assert repr(i) == exp\n\n def test_categorical_index_repr_timedelta_ordered(self):\n idx = timedelta_range("1 days", periods=5)\n i = CategoricalIndex(Categorical(idx, ordered=True))\n 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\n assert repr(i) == exp\n\n idx = timedelta_range("1 hours", periods=10)\n i = CategoricalIndex(Categorical(idx, ordered=True))\n exp = """CategoricalIndex(['0 days 01:00:00', '1 days 01:00:00', '2 days 01:00:00',\n '3 days 01:00:00', '4 days 01:00:00', '5 days 01:00:00',\n '6 days 01:00:00', '7 days 01:00:00', '8 days 01:00:00',\n '9 days 01:00:00'],\n 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\n\n assert repr(i) == exp\n\n def test_categorical_str_repr(self):\n # GH 33676\n result = repr(Categorical([1, "2", 3, 4]))\n expected = "[1, '2', 3, 4]\nCategories (4, object): [1, 3, 4, '2']"\n assert result == expected\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\test_repr.py
test_repr.py
Python
27,088
0.95
0.047273
0.011547
awesome-app
6
2024-11-30T17:47:56.485570
GPL-3.0
true
1dbd2385fd0f2c3deae1ccf85a46009b
import numpy as np\nimport pytest\n\nfrom pandas import (\n Categorical,\n Index,\n)\nimport pandas._testing as tm\n\n\nclass TestCategoricalSort:\n def test_argsort(self):\n c = Categorical([5, 3, 1, 4, 2], ordered=True)\n\n expected = np.array([2, 4, 1, 3, 0])\n tm.assert_numpy_array_equal(\n c.argsort(ascending=True), expected, check_dtype=False\n )\n\n expected = expected[::-1]\n tm.assert_numpy_array_equal(\n c.argsort(ascending=False), expected, check_dtype=False\n )\n\n def test_numpy_argsort(self):\n c = Categorical([5, 3, 1, 4, 2], ordered=True)\n\n expected = np.array([2, 4, 1, 3, 0])\n tm.assert_numpy_array_equal(np.argsort(c), expected, check_dtype=False)\n\n tm.assert_numpy_array_equal(\n np.argsort(c, kind="mergesort"), expected, check_dtype=False\n )\n\n msg = "the 'axis' parameter is not supported"\n with pytest.raises(ValueError, match=msg):\n np.argsort(c, axis=0)\n\n msg = "the 'order' parameter is not supported"\n with pytest.raises(ValueError, match=msg):\n np.argsort(c, order="C")\n\n def test_sort_values(self):\n # unordered cats are sortable\n cat = Categorical(["a", "b", "b", "a"], ordered=False)\n cat.sort_values()\n\n cat = Categorical(["a", "c", "b", "d"], ordered=True)\n\n # sort_values\n res = cat.sort_values()\n exp = np.array(["a", "b", "c", "d"], dtype=object)\n tm.assert_numpy_array_equal(res.__array__(), exp)\n tm.assert_index_equal(res.categories, cat.categories)\n\n cat = Categorical(\n ["a", "c", "b", "d"], categories=["a", "b", "c", "d"], ordered=True\n )\n res = cat.sort_values()\n exp = np.array(["a", "b", "c", "d"], dtype=object)\n tm.assert_numpy_array_equal(res.__array__(), exp)\n tm.assert_index_equal(res.categories, cat.categories)\n\n res = cat.sort_values(ascending=False)\n exp = np.array(["d", "c", "b", "a"], dtype=object)\n tm.assert_numpy_array_equal(res.__array__(), exp)\n tm.assert_index_equal(res.categories, cat.categories)\n\n # sort (inplace order)\n cat1 = cat.copy()\n orig_codes = cat1._codes\n cat1.sort_values(inplace=True)\n assert cat1._codes is orig_codes\n exp = np.array(["a", "b", "c", "d"], dtype=object)\n tm.assert_numpy_array_equal(cat1.__array__(), exp)\n tm.assert_index_equal(res.categories, cat.categories)\n\n # reverse\n cat = Categorical(["a", "c", "c", "b", "d"], ordered=True)\n res = cat.sort_values(ascending=False)\n exp_val = np.array(["d", "c", "c", "b", "a"], dtype=object)\n exp_categories = Index(["a", "b", "c", "d"])\n tm.assert_numpy_array_equal(res.__array__(), exp_val)\n tm.assert_index_equal(res.categories, exp_categories)\n\n def test_sort_values_na_position(self):\n # see gh-12882\n cat = Categorical([5, 2, np.nan, 2, np.nan], ordered=True)\n exp_categories = Index([2, 5])\n\n exp = np.array([2.0, 2.0, 5.0, np.nan, np.nan])\n res = cat.sort_values() # default arguments\n tm.assert_numpy_array_equal(res.__array__(), exp)\n tm.assert_index_equal(res.categories, exp_categories)\n\n exp = np.array([np.nan, np.nan, 2.0, 2.0, 5.0])\n res = cat.sort_values(ascending=True, na_position="first")\n tm.assert_numpy_array_equal(res.__array__(), exp)\n tm.assert_index_equal(res.categories, exp_categories)\n\n exp = np.array([np.nan, np.nan, 5.0, 2.0, 2.0])\n res = cat.sort_values(ascending=False, na_position="first")\n tm.assert_numpy_array_equal(res.__array__(), exp)\n tm.assert_index_equal(res.categories, exp_categories)\n\n exp = np.array([2.0, 2.0, 5.0, np.nan, np.nan])\n res = cat.sort_values(ascending=True, na_position="last")\n tm.assert_numpy_array_equal(res.__array__(), exp)\n tm.assert_index_equal(res.categories, exp_categories)\n\n exp = np.array([5.0, 2.0, 2.0, np.nan, np.nan])\n res = cat.sort_values(ascending=False, na_position="last")\n tm.assert_numpy_array_equal(res.__array__(), exp)\n tm.assert_index_equal(res.categories, exp_categories)\n\n cat = Categorical(["a", "c", "b", "d", np.nan], ordered=True)\n res = cat.sort_values(ascending=False, na_position="last")\n exp_val = np.array(["d", "c", "b", "a", np.nan], dtype=object)\n exp_categories = Index(["a", "b", "c", "d"])\n tm.assert_numpy_array_equal(res.__array__(), exp_val)\n tm.assert_index_equal(res.categories, exp_categories)\n\n cat = Categorical(["a", "c", "b", "d", np.nan], ordered=True)\n res = cat.sort_values(ascending=False, na_position="first")\n exp_val = np.array([np.nan, "d", "c", "b", "a"], dtype=object)\n exp_categories = Index(["a", "b", "c", "d"])\n tm.assert_numpy_array_equal(res.__array__(), exp_val)\n tm.assert_index_equal(res.categories, exp_categories)\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\test_sorting.py
test_sorting.py
Python
5,052
0.95
0.039063
0.048544
vue-tools
41
2023-12-04T23:58:39.776387
BSD-3-Clause
true
7b9e9ecdada1c275300ae79ae5e82b0b
from pandas import Categorical\nimport pandas._testing as tm\n\n\nclass SubclassedCategorical(Categorical):\n pass\n\n\nclass TestCategoricalSubclassing:\n def test_constructor(self):\n sc = SubclassedCategorical(["a", "b", "c"])\n assert isinstance(sc, SubclassedCategorical)\n tm.assert_categorical_equal(sc, Categorical(["a", "b", "c"]))\n\n def test_from_codes(self):\n sc = SubclassedCategorical.from_codes([1, 0, 2], ["a", "b", "c"])\n assert isinstance(sc, SubclassedCategorical)\n exp = Categorical.from_codes([1, 0, 2], ["a", "b", "c"])\n tm.assert_categorical_equal(sc, exp)\n\n def test_map(self):\n sc = SubclassedCategorical(["a", "b", "c"])\n res = sc.map(lambda x: x.upper(), na_action=None)\n assert isinstance(res, SubclassedCategorical)\n exp = Categorical(["A", "B", "C"])\n tm.assert_categorical_equal(res, exp)\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\test_subclass.py
test_subclass.py
Python
903
0.85
0.192308
0
node-utils
233
2025-05-08T03:23:14.804829
GPL-3.0
true
a0f092cfae9ec31da3537dede0c9b962
import numpy as np\nimport pytest\n\nfrom pandas import Categorical\nimport pandas._testing as tm\n\n\n@pytest.fixture(params=[True, False])\ndef allow_fill(request):\n """Boolean 'allow_fill' parameter for Categorical.take"""\n return request.param\n\n\nclass TestTake:\n # https://github.com/pandas-dev/pandas/issues/20664\n\n def test_take_default_allow_fill(self):\n cat = Categorical(["a", "b"])\n with tm.assert_produces_warning(None):\n result = cat.take([0, -1])\n\n assert result.equals(cat)\n\n def test_take_positive_no_warning(self):\n cat = Categorical(["a", "b"])\n with tm.assert_produces_warning(None):\n cat.take([0, 0])\n\n def test_take_bounds(self, allow_fill):\n # https://github.com/pandas-dev/pandas/issues/20664\n cat = Categorical(["a", "b", "a"])\n if allow_fill:\n msg = "indices are out-of-bounds"\n else:\n msg = "index 4 is out of bounds for( axis 0 with)? size 3"\n with pytest.raises(IndexError, match=msg):\n cat.take([4, 5], allow_fill=allow_fill)\n\n def test_take_empty(self, allow_fill):\n # https://github.com/pandas-dev/pandas/issues/20664\n cat = Categorical([], categories=["a", "b"])\n if allow_fill:\n msg = "indices are out-of-bounds"\n else:\n msg = "cannot do a non-empty take from an empty axes"\n with pytest.raises(IndexError, match=msg):\n cat.take([0], allow_fill=allow_fill)\n\n def test_positional_take(self, ordered):\n cat = Categorical(["a", "a", "b", "b"], categories=["b", "a"], ordered=ordered)\n result = cat.take([0, 1, 2], allow_fill=False)\n expected = Categorical(\n ["a", "a", "b"], categories=cat.categories, ordered=ordered\n )\n tm.assert_categorical_equal(result, expected)\n\n def test_positional_take_unobserved(self, ordered):\n cat = Categorical(["a", "b"], categories=["a", "b", "c"], ordered=ordered)\n result = cat.take([1, 0], allow_fill=False)\n expected = Categorical(["b", "a"], categories=cat.categories, ordered=ordered)\n tm.assert_categorical_equal(result, expected)\n\n def test_take_allow_fill(self):\n # https://github.com/pandas-dev/pandas/issues/23296\n cat = Categorical(["a", "a", "b"])\n result = cat.take([0, -1, -1], allow_fill=True)\n expected = Categorical(["a", np.nan, np.nan], categories=["a", "b"])\n tm.assert_categorical_equal(result, expected)\n\n def test_take_fill_with_negative_one(self):\n # -1 was a category\n cat = Categorical([-1, 0, 1])\n result = cat.take([0, -1, 1], allow_fill=True, fill_value=-1)\n expected = Categorical([-1, -1, 0], categories=[-1, 0, 1])\n tm.assert_categorical_equal(result, expected)\n\n def test_take_fill_value(self):\n # https://github.com/pandas-dev/pandas/issues/23296\n cat = Categorical(["a", "b", "c"])\n result = cat.take([0, 1, -1], fill_value="a", allow_fill=True)\n expected = Categorical(["a", "b", "a"], categories=["a", "b", "c"])\n tm.assert_categorical_equal(result, expected)\n\n def test_take_fill_value_new_raises(self):\n # https://github.com/pandas-dev/pandas/issues/23296\n cat = Categorical(["a", "b", "c"])\n xpr = r"Cannot setitem on a Categorical with a new category \(d\)"\n with pytest.raises(TypeError, match=xpr):\n cat.take([0, 1, -1], fill_value="d", allow_fill=True)\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\test_take.py
test_take.py
Python
3,501
0.95
0.179775
0.09589
react-lib
617
2024-09-11T14:08:01.254507
GPL-3.0
true
3d0b3c73813be30438471ee80e2663b1
import pytest\n\nimport pandas._testing as tm\n\n\nclass TestCategoricalWarnings:\n def test_tab_complete_warning(self, ip):\n # https://github.com/pandas-dev/pandas/issues/16409\n pytest.importorskip("IPython", minversion="6.0.0")\n from IPython.core.completer import provisionalcompleter\n\n code = "import pandas as pd; c = pd.Categorical([])"\n ip.run_cell(code)\n\n # GH 31324 newer jedi version raises Deprecation warning;\n # appears resolved 2021-02-02\n with tm.assert_produces_warning(None, raise_on_extra_warnings=False):\n with provisionalcompleter("ignore"):\n list(ip.Completer.completions("c.", 1))\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\test_warnings.py
test_warnings.py
Python
682
0.95
0.105263
0.214286
python-kit
49
2024-05-30T04:23:01.775959
BSD-3-Clause
true
707087ec5ac5526efe77e1892b379174
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\__pycache__\test_algos.cpython-313.pyc
test_algos.cpython-313.pyc
Other
5,269
0.8
0
0
react-lib
299
2024-01-01T00:59:09.896345
BSD-3-Clause
true
03cea50dea01ac22147ea00599d7b4dd
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\__pycache__\test_analytics.cpython-313.pyc
test_analytics.cpython-313.pyc
Other
20,597
0.95
0.004444
0
awesome-app
282
2023-11-16T18:59:14.733049
GPL-3.0
true
0b1ce09dd1ab25157ded7219120fad35
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\__pycache__\test_api.cpython-313.pyc
test_api.cpython-313.pyc
Other
28,172
0.8
0
0.004149
react-lib
501
2024-04-18T08:58:05.214387
GPL-3.0
true
c56186c8d8efb72bdc0d91ac8429edba
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\__pycache__\test_astype.cpython-313.pyc
test_astype.cpython-313.pyc
Other
8,994
0.8
0
0
awesome-app
205
2025-05-16T02:14:10.521692
BSD-3-Clause
true
4d24920cb3f552b987d853af618edc74
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\__pycache__\test_constructors.cpython-313.pyc
test_constructors.cpython-313.pyc
Other
48,572
0.8
0
0
vue-tools
514
2023-12-23T18:44:08.747342
Apache-2.0
true
51bd4d2c749a006fb7b1f8e7c5d3454a
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\__pycache__\test_dtypes.cpython-313.pyc
test_dtypes.cpython-313.pyc
Other
8,714
0.8
0
0
python-kit
374
2024-10-22T13:39:29.289042
BSD-3-Clause
true
b005aff71e853bf478f119363b4ccbc7
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\__pycache__\test_indexing.cpython-313.pyc
test_indexing.cpython-313.pyc
Other
20,496
0.8
0
0.014925
python-kit
219
2025-07-08T12:40:43.819482
MIT
true
1b87b2d581f02e7039887b81199e5ace
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\__pycache__\test_map.cpython-313.pyc
test_map.cpython-313.pyc
Other
7,870
0.8
0.010101
0.020408
awesome-app
904
2023-10-23T06:56:06.638285
Apache-2.0
true
cbe0a148947efa05b4bc272039b83ab2
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\__pycache__\test_missing.cpython-313.pyc
test_missing.cpython-313.pyc
Other
12,321
0.8
0
0.027027
vue-tools
128
2025-04-08T07:05:58.707411
Apache-2.0
true
bb57f4edfa46525d9124f5c1c17ee2c4
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\__pycache__\test_operators.cpython-313.pyc
test_operators.cpython-313.pyc
Other
22,306
0.95
0.011905
0.012121
node-utils
927
2023-10-19T13:53:30.588493
BSD-3-Clause
true
7e6bfe77f07bbfff8a0774f6105ffb9a
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\__pycache__\test_replace.cpython-313.pyc
test_replace.cpython-313.pyc
Other
5,679
0.8
0
0.027778
python-kit
419
2024-03-17T00:10:13.838172
GPL-3.0
true
3ee9d861f37684455c57fb758d1c1961
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\__pycache__\test_repr.cpython-313.pyc
test_repr.cpython-313.pyc
Other
30,756
0.8
0
0.005051
awesome-app
69
2024-07-02T07:52:17.663972
BSD-3-Clause
true
419125d17e9f6bbced81fb5a1e022cf6
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\__pycache__\test_sorting.cpython-313.pyc
test_sorting.cpython-313.pyc
Other
8,139
0.8
0
0
awesome-app
886
2024-03-28T07:01:35.147202
Apache-2.0
true
9fda7251cf6dbf06cc59e6396415a125
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\__pycache__\test_subclass.cpython-313.pyc
test_subclass.cpython-313.pyc
Other
2,273
0.8
0
0
react-lib
799
2023-10-06T13:20:22.863899
Apache-2.0
true
a1ac7f77b1b8955472feac2bc84d01ff
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\__pycache__\test_take.cpython-313.pyc
test_take.cpython-313.pyc
Other
5,721
0.8
0.032787
0
awesome-app
794
2024-10-19T12:55:20.858368
Apache-2.0
true
136343bfd4f9b2f06277bacf972bc61e
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\__pycache__\test_warnings.cpython-313.pyc
test_warnings.cpython-313.pyc
Other
1,452
0.95
0
0
python-kit
497
2024-12-23T17:00:12.399096
Apache-2.0
true
8d4435a83e3c5299922161849fe893ac
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\categorical\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
206
0.7
0
0
vue-tools
50
2023-12-12T08:36:52.756241
BSD-3-Clause
true
ead7bb2c2cc7d738c8c0efd39280407d
import numpy as np\nimport pytest\n\nfrom pandas._libs import iNaT\n\nfrom pandas.core.dtypes.dtypes import DatetimeTZDtype\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.core.arrays import DatetimeArray\n\n\nclass TestDatetimeArrayConstructor:\n def test_from_sequence_invalid_type(self):\n mi = pd.MultiIndex.from_product([np.arange(5), np.arange(5)])\n with pytest.raises(TypeError, match="Cannot create a DatetimeArray"):\n DatetimeArray._from_sequence(mi, dtype="M8[ns]")\n\n def test_only_1dim_accepted(self):\n arr = np.array([0, 1, 2, 3], dtype="M8[h]").astype("M8[ns]")\n\n depr_msg = "DatetimeArray.__init__ is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n with pytest.raises(ValueError, match="Only 1-dimensional"):\n # 3-dim, we allow 2D to sneak in for ops purposes GH#29853\n DatetimeArray(arr.reshape(2, 2, 1))\n\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n with pytest.raises(ValueError, match="Only 1-dimensional"):\n # 0-dim\n DatetimeArray(arr[[0]].squeeze())\n\n def test_freq_validation(self):\n # GH#24623 check that invalid instances cannot be created with the\n # public constructor\n arr = np.arange(5, dtype=np.int64) * 3600 * 10**9\n\n msg = (\n "Inferred frequency h from passed values does not "\n "conform to passed frequency W-SUN"\n )\n depr_msg = "DatetimeArray.__init__ is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n with pytest.raises(ValueError, match=msg):\n DatetimeArray(arr, freq="W")\n\n @pytest.mark.parametrize(\n "meth",\n [\n DatetimeArray._from_sequence,\n pd.to_datetime,\n pd.DatetimeIndex,\n ],\n )\n def test_mixing_naive_tzaware_raises(self, meth):\n # GH#24569\n arr = np.array([pd.Timestamp("2000"), pd.Timestamp("2000", tz="CET")])\n\n msg = (\n "Cannot mix tz-aware with tz-naive values|"\n "Tz-aware datetime.datetime cannot be converted "\n "to datetime64 unless utc=True"\n )\n\n for obj in [arr, arr[::-1]]:\n # check that we raise regardless of whether naive is found\n # before aware or vice-versa\n with pytest.raises(ValueError, match=msg):\n meth(obj)\n\n def test_from_pandas_array(self):\n arr = pd.array(np.arange(5, dtype=np.int64)) * 3600 * 10**9\n\n result = DatetimeArray._from_sequence(arr, dtype="M8[ns]")._with_freq("infer")\n\n expected = pd.date_range("1970-01-01", periods=5, freq="h")._data\n tm.assert_datetime_array_equal(result, expected)\n\n def test_mismatched_timezone_raises(self):\n depr_msg = "DatetimeArray.__init__ is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n arr = DatetimeArray(\n np.array(["2000-01-01T06:00:00"], dtype="M8[ns]"),\n dtype=DatetimeTZDtype(tz="US/Central"),\n )\n dtype = DatetimeTZDtype(tz="US/Eastern")\n msg = r"dtype=datetime64\[ns.*\] does not match data dtype datetime64\[ns.*\]"\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n with pytest.raises(TypeError, match=msg):\n DatetimeArray(arr, dtype=dtype)\n\n # also with mismatched tzawareness\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n with pytest.raises(TypeError, match=msg):\n DatetimeArray(arr, dtype=np.dtype("M8[ns]"))\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n with pytest.raises(TypeError, match=msg):\n DatetimeArray(arr.tz_localize(None), dtype=arr.dtype)\n\n def test_non_array_raises(self):\n depr_msg = "DatetimeArray.__init__ is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n with pytest.raises(ValueError, match="list"):\n DatetimeArray([1, 2, 3])\n\n def test_bool_dtype_raises(self):\n arr = np.array([1, 2, 3], dtype="bool")\n\n depr_msg = "DatetimeArray.__init__ is deprecated"\n msg = "Unexpected value for 'dtype': 'bool'. Must be"\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n with pytest.raises(ValueError, match=msg):\n DatetimeArray(arr)\n\n msg = r"dtype bool cannot be converted to datetime64\[ns\]"\n with pytest.raises(TypeError, match=msg):\n DatetimeArray._from_sequence(arr, dtype="M8[ns]")\n\n with pytest.raises(TypeError, match=msg):\n pd.DatetimeIndex(arr)\n\n with pytest.raises(TypeError, match=msg):\n pd.to_datetime(arr)\n\n def test_incorrect_dtype_raises(self):\n depr_msg = "DatetimeArray.__init__ is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n with pytest.raises(ValueError, match="Unexpected value for 'dtype'."):\n DatetimeArray(np.array([1, 2, 3], dtype="i8"), dtype="category")\n\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n with pytest.raises(ValueError, match="Unexpected value for 'dtype'."):\n DatetimeArray(np.array([1, 2, 3], dtype="i8"), dtype="m8[s]")\n\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n with pytest.raises(ValueError, match="Unexpected value for 'dtype'."):\n DatetimeArray(np.array([1, 2, 3], dtype="i8"), dtype="M8[D]")\n\n def test_mismatched_values_dtype_units(self):\n arr = np.array([1, 2, 3], dtype="M8[s]")\n dtype = np.dtype("M8[ns]")\n msg = "Values resolution does not match dtype."\n depr_msg = "DatetimeArray.__init__ is deprecated"\n\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n with pytest.raises(ValueError, match=msg):\n DatetimeArray(arr, dtype=dtype)\n\n dtype2 = DatetimeTZDtype(tz="UTC", unit="ns")\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n with pytest.raises(ValueError, match=msg):\n DatetimeArray(arr, dtype=dtype2)\n\n def test_freq_infer_raises(self):\n depr_msg = "DatetimeArray.__init__ is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n with pytest.raises(ValueError, match="Frequency inference"):\n DatetimeArray(np.array([1, 2, 3], dtype="i8"), freq="infer")\n\n def test_copy(self):\n data = np.array([1, 2, 3], dtype="M8[ns]")\n arr = DatetimeArray._from_sequence(data, copy=False)\n assert arr._ndarray is data\n\n arr = DatetimeArray._from_sequence(data, copy=True)\n assert arr._ndarray is not data\n\n @pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"])\n def test_numpy_datetime_unit(self, unit):\n data = np.array([1, 2, 3], dtype=f"M8[{unit}]")\n arr = DatetimeArray._from_sequence(data)\n assert arr.unit == unit\n assert arr[0].unit == unit\n\n\nclass TestSequenceToDT64NS:\n def test_tz_dtype_mismatch_raises(self):\n arr = DatetimeArray._from_sequence(\n ["2000"], dtype=DatetimeTZDtype(tz="US/Central")\n )\n with pytest.raises(TypeError, match="data is already tz-aware"):\n DatetimeArray._from_sequence(arr, dtype=DatetimeTZDtype(tz="UTC"))\n\n def test_tz_dtype_matches(self):\n dtype = DatetimeTZDtype(tz="US/Central")\n arr = DatetimeArray._from_sequence(["2000"], dtype=dtype)\n result = DatetimeArray._from_sequence(arr, dtype=dtype)\n tm.assert_equal(arr, result)\n\n @pytest.mark.parametrize("order", ["F", "C"])\n def test_2d(self, order):\n dti = pd.date_range("2016-01-01", periods=6, tz="US/Pacific")\n arr = np.array(dti, dtype=object).reshape(3, 2)\n if order == "F":\n arr = arr.T\n\n res = DatetimeArray._from_sequence(arr, dtype=dti.dtype)\n expected = DatetimeArray._from_sequence(arr.ravel(), dtype=dti.dtype).reshape(\n arr.shape\n )\n tm.assert_datetime_array_equal(res, expected)\n\n\n# ----------------------------------------------------------------------------\n# Arrow interaction\n\n\nEXTREME_VALUES = [0, 123456789, None, iNaT, 2**63 - 1, -(2**63) + 1]\nFINE_TO_COARSE_SAFE = [123_000_000_000, None, -123_000_000_000]\nCOARSE_TO_FINE_SAFE = [123, None, -123]\n\n\n@pytest.mark.parametrize(\n ("pa_unit", "pd_unit", "pa_tz", "pd_tz", "data"),\n [\n ("s", "s", "UTC", "UTC", EXTREME_VALUES),\n ("ms", "ms", "UTC", "Europe/Berlin", EXTREME_VALUES),\n ("us", "us", "US/Eastern", "UTC", EXTREME_VALUES),\n ("ns", "ns", "US/Central", "Asia/Kolkata", EXTREME_VALUES),\n ("ns", "s", "UTC", "UTC", FINE_TO_COARSE_SAFE),\n ("us", "ms", "UTC", "Europe/Berlin", FINE_TO_COARSE_SAFE),\n ("ms", "us", "US/Eastern", "UTC", COARSE_TO_FINE_SAFE),\n ("s", "ns", "US/Central", "Asia/Kolkata", COARSE_TO_FINE_SAFE),\n ],\n)\ndef test_from_arrow_with_different_units_and_timezones_with(\n pa_unit, pd_unit, pa_tz, pd_tz, data\n):\n pa = pytest.importorskip("pyarrow")\n\n pa_type = pa.timestamp(pa_unit, tz=pa_tz)\n arr = pa.array(data, type=pa_type)\n dtype = DatetimeTZDtype(unit=pd_unit, tz=pd_tz)\n\n result = dtype.__from_arrow__(arr)\n expected = DatetimeArray._from_sequence(data, dtype=f"M8[{pa_unit}, UTC]").astype(\n dtype, copy=False\n )\n tm.assert_extension_array_equal(result, expected)\n\n result = dtype.__from_arrow__(pa.chunked_array([arr]))\n tm.assert_extension_array_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n ("unit", "tz"),\n [\n ("s", "UTC"),\n ("ms", "Europe/Berlin"),\n ("us", "US/Eastern"),\n ("ns", "Asia/Kolkata"),\n ("ns", "UTC"),\n ],\n)\ndef test_from_arrow_from_empty(unit, tz):\n pa = pytest.importorskip("pyarrow")\n\n data = []\n arr = pa.array(data)\n dtype = DatetimeTZDtype(unit=unit, tz=tz)\n\n result = dtype.__from_arrow__(arr)\n expected = DatetimeArray._from_sequence(np.array(data, dtype=f"datetime64[{unit}]"))\n expected = expected.tz_localize(tz=tz)\n tm.assert_extension_array_equal(result, expected)\n\n result = dtype.__from_arrow__(pa.chunked_array([arr]))\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_from_arrow_from_integers():\n pa = pytest.importorskip("pyarrow")\n\n data = [0, 123456789, None, 2**63 - 1, iNaT, -123456789]\n arr = pa.array(data)\n dtype = DatetimeTZDtype(unit="ns", tz="UTC")\n\n result = dtype.__from_arrow__(arr)\n expected = DatetimeArray._from_sequence(np.array(data, dtype="datetime64[ns]"))\n expected = expected.tz_localize("UTC")\n tm.assert_extension_array_equal(result, expected)\n\n result = dtype.__from_arrow__(pa.chunked_array([arr]))\n tm.assert_extension_array_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\arrays\datetimes\test_constructors.py
test_constructors.py
Python
11,050
0.95
0.098592
0.044248
react-lib
639
2024-01-29T16:54:23.349290
Apache-2.0
true
045b0d0ccb87f931504a85a6d2608a0b
import pytest\n\nimport pandas._testing as tm\nfrom pandas.core.arrays import DatetimeArray\n\n\nclass TestAccumulator:\n def test_accumulators_freq(self):\n # GH#50297\n arr = DatetimeArray._from_sequence(\n [\n "2000-01-01",\n "2000-01-02",\n "2000-01-03",\n ],\n dtype="M8[ns]",\n )._with_freq("infer")\n result = arr._accumulate("cummin")\n expected = DatetimeArray._from_sequence(["2000-01-01"] * 3, dtype="M8[ns]")\n tm.assert_datetime_array_equal(result, expected)\n\n result = arr._accumulate("cummax")\n expected = DatetimeArray._from_sequence(\n [\n "2000-01-01",\n "2000-01-02",\n "2000-01-03",\n ],\n dtype="M8[ns]",\n )\n tm.assert_datetime_array_equal(result, expected)\n\n @pytest.mark.parametrize("func", ["cumsum", "cumprod"])\n def test_accumulators_disallowed(self, func):\n # GH#50297\n arr = DatetimeArray._from_sequence(\n [\n "2000-01-01",\n "2000-01-02",\n ],\n dtype="M8[ns]",\n )._with_freq("infer")\n with pytest.raises(TypeError, match=f"Accumulation {func}"):\n arr._accumulate(func)\n
.venv\Lib\site-packages\pandas\tests\arrays\datetimes\test_cumulative.py
test_cumulative.py
Python
1,307
0.95
0.068182
0.051282
react-lib
301
2023-08-23T10:13:44.802739
MIT
true
ad9196820014ff3f2662cd3a66ef12b6
import numpy as np\nimport pytest\n\nfrom pandas.core.dtypes.dtypes import DatetimeTZDtype\n\nimport pandas as pd\nfrom pandas import NaT\nimport pandas._testing as tm\nfrom pandas.core.arrays import DatetimeArray\n\n\nclass TestReductions:\n @pytest.fixture(params=["s", "ms", "us", "ns"])\n def unit(self, request):\n return request.param\n\n @pytest.fixture\n def arr1d(self, tz_naive_fixture):\n """Fixture returning DatetimeArray with parametrized timezones"""\n tz = tz_naive_fixture\n dtype = DatetimeTZDtype(tz=tz) if tz is not None else np.dtype("M8[ns]")\n arr = DatetimeArray._from_sequence(\n [\n "2000-01-03",\n "2000-01-03",\n "NaT",\n "2000-01-02",\n "2000-01-05",\n "2000-01-04",\n ],\n dtype=dtype,\n )\n return arr\n\n def test_min_max(self, arr1d, unit):\n arr = arr1d\n arr = arr.as_unit(unit)\n tz = arr.tz\n\n result = arr.min()\n expected = pd.Timestamp("2000-01-02", tz=tz).as_unit(unit)\n assert result == expected\n assert result.unit == expected.unit\n\n result = arr.max()\n expected = pd.Timestamp("2000-01-05", tz=tz).as_unit(unit)\n assert result == expected\n assert result.unit == expected.unit\n\n result = arr.min(skipna=False)\n assert result is NaT\n\n result = arr.max(skipna=False)\n assert result is NaT\n\n @pytest.mark.parametrize("tz", [None, "US/Central"])\n @pytest.mark.parametrize("skipna", [True, False])\n def test_min_max_empty(self, skipna, tz):\n dtype = DatetimeTZDtype(tz=tz) if tz is not None else np.dtype("M8[ns]")\n arr = DatetimeArray._from_sequence([], dtype=dtype)\n result = arr.min(skipna=skipna)\n assert result is NaT\n\n result = arr.max(skipna=skipna)\n assert result is NaT\n\n @pytest.mark.parametrize("tz", [None, "US/Central"])\n @pytest.mark.parametrize("skipna", [True, False])\n def test_median_empty(self, skipna, tz):\n dtype = DatetimeTZDtype(tz=tz) if tz is not None else np.dtype("M8[ns]")\n arr = DatetimeArray._from_sequence([], dtype=dtype)\n result = arr.median(skipna=skipna)\n assert result is NaT\n\n arr = arr.reshape(0, 3)\n result = arr.median(axis=0, skipna=skipna)\n expected = type(arr)._from_sequence([NaT, NaT, NaT], dtype=arr.dtype)\n tm.assert_equal(result, expected)\n\n result = arr.median(axis=1, skipna=skipna)\n expected = type(arr)._from_sequence([], dtype=arr.dtype)\n tm.assert_equal(result, expected)\n\n def test_median(self, arr1d):\n arr = arr1d\n\n result = arr.median()\n assert result == arr[0]\n result = arr.median(skipna=False)\n assert result is NaT\n\n result = arr.dropna().median(skipna=False)\n assert result == arr[0]\n\n result = arr.median(axis=0)\n assert result == arr[0]\n\n def test_median_axis(self, arr1d):\n arr = arr1d\n assert arr.median(axis=0) == arr.median()\n assert arr.median(axis=0, skipna=False) is NaT\n\n msg = r"abs\(axis\) must be less than ndim"\n with pytest.raises(ValueError, match=msg):\n arr.median(axis=1)\n\n @pytest.mark.filterwarnings("ignore:All-NaN slice encountered:RuntimeWarning")\n def test_median_2d(self, arr1d):\n arr = arr1d.reshape(1, -1)\n\n # axis = None\n assert arr.median() == arr1d.median()\n assert arr.median(skipna=False) is NaT\n\n # axis = 0\n result = arr.median(axis=0)\n expected = arr1d\n tm.assert_equal(result, expected)\n\n # Since column 3 is all-NaT, we get NaT there with or without skipna\n result = arr.median(axis=0, skipna=False)\n expected = arr1d\n tm.assert_equal(result, expected)\n\n # axis = 1\n result = arr.median(axis=1)\n expected = type(arr)._from_sequence([arr1d.median()], dtype=arr.dtype)\n tm.assert_equal(result, expected)\n\n result = arr.median(axis=1, skipna=False)\n expected = type(arr)._from_sequence([NaT], dtype=arr.dtype)\n tm.assert_equal(result, expected)\n\n def test_mean(self, arr1d):\n arr = arr1d\n\n # manually verified result\n expected = arr[0] + 0.4 * pd.Timedelta(days=1)\n\n result = arr.mean()\n assert result == expected\n result = arr.mean(skipna=False)\n assert result is NaT\n\n result = arr.dropna().mean(skipna=False)\n assert result == expected\n\n result = arr.mean(axis=0)\n assert result == expected\n\n def test_mean_2d(self):\n dti = pd.date_range("2016-01-01", periods=6, tz="US/Pacific")\n dta = dti._data.reshape(3, 2)\n\n result = dta.mean(axis=0)\n expected = dta[1]\n tm.assert_datetime_array_equal(result, expected)\n\n result = dta.mean(axis=1)\n expected = dta[:, 0] + pd.Timedelta(hours=12)\n tm.assert_datetime_array_equal(result, expected)\n\n result = dta.mean(axis=None)\n expected = dti.mean()\n assert result == expected\n\n @pytest.mark.parametrize("skipna", [True, False])\n def test_mean_empty(self, arr1d, skipna):\n arr = arr1d[:0]\n\n assert arr.mean(skipna=skipna) is NaT\n\n arr2d = arr.reshape(0, 3)\n result = arr2d.mean(axis=0, skipna=skipna)\n expected = DatetimeArray._from_sequence([NaT, NaT, NaT], dtype=arr.dtype)\n tm.assert_datetime_array_equal(result, expected)\n\n result = arr2d.mean(axis=1, skipna=skipna)\n expected = arr # i.e. 1D, empty\n tm.assert_datetime_array_equal(result, expected)\n\n result = arr2d.mean(axis=None, skipna=skipna)\n assert result is NaT\n
.venv\Lib\site-packages\pandas\tests\arrays\datetimes\test_reductions.py
test_reductions.py
Python
5,787
0.95
0.081967
0.035211
python-kit
592
2024-02-01T19:36:35.653109
Apache-2.0
true
bdea9c982c2380e4115cd9f0b2b5aff8
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\datetimes\__pycache__\test_constructors.cpython-313.pyc
test_constructors.cpython-313.pyc
Other
19,217
0.95
0.006803
0
node-utils
721
2025-01-04T01:16:14.341362
Apache-2.0
true
55197002f87359c201f7625e07092d12
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\datetimes\__pycache__\test_cumulative.cpython-313.pyc
test_cumulative.cpython-313.pyc
Other
2,137
0.8
0
0
node-utils
375
2025-05-21T03:10:43.283468
Apache-2.0
true
22578c334232f23530ef2afa02d57877
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\datetimes\__pycache__\test_reductions.cpython-313.pyc
test_reductions.cpython-313.pyc
Other
9,469
0.8
0
0
react-lib
495
2025-06-27T04:48:58.221333
Apache-2.0
true
ee22c7c75841e99a4a827a1a52584177
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\datetimes\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
204
0.7
0
0
vue-tools
944
2024-12-21T23:14:52.349677
BSD-3-Clause
true
d049eb68291bf7ed954bb0fee3ffb9f8
import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas.core.arrays.floating import (\n Float32Dtype,\n Float64Dtype,\n)\n\n\n@pytest.fixture(params=[Float32Dtype, Float64Dtype])\ndef dtype(request):\n """Parametrized fixture returning a float 'dtype'"""\n return request.param()\n\n\n@pytest.fixture\ndef data(dtype):\n """Fixture returning 'data' array according to parametrized float 'dtype'"""\n return pd.array(\n list(np.arange(0.1, 0.9, 0.1))\n + [pd.NA]\n + list(np.arange(1, 9.8, 0.1))\n + [pd.NA]\n + [9.9, 10.0],\n dtype=dtype,\n )\n\n\n@pytest.fixture\ndef data_missing(dtype):\n """\n Fixture returning array with missing data according to parametrized float\n 'dtype'.\n """\n return pd.array([np.nan, 0.1], dtype=dtype)\n\n\n@pytest.fixture(params=["data", "data_missing"])\ndef all_data(request, data, data_missing):\n """Parametrized fixture returning 'data' or 'data_missing' float arrays.\n\n Used to test dtype conversion with and without missing values.\n """\n if request.param == "data":\n return data\n elif request.param == "data_missing":\n return data_missing\n
.venv\Lib\site-packages\pandas\tests\arrays\floating\conftest.py
conftest.py
Python
1,161
0.85
0.104167
0
vue-tools
881
2024-03-19T08:02:42.872121
MIT
true
2797818f5c59fc82ad065587a06acb7c
import operator\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.core.arrays import FloatingArray\n\n# Basic test for the arithmetic array ops\n# -----------------------------------------------------------------------------\n\n\n@pytest.mark.parametrize(\n "opname, exp",\n [\n ("add", [1.1, 2.2, None, None, 5.5]),\n ("mul", [0.1, 0.4, None, None, 2.5]),\n ("sub", [0.9, 1.8, None, None, 4.5]),\n ("truediv", [10.0, 10.0, None, None, 10.0]),\n ("floordiv", [9.0, 9.0, None, None, 10.0]),\n ("mod", [0.1, 0.2, None, None, 0.0]),\n ],\n ids=["add", "mul", "sub", "div", "floordiv", "mod"],\n)\ndef test_array_op(dtype, opname, exp):\n a = pd.array([1.0, 2.0, None, 4.0, 5.0], dtype=dtype)\n b = pd.array([0.1, 0.2, 0.3, None, 0.5], dtype=dtype)\n\n op = getattr(operator, opname)\n\n result = op(a, b)\n expected = pd.array(exp, dtype=dtype)\n tm.assert_extension_array_equal(result, expected)\n\n\n@pytest.mark.parametrize("zero, negative", [(0, False), (0.0, False), (-0.0, True)])\ndef test_divide_by_zero(dtype, zero, negative):\n # TODO pending NA/NaN discussion\n # https://github.com/pandas-dev/pandas/issues/32265/\n a = pd.array([0, 1, -1, None], dtype=dtype)\n result = a / zero\n expected = FloatingArray(\n np.array([np.nan, np.inf, -np.inf, np.nan], dtype=dtype.numpy_dtype),\n np.array([False, False, False, True]),\n )\n if negative:\n expected *= -1\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_pow_scalar(dtype):\n a = pd.array([-1, 0, 1, None, 2], dtype=dtype)\n result = a**0\n expected = pd.array([1, 1, 1, 1, 1], dtype=dtype)\n tm.assert_extension_array_equal(result, expected)\n\n result = a**1\n expected = pd.array([-1, 0, 1, None, 2], dtype=dtype)\n tm.assert_extension_array_equal(result, expected)\n\n result = a**pd.NA\n expected = pd.array([None, None, 1, None, None], dtype=dtype)\n tm.assert_extension_array_equal(result, expected)\n\n result = a**np.nan\n # TODO np.nan should be converted to pd.NA / missing before operation?\n expected = FloatingArray(\n np.array([np.nan, np.nan, 1, np.nan, np.nan], dtype=dtype.numpy_dtype),\n mask=a._mask,\n )\n tm.assert_extension_array_equal(result, expected)\n\n # reversed\n a = a[1:] # Can't raise integers to negative powers.\n\n result = 0**a\n expected = pd.array([1, 0, None, 0], dtype=dtype)\n tm.assert_extension_array_equal(result, expected)\n\n result = 1**a\n expected = pd.array([1, 1, 1, 1], dtype=dtype)\n tm.assert_extension_array_equal(result, expected)\n\n result = pd.NA**a\n expected = pd.array([1, None, None, None], dtype=dtype)\n tm.assert_extension_array_equal(result, expected)\n\n result = np.nan**a\n expected = FloatingArray(\n np.array([1, np.nan, np.nan, np.nan], dtype=dtype.numpy_dtype), mask=a._mask\n )\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_pow_array(dtype):\n a = pd.array([0, 0, 0, 1, 1, 1, None, None, None], dtype=dtype)\n b = pd.array([0, 1, None, 0, 1, None, 0, 1, None], dtype=dtype)\n result = a**b\n expected = pd.array([1, 0, None, 1, 1, 1, 1, None, None], dtype=dtype)\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_rpow_one_to_na():\n # https://github.com/pandas-dev/pandas/issues/22022\n # https://github.com/pandas-dev/pandas/issues/29997\n arr = pd.array([np.nan, np.nan], dtype="Float64")\n result = np.array([1.0, 2.0]) ** arr\n expected = pd.array([1.0, np.nan], dtype="Float64")\n tm.assert_extension_array_equal(result, expected)\n\n\n@pytest.mark.parametrize("other", [0, 0.5])\ndef test_arith_zero_dim_ndarray(other):\n arr = pd.array([1, None, 2], dtype="Float64")\n result = arr + np.array(other)\n expected = arr + other\n tm.assert_equal(result, expected)\n\n\n# Test generic characteristics / errors\n# -----------------------------------------------------------------------------\n\n\ndef test_error_invalid_values(data, all_arithmetic_operators):\n op = all_arithmetic_operators\n s = pd.Series(data)\n ops = getattr(s, op)\n\n # invalid scalars\n msg = "|".join(\n [\n r"can only perform ops with numeric values",\n r"FloatingArray cannot perform the operation mod",\n "unsupported operand type",\n "not all arguments converted during string formatting",\n "can't multiply sequence by non-int of type 'float'",\n "ufunc 'subtract' cannot use operands with types dtype",\n r"can only concatenate str \(not \"float\"\) to str",\n "ufunc '.*' not supported for the input types, and the inputs could not",\n "ufunc '.*' did not contain a loop with signature matching types",\n "Concatenation operation is not implemented for NumPy arrays",\n "has no kernel",\n "not implemented",\n "not supported for dtype",\n "Can only string multiply by an integer",\n ]\n )\n with pytest.raises(TypeError, match=msg):\n ops("foo")\n with pytest.raises(TypeError, match=msg):\n ops(pd.Timestamp("20180101"))\n\n # invalid array-likes\n with pytest.raises(TypeError, match=msg):\n ops(pd.Series("foo", index=s.index))\n\n msg = "|".join(\n [\n "can only perform ops with numeric values",\n "cannot perform .* with this index type: DatetimeArray",\n "Addition/subtraction of integers and integer-arrays "\n "with DatetimeArray is no longer supported. *",\n "unsupported operand type",\n "not all arguments converted during string formatting",\n "can't multiply sequence by non-int of type 'float'",\n "ufunc 'subtract' cannot use operands with types dtype",\n (\n "ufunc 'add' cannot use operands with types "\n rf"dtype\('{tm.ENDIAN}M8\[ns\]'\)"\n ),\n r"ufunc 'add' cannot use operands with types dtype\('float\d{2}'\)",\n "cannot subtract DatetimeArray from ndarray",\n "has no kernel",\n "not implemented",\n "not supported for dtype",\n ]\n )\n with pytest.raises(TypeError, match=msg):\n ops(pd.Series(pd.date_range("20180101", periods=len(s))))\n\n\n# Various\n# -----------------------------------------------------------------------------\n\n\ndef test_cross_type_arithmetic():\n df = pd.DataFrame(\n {\n "A": pd.array([1, 2, np.nan], dtype="Float64"),\n "B": pd.array([1, np.nan, 3], dtype="Float32"),\n "C": np.array([1, 2, 3], dtype="float64"),\n }\n )\n\n result = df.A + df.C\n expected = pd.Series([2, 4, np.nan], dtype="Float64")\n tm.assert_series_equal(result, expected)\n\n result = (df.A + df.C) * 3 == 12\n expected = pd.Series([False, True, None], dtype="boolean")\n tm.assert_series_equal(result, expected)\n\n result = df.A + df.B\n expected = pd.Series([2, np.nan, np.nan], dtype="Float64")\n tm.assert_series_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "source, neg_target, abs_target",\n [\n ([1.1, 2.2, 3.3], [-1.1, -2.2, -3.3], [1.1, 2.2, 3.3]),\n ([1.1, 2.2, None], [-1.1, -2.2, None], [1.1, 2.2, None]),\n ([-1.1, 0.0, 1.1], [1.1, 0.0, -1.1], [1.1, 0.0, 1.1]),\n ],\n)\ndef test_unary_float_operators(float_ea_dtype, source, neg_target, abs_target):\n # GH38794\n dtype = float_ea_dtype\n arr = pd.array(source, dtype=dtype)\n neg_result, pos_result, abs_result = -arr, +arr, abs(arr)\n neg_target = pd.array(neg_target, dtype=dtype)\n abs_target = pd.array(abs_target, dtype=dtype)\n\n tm.assert_extension_array_equal(neg_result, neg_target)\n tm.assert_extension_array_equal(pos_result, arr)\n assert not tm.shares_memory(pos_result, arr)\n tm.assert_extension_array_equal(abs_result, abs_target)\n\n\ndef test_bitwise(dtype):\n left = pd.array([1, None, 3, 4], dtype=dtype)\n right = pd.array([None, 3, 5, 4], dtype=dtype)\n\n with pytest.raises(TypeError, match="unsupported operand type"):\n left | right\n with pytest.raises(TypeError, match="unsupported operand type"):\n left & right\n with pytest.raises(TypeError, match="unsupported operand type"):\n left ^ right\n
.venv\Lib\site-packages\pandas\tests\arrays\floating\test_arithmetic.py
test_arithmetic.py
Python
8,311
0.95
0.066667
0.076923
awesome-app
193
2023-12-18T19:53:19.057800
BSD-3-Clause
true
ae3bc977c554f0ec3df07ca9db4a82cc
import numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\n\n\ndef test_astype():\n # with missing values\n arr = pd.array([0.1, 0.2, None], dtype="Float64")\n\n with pytest.raises(ValueError, match="cannot convert NA to integer"):\n arr.astype("int64")\n\n with pytest.raises(ValueError, match="cannot convert float NaN to bool"):\n arr.astype("bool")\n\n result = arr.astype("float64")\n expected = np.array([0.1, 0.2, np.nan], dtype="float64")\n tm.assert_numpy_array_equal(result, expected)\n\n # no missing values\n arr = pd.array([0.0, 1.0, 0.5], dtype="Float64")\n result = arr.astype("int64")\n expected = np.array([0, 1, 0], dtype="int64")\n tm.assert_numpy_array_equal(result, expected)\n\n result = arr.astype("bool")\n expected = np.array([False, True, True], dtype="bool")\n tm.assert_numpy_array_equal(result, expected)\n\n\ndef test_astype_to_floating_array():\n # astype to FloatingArray\n arr = pd.array([0.0, 1.0, None], dtype="Float64")\n\n result = arr.astype("Float64")\n tm.assert_extension_array_equal(result, arr)\n result = arr.astype(pd.Float64Dtype())\n tm.assert_extension_array_equal(result, arr)\n result = arr.astype("Float32")\n expected = pd.array([0.0, 1.0, None], dtype="Float32")\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_astype_to_boolean_array():\n # astype to BooleanArray\n arr = pd.array([0.0, 1.0, None], dtype="Float64")\n\n result = arr.astype("boolean")\n expected = pd.array([False, True, None], dtype="boolean")\n tm.assert_extension_array_equal(result, expected)\n result = arr.astype(pd.BooleanDtype())\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_astype_to_integer_array():\n # astype to IntegerArray\n arr = pd.array([0.0, 1.5, None], dtype="Float64")\n\n result = arr.astype("Int64")\n expected = pd.array([0, 1, None], dtype="Int64")\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_astype_str(using_infer_string):\n a = pd.array([0.1, 0.2, None], dtype="Float64")\n\n if using_infer_string:\n expected = pd.array(["0.1", "0.2", None], dtype=pd.StringDtype(na_value=np.nan))\n\n tm.assert_extension_array_equal(a.astype(str), expected)\n tm.assert_extension_array_equal(a.astype("str"), expected)\n else:\n expected = np.array(["0.1", "0.2", "<NA>"], dtype="U32")\n\n tm.assert_numpy_array_equal(a.astype(str), expected)\n tm.assert_numpy_array_equal(a.astype("str"), expected)\n\n\ndef test_astype_copy():\n arr = pd.array([0.1, 0.2, None], dtype="Float64")\n orig = pd.array([0.1, 0.2, None], dtype="Float64")\n\n # copy=True -> ensure both data and mask are actual copies\n result = arr.astype("Float64", copy=True)\n assert result is not arr\n assert not tm.shares_memory(result, arr)\n result[0] = 10\n tm.assert_extension_array_equal(arr, orig)\n result[0] = pd.NA\n tm.assert_extension_array_equal(arr, orig)\n\n # copy=False\n result = arr.astype("Float64", copy=False)\n assert result is arr\n assert np.shares_memory(result._data, arr._data)\n assert np.shares_memory(result._mask, arr._mask)\n result[0] = 10\n assert arr[0] == 10\n result[0] = pd.NA\n assert arr[0] is pd.NA\n\n # astype to different dtype -> always needs a copy -> even with copy=False\n # we need to ensure that also the mask is actually copied\n arr = pd.array([0.1, 0.2, None], dtype="Float64")\n orig = pd.array([0.1, 0.2, None], dtype="Float64")\n\n result = arr.astype("Float32", copy=False)\n assert not tm.shares_memory(result, arr)\n result[0] = 10\n tm.assert_extension_array_equal(arr, orig)\n result[0] = pd.NA\n tm.assert_extension_array_equal(arr, orig)\n\n\ndef test_astype_object(dtype):\n arr = pd.array([1.0, pd.NA], dtype=dtype)\n\n result = arr.astype(object)\n expected = np.array([1.0, pd.NA], dtype=object)\n tm.assert_numpy_array_equal(result, expected)\n # check exact element types\n assert isinstance(result[0], float)\n assert result[1] is pd.NA\n\n\ndef test_Float64_conversion():\n # GH#40729\n testseries = pd.Series(["1", "2", "3", "4"], dtype="object")\n result = testseries.astype(pd.Float64Dtype())\n\n expected = pd.Series([1.0, 2.0, 3.0, 4.0], dtype=pd.Float64Dtype())\n\n tm.assert_series_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\arrays\floating\test_astype.py
test_astype.py
Python
4,337
0.95
0.066667
0.11
awesome-app
484
2023-07-31T06:17:48.227644
MIT
true
6397e01d27623f59eb06e0a461699614
import numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.core.arrays import FloatingArray\nfrom pandas.tests.arrays.masked_shared import (\n ComparisonOps,\n NumericOps,\n)\n\n\nclass TestComparisonOps(NumericOps, ComparisonOps):\n @pytest.mark.parametrize("other", [True, False, pd.NA, -1.0, 0.0, 1])\n def test_scalar(self, other, comparison_op, dtype):\n ComparisonOps.test_scalar(self, other, comparison_op, dtype)\n\n def test_compare_with_integerarray(self, comparison_op):\n op = comparison_op\n a = pd.array([0, 1, None] * 3, dtype="Int64")\n b = pd.array([0] * 3 + [1] * 3 + [None] * 3, dtype="Float64")\n other = b.astype("Int64")\n expected = op(a, other)\n result = op(a, b)\n tm.assert_extension_array_equal(result, expected)\n expected = op(other, a)\n result = op(b, a)\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_equals():\n # GH-30652\n # equals is generally tested in /tests/extension/base/methods, but this\n # specifically tests that two arrays of the same class but different dtype\n # do not evaluate equal\n a1 = pd.array([1, 2, None], dtype="Float64")\n a2 = pd.array([1, 2, None], dtype="Float32")\n assert a1.equals(a2) is False\n\n\ndef test_equals_nan_vs_na():\n # GH#44382\n\n mask = np.zeros(3, dtype=bool)\n data = np.array([1.0, np.nan, 3.0], dtype=np.float64)\n\n left = FloatingArray(data, mask)\n assert left.equals(left)\n tm.assert_extension_array_equal(left, left)\n\n assert left.equals(left.copy())\n assert left.equals(FloatingArray(data.copy(), mask.copy()))\n\n mask2 = np.array([False, True, False], dtype=bool)\n data2 = np.array([1.0, 2.0, 3.0], dtype=np.float64)\n right = FloatingArray(data2, mask2)\n assert right.equals(right)\n tm.assert_extension_array_equal(right, right)\n\n assert not left.equals(right)\n\n # with mask[1] = True, the only difference is data[1], which should\n # not matter for equals\n mask[1] = True\n assert left.equals(right)\n
.venv\Lib\site-packages\pandas\tests\arrays\floating\test_comparison.py
test_comparison.py
Python
2,071
0.95
0.107692
0.137255
vue-tools
247
2024-11-20T00:48:43.141979
MIT
true
f42df0da80390a1863d3bafdd1484a29
import pytest\n\nimport pandas as pd\nimport pandas._testing as tm\n\n\n@pytest.mark.parametrize(\n "to_concat_dtypes, result_dtype",\n [\n (["Float64", "Float64"], "Float64"),\n (["Float32", "Float64"], "Float64"),\n (["Float32", "Float32"], "Float32"),\n ],\n)\ndef test_concat_series(to_concat_dtypes, result_dtype):\n result = pd.concat([pd.Series([1, 2, pd.NA], dtype=t) for t in to_concat_dtypes])\n expected = pd.concat([pd.Series([1, 2, pd.NA], dtype=object)] * 2).astype(\n result_dtype\n )\n tm.assert_series_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\arrays\floating\test_concat.py
test_concat.py
Python
573
0.85
0.1
0
react-lib
918
2024-03-17T16:08:33.838377
MIT
true
f6199e21665fdf9ddce461442d020e33
import numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.core.arrays import FloatingArray\nfrom pandas.core.arrays.floating import (\n Float32Dtype,\n Float64Dtype,\n)\n\n\ndef test_uses_pandas_na():\n a = pd.array([1, None], dtype=Float64Dtype())\n assert a[1] is pd.NA\n\n\ndef test_floating_array_constructor():\n values = np.array([1, 2, 3, 4], dtype="float64")\n mask = np.array([False, False, False, True], dtype="bool")\n\n result = FloatingArray(values, mask)\n expected = pd.array([1, 2, 3, np.nan], dtype="Float64")\n tm.assert_extension_array_equal(result, expected)\n tm.assert_numpy_array_equal(result._data, values)\n tm.assert_numpy_array_equal(result._mask, mask)\n\n msg = r".* should be .* numpy array. Use the 'pd.array' function instead"\n with pytest.raises(TypeError, match=msg):\n FloatingArray(values.tolist(), mask)\n\n with pytest.raises(TypeError, match=msg):\n FloatingArray(values, mask.tolist())\n\n with pytest.raises(TypeError, match=msg):\n FloatingArray(values.astype(int), mask)\n\n msg = r"__init__\(\) missing 1 required positional argument: 'mask'"\n with pytest.raises(TypeError, match=msg):\n FloatingArray(values)\n\n\ndef test_floating_array_disallows_float16():\n # GH#44715\n arr = np.array([1, 2], dtype=np.float16)\n mask = np.array([False, False])\n\n msg = "FloatingArray does not support np.float16 dtype"\n with pytest.raises(TypeError, match=msg):\n FloatingArray(arr, mask)\n\n\ndef test_floating_array_disallows_Float16_dtype(request):\n # GH#44715\n with pytest.raises(TypeError, match="data type 'Float16' not understood"):\n pd.array([1.0, 2.0], dtype="Float16")\n\n\ndef test_floating_array_constructor_copy():\n values = np.array([1, 2, 3, 4], dtype="float64")\n mask = np.array([False, False, False, True], dtype="bool")\n\n result = FloatingArray(values, mask)\n assert result._data is values\n assert result._mask is mask\n\n result = FloatingArray(values, mask, copy=True)\n assert result._data is not values\n assert result._mask is not mask\n\n\ndef test_to_array():\n result = pd.array([0.1, 0.2, 0.3, 0.4])\n expected = pd.array([0.1, 0.2, 0.3, 0.4], dtype="Float64")\n tm.assert_extension_array_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "a, b",\n [\n ([1, None], [1, pd.NA]),\n ([None], [pd.NA]),\n ([None, np.nan], [pd.NA, pd.NA]),\n ([1, np.nan], [1, pd.NA]),\n ([np.nan], [pd.NA]),\n ],\n)\ndef test_to_array_none_is_nan(a, b):\n result = pd.array(a, dtype="Float64")\n expected = pd.array(b, dtype="Float64")\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_to_array_mixed_integer_float():\n result = pd.array([1, 2.0])\n expected = pd.array([1.0, 2.0], dtype="Float64")\n tm.assert_extension_array_equal(result, expected)\n\n result = pd.array([1, None, 2.0])\n expected = pd.array([1.0, None, 2.0], dtype="Float64")\n tm.assert_extension_array_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "values",\n [\n ["foo", "bar"],\n "foo",\n 1,\n 1.0,\n pd.date_range("20130101", periods=2),\n np.array(["foo"]),\n [[1, 2], [3, 4]],\n [np.nan, {"a": 1}],\n # GH#44514 all-NA case used to get quietly swapped out before checking ndim\n np.array([pd.NA] * 6, dtype=object).reshape(3, 2),\n ],\n)\ndef test_to_array_error(values):\n # error in converting existing arrays to FloatingArray\n msg = "|".join(\n [\n "cannot be converted to FloatingDtype",\n "values must be a 1D list-like",\n "Cannot pass scalar",\n r"float\(\) argument must be a string or a (real )?number, not 'dict'",\n "could not convert string to float: 'foo'",\n r"could not convert string to float: np\.str_\('foo'\)",\n ]\n )\n with pytest.raises((TypeError, ValueError), match=msg):\n pd.array(values, dtype="Float64")\n\n\n@pytest.mark.parametrize("values", [["1", "2", None], ["1.5", "2", None]])\ndef test_construct_from_float_strings(values):\n # see also test_to_integer_array_str\n expected = pd.array([float(values[0]), 2, None], dtype="Float64")\n\n res = pd.array(values, dtype="Float64")\n tm.assert_extension_array_equal(res, expected)\n\n res = FloatingArray._from_sequence(values)\n tm.assert_extension_array_equal(res, expected)\n\n\ndef test_to_array_inferred_dtype():\n # if values has dtype -> respect it\n result = pd.array(np.array([1, 2], dtype="float32"))\n assert result.dtype == Float32Dtype()\n\n # if values have no dtype -> always float64\n result = pd.array([1.0, 2.0])\n assert result.dtype == Float64Dtype()\n\n\ndef test_to_array_dtype_keyword():\n result = pd.array([1, 2], dtype="Float32")\n assert result.dtype == Float32Dtype()\n\n # if values has dtype -> override it\n result = pd.array(np.array([1, 2], dtype="float32"), dtype="Float64")\n assert result.dtype == Float64Dtype()\n\n\ndef test_to_array_integer():\n result = pd.array([1, 2], dtype="Float64")\n expected = pd.array([1.0, 2.0], dtype="Float64")\n tm.assert_extension_array_equal(result, expected)\n\n # for integer dtypes, the itemsize is not preserved\n # TODO can we specify "floating" in general?\n result = pd.array(np.array([1, 2], dtype="int32"), dtype="Float64")\n assert result.dtype == Float64Dtype()\n\n\n@pytest.mark.parametrize(\n "bool_values, values, target_dtype, expected_dtype",\n [\n ([False, True], [0, 1], Float64Dtype(), Float64Dtype()),\n ([False, True], [0, 1], "Float64", Float64Dtype()),\n ([False, True, np.nan], [0, 1, np.nan], Float64Dtype(), Float64Dtype()),\n ],\n)\ndef test_to_array_bool(bool_values, values, target_dtype, expected_dtype):\n result = pd.array(bool_values, dtype=target_dtype)\n assert result.dtype == expected_dtype\n expected = pd.array(values, dtype=target_dtype)\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_series_from_float(data):\n # construct from our dtype & string dtype\n dtype = data.dtype\n\n # from float\n expected = pd.Series(data)\n result = pd.Series(data.to_numpy(na_value=np.nan, dtype="float"), dtype=str(dtype))\n tm.assert_series_equal(result, expected)\n\n # from list\n expected = pd.Series(data)\n result = pd.Series(np.array(data).tolist(), dtype=str(dtype))\n tm.assert_series_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\arrays\floating\test_construction.py
test_construction.py
Python
6,455
0.95
0.098039
0.082803
react-lib
453
2024-07-26T16:29:11.874449
GPL-3.0
true
c5f8136cbf34c3260a786c96371d5ee0
import numpy as np\n\nimport pandas as pd\n\n\ndef test_contains_nan():\n # GH#52840\n arr = pd.array(range(5)) / 0\n\n assert np.isnan(arr._data[0])\n assert not arr.isna()[0]\n assert np.nan in arr\n
.venv\Lib\site-packages\pandas\tests\arrays\floating\test_contains.py
test_contains.py
Python
204
0.95
0.083333
0.125
react-lib
634
2024-10-11T00:42:04.105709
MIT
true
69a515340054ad67830858281655a5f1
import numpy as np\nimport pytest\n\nfrom pandas.compat import IS64\n\nimport pandas as pd\nimport pandas._testing as tm\n\n\n@pytest.mark.parametrize("ufunc", [np.abs, np.sign])\n# np.sign emits a warning with nans, <https://github.com/numpy/numpy/issues/15127>\n@pytest.mark.filterwarnings("ignore:invalid value encountered in sign:RuntimeWarning")\ndef test_ufuncs_single(ufunc):\n a = pd.array([1, 2, -3, np.nan], dtype="Float64")\n result = ufunc(a)\n expected = pd.array(ufunc(a.astype(float)), dtype="Float64")\n tm.assert_extension_array_equal(result, expected)\n\n s = pd.Series(a)\n result = ufunc(s)\n expected = pd.Series(expected)\n tm.assert_series_equal(result, expected)\n\n\n@pytest.mark.parametrize("ufunc", [np.log, np.exp, np.sin, np.cos, np.sqrt])\ndef test_ufuncs_single_float(ufunc):\n a = pd.array([1.0, 0.2, 3.0, np.nan], dtype="Float64")\n with np.errstate(invalid="ignore"):\n result = ufunc(a)\n expected = pd.array(ufunc(a.astype(float)), dtype="Float64")\n tm.assert_extension_array_equal(result, expected)\n\n s = pd.Series(a)\n with np.errstate(invalid="ignore"):\n result = ufunc(s)\n expected = pd.Series(ufunc(s.astype(float)), dtype="Float64")\n tm.assert_series_equal(result, expected)\n\n\n@pytest.mark.parametrize("ufunc", [np.add, np.subtract])\ndef test_ufuncs_binary_float(ufunc):\n # two FloatingArrays\n a = pd.array([1, 0.2, -3, np.nan], dtype="Float64")\n result = ufunc(a, a)\n expected = pd.array(ufunc(a.astype(float), a.astype(float)), dtype="Float64")\n tm.assert_extension_array_equal(result, expected)\n\n # FloatingArray with numpy array\n arr = np.array([1, 2, 3, 4])\n result = ufunc(a, arr)\n expected = pd.array(ufunc(a.astype(float), arr), dtype="Float64")\n tm.assert_extension_array_equal(result, expected)\n\n result = ufunc(arr, a)\n expected = pd.array(ufunc(arr, a.astype(float)), dtype="Float64")\n tm.assert_extension_array_equal(result, expected)\n\n # FloatingArray with scalar\n result = ufunc(a, 1)\n expected = pd.array(ufunc(a.astype(float), 1), dtype="Float64")\n tm.assert_extension_array_equal(result, expected)\n\n result = ufunc(1, a)\n expected = pd.array(ufunc(1, a.astype(float)), dtype="Float64")\n tm.assert_extension_array_equal(result, expected)\n\n\n@pytest.mark.parametrize("values", [[0, 1], [0, None]])\ndef test_ufunc_reduce_raises(values):\n arr = pd.array(values, dtype="Float64")\n\n res = np.add.reduce(arr)\n expected = arr.sum(skipna=False)\n tm.assert_almost_equal(res, expected)\n\n\n@pytest.mark.skipif(not IS64, reason="GH 36579: fail on 32-bit system")\n@pytest.mark.parametrize(\n "pandasmethname, kwargs",\n [\n ("var", {"ddof": 0}),\n ("var", {"ddof": 1}),\n ("std", {"ddof": 0}),\n ("std", {"ddof": 1}),\n ("kurtosis", {}),\n ("skew", {}),\n ("sem", {}),\n ],\n)\ndef test_stat_method(pandasmethname, kwargs):\n s = pd.Series(data=[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, np.nan, np.nan], dtype="Float64")\n pandasmeth = getattr(s, pandasmethname)\n result = pandasmeth(**kwargs)\n s2 = pd.Series(data=[0.1, 0.2, 0.3, 0.4, 0.5, 0.6], dtype="float64")\n pandasmeth = getattr(s2, pandasmethname)\n expected = pandasmeth(**kwargs)\n assert expected == result\n\n\ndef test_value_counts_na():\n arr = pd.array([0.1, 0.2, 0.1, pd.NA], dtype="Float64")\n result = arr.value_counts(dropna=False)\n idx = pd.Index([0.1, 0.2, pd.NA], dtype=arr.dtype)\n assert idx.dtype == arr.dtype\n expected = pd.Series([2, 1, 1], index=idx, dtype="Int64", name="count")\n tm.assert_series_equal(result, expected)\n\n result = arr.value_counts(dropna=True)\n expected = pd.Series([2, 1], index=idx[:-1], dtype="Int64", name="count")\n tm.assert_series_equal(result, expected)\n\n\ndef test_value_counts_empty():\n ser = pd.Series([], dtype="Float64")\n result = ser.value_counts()\n idx = pd.Index([], dtype="Float64")\n assert idx.dtype == "Float64"\n expected = pd.Series([], index=idx, dtype="Int64", name="count")\n tm.assert_series_equal(result, expected)\n\n\ndef test_value_counts_with_normalize():\n ser = pd.Series([0.1, 0.2, 0.1, pd.NA], dtype="Float64")\n result = ser.value_counts(normalize=True)\n expected = pd.Series([2, 1], index=ser[:2], dtype="Float64", name="proportion") / 3\n assert expected.index.dtype == ser.dtype\n tm.assert_series_equal(result, expected)\n\n\n@pytest.mark.parametrize("skipna", [True, False])\n@pytest.mark.parametrize("min_count", [0, 4])\ndef test_floating_array_sum(skipna, min_count, dtype):\n arr = pd.array([1, 2, 3, None], dtype=dtype)\n result = arr.sum(skipna=skipna, min_count=min_count)\n if skipna and min_count == 0:\n assert result == 6.0\n else:\n assert result is pd.NA\n\n\n@pytest.mark.parametrize(\n "values, expected", [([1, 2, 3], 6.0), ([1, 2, 3, None], 6.0), ([None], 0.0)]\n)\ndef test_floating_array_numpy_sum(values, expected):\n arr = pd.array(values, dtype="Float64")\n result = np.sum(arr)\n assert result == expected\n\n\n@pytest.mark.parametrize("op", ["sum", "min", "max", "prod"])\ndef test_preserve_dtypes(op):\n df = pd.DataFrame(\n {\n "A": ["a", "b", "b"],\n "B": [1, None, 3],\n "C": pd.array([0.1, None, 3.0], dtype="Float64"),\n }\n )\n\n # op\n result = getattr(df.C, op)()\n assert isinstance(result, np.float64)\n\n # groupby\n result = getattr(df.groupby("A"), op)()\n\n expected = pd.DataFrame(\n {"B": np.array([1.0, 3.0]), "C": pd.array([0.1, 3], dtype="Float64")},\n index=pd.Index(["a", "b"], name="A"),\n )\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize("skipna", [True, False])\n@pytest.mark.parametrize("method", ["min", "max"])\ndef test_floating_array_min_max(skipna, method, dtype):\n arr = pd.array([0.0, 1.0, None], dtype=dtype)\n func = getattr(arr, method)\n result = func(skipna=skipna)\n if skipna:\n assert result == (0 if method == "min" else 1)\n else:\n assert result is pd.NA\n\n\n@pytest.mark.parametrize("skipna", [True, False])\n@pytest.mark.parametrize("min_count", [0, 9])\ndef test_floating_array_prod(skipna, min_count, dtype):\n arr = pd.array([1.0, 2.0, None], dtype=dtype)\n result = arr.prod(skipna=skipna, min_count=min_count)\n if skipna and min_count == 0:\n assert result == 2\n else:\n assert result is pd.NA\n
.venv\Lib\site-packages\pandas\tests\arrays\floating\test_function.py
test_function.py
Python
6,403
0.95
0.087629
0.03871
awesome-app
318
2025-03-10T01:39:15.691608
Apache-2.0
true
b78b52b7ecc075d3e58cfecdb1689e73
import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas.core.arrays.floating import (\n Float32Dtype,\n Float64Dtype,\n)\n\n\ndef test_dtypes(dtype):\n # smoke tests on auto dtype construction\n\n np.dtype(dtype.type).kind == "f"\n assert dtype.name is not None\n\n\n@pytest.mark.parametrize(\n "dtype, expected",\n [(Float32Dtype(), "Float32Dtype()"), (Float64Dtype(), "Float64Dtype()")],\n)\ndef test_repr_dtype(dtype, expected):\n assert repr(dtype) == expected\n\n\ndef test_repr_array():\n result = repr(pd.array([1.0, None, 3.0]))\n expected = "<FloatingArray>\n[1.0, <NA>, 3.0]\nLength: 3, dtype: Float64"\n assert result == expected\n\n\ndef test_repr_array_long():\n data = pd.array([1.0, 2.0, None] * 1000)\n expected = """<FloatingArray>\n[ 1.0, 2.0, <NA>, 1.0, 2.0, <NA>, 1.0, 2.0, <NA>, 1.0,\n ...\n <NA>, 1.0, 2.0, <NA>, 1.0, 2.0, <NA>, 1.0, 2.0, <NA>]\nLength: 3000, dtype: Float64"""\n result = repr(data)\n assert result == expected\n\n\ndef test_frame_repr(data_missing):\n df = pd.DataFrame({"A": data_missing})\n result = repr(df)\n expected = " A\n0 <NA>\n1 0.1"\n assert result == expected\n
.venv\Lib\site-packages\pandas\tests\arrays\floating\test_repr.py
test_repr.py
Python
1,157
0.95
0.106383
0.028571
node-utils
806
2023-07-28T05:19:21.158863
MIT
true
704762d48feded9c74006c09a601fa5b
import numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.core.arrays import FloatingArray\n\n\n@pytest.mark.parametrize("box", [True, False], ids=["series", "array"])\ndef test_to_numpy(box):\n con = pd.Series if box else pd.array\n\n # default (with or without missing values) -> object dtype\n arr = con([0.1, 0.2, 0.3], dtype="Float64")\n result = arr.to_numpy()\n expected = np.array([0.1, 0.2, 0.3], dtype="float64")\n tm.assert_numpy_array_equal(result, expected)\n\n arr = con([0.1, 0.2, None], dtype="Float64")\n result = arr.to_numpy()\n expected = np.array([0.1, 0.2, np.nan], dtype="float64")\n tm.assert_numpy_array_equal(result, expected)\n\n\n@pytest.mark.parametrize("box", [True, False], ids=["series", "array"])\ndef test_to_numpy_float(box):\n con = pd.Series if box else pd.array\n\n # no missing values -> can convert to float, otherwise raises\n arr = con([0.1, 0.2, 0.3], dtype="Float64")\n result = arr.to_numpy(dtype="float64")\n expected = np.array([0.1, 0.2, 0.3], dtype="float64")\n tm.assert_numpy_array_equal(result, expected)\n\n arr = con([0.1, 0.2, None], dtype="Float64")\n result = arr.to_numpy(dtype="float64")\n expected = np.array([0.1, 0.2, np.nan], dtype="float64")\n tm.assert_numpy_array_equal(result, expected)\n\n result = arr.to_numpy(dtype="float64", na_value=np.nan)\n expected = np.array([0.1, 0.2, np.nan], dtype="float64")\n tm.assert_numpy_array_equal(result, expected)\n\n\n@pytest.mark.parametrize("box", [True, False], ids=["series", "array"])\ndef test_to_numpy_int(box):\n con = pd.Series if box else pd.array\n\n # no missing values -> can convert to int, otherwise raises\n arr = con([1.0, 2.0, 3.0], dtype="Float64")\n result = arr.to_numpy(dtype="int64")\n expected = np.array([1, 2, 3], dtype="int64")\n tm.assert_numpy_array_equal(result, expected)\n\n arr = con([1.0, 2.0, None], dtype="Float64")\n with pytest.raises(ValueError, match="cannot convert to 'int64'-dtype"):\n result = arr.to_numpy(dtype="int64")\n\n # automatic casting (floors the values)\n arr = con([0.1, 0.9, 1.1], dtype="Float64")\n result = arr.to_numpy(dtype="int64")\n expected = np.array([0, 0, 1], dtype="int64")\n tm.assert_numpy_array_equal(result, expected)\n\n\n@pytest.mark.parametrize("box", [True, False], ids=["series", "array"])\ndef test_to_numpy_na_value(box):\n con = pd.Series if box else pd.array\n\n arr = con([0.0, 1.0, None], dtype="Float64")\n result = arr.to_numpy(dtype=object, na_value=None)\n expected = np.array([0.0, 1.0, None], dtype="object")\n tm.assert_numpy_array_equal(result, expected)\n\n result = arr.to_numpy(dtype=bool, na_value=False)\n expected = np.array([False, True, False], dtype="bool")\n tm.assert_numpy_array_equal(result, expected)\n\n result = arr.to_numpy(dtype="int64", na_value=-99)\n expected = np.array([0, 1, -99], dtype="int64")\n tm.assert_numpy_array_equal(result, expected)\n\n\ndef test_to_numpy_na_value_with_nan():\n # array with both NaN and NA -> only fill NA with `na_value`\n arr = FloatingArray(np.array([0.0, np.nan, 0.0]), np.array([False, False, True]))\n result = arr.to_numpy(dtype="float64", na_value=-1)\n expected = np.array([0.0, np.nan, -1.0], dtype="float64")\n tm.assert_numpy_array_equal(result, expected)\n\n\n@pytest.mark.parametrize("dtype", ["float64", "float32", "int32", "int64", "bool"])\n@pytest.mark.parametrize("box", [True, False], ids=["series", "array"])\ndef test_to_numpy_dtype(box, dtype):\n con = pd.Series if box else pd.array\n arr = con([0.0, 1.0], dtype="Float64")\n\n result = arr.to_numpy(dtype=dtype)\n expected = np.array([0, 1], dtype=dtype)\n tm.assert_numpy_array_equal(result, expected)\n\n\n@pytest.mark.parametrize("dtype", ["int32", "int64", "bool"])\n@pytest.mark.parametrize("box", [True, False], ids=["series", "array"])\ndef test_to_numpy_na_raises(box, dtype):\n con = pd.Series if box else pd.array\n arr = con([0.0, 1.0, None], dtype="Float64")\n with pytest.raises(ValueError, match=dtype):\n arr.to_numpy(dtype=dtype)\n\n\n@pytest.mark.parametrize("box", [True, False], ids=["series", "array"])\ndef test_to_numpy_string(box, dtype):\n con = pd.Series if box else pd.array\n arr = con([0.0, 1.0, None], dtype="Float64")\n\n result = arr.to_numpy(dtype="str")\n expected = np.array([0.0, 1.0, pd.NA], dtype=f"{tm.ENDIAN}U32")\n tm.assert_numpy_array_equal(result, expected)\n\n\ndef test_to_numpy_copy():\n # to_numpy can be zero-copy if no missing values\n arr = pd.array([0.1, 0.2, 0.3], dtype="Float64")\n result = arr.to_numpy(dtype="float64")\n result[0] = 10\n tm.assert_extension_array_equal(arr, pd.array([10, 0.2, 0.3], dtype="Float64"))\n\n arr = pd.array([0.1, 0.2, 0.3], dtype="Float64")\n result = arr.to_numpy(dtype="float64", copy=True)\n result[0] = 10\n tm.assert_extension_array_equal(arr, pd.array([0.1, 0.2, 0.3], dtype="Float64"))\n
.venv\Lib\site-packages\pandas\tests\arrays\floating\test_to_numpy.py
test_to_numpy.py
Python
4,954
0.95
0.128788
0.060606
react-lib
222
2024-10-19T00:15:37.800025
BSD-3-Clause
true
7d249378faea3d94406bfed210d848a5
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\floating\__pycache__\conftest.cpython-313.pyc
conftest.cpython-313.pyc
Other
2,142
0.8
0
0
python-kit
91
2023-10-10T11:07:50.792783
MIT
true
3d907f4766877edd1c5d903f7d4407f3
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\floating\__pycache__\test_arithmetic.cpython-313.pyc
test_arithmetic.cpython-313.pyc
Other
11,758
0.8
0.02439
0
react-lib
735
2025-01-02T19:58:58.537347
GPL-3.0
true
8a632fdf9e8b5006fdbf66b7aec24bf9
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\floating\__pycache__\test_astype.cpython-313.pyc
test_astype.cpython-313.pyc
Other
7,339
0.8
0
0.021978
python-kit
581
2023-08-10T19:26:25.347829
MIT
true
111835c153667d6f6b0879fb2d63a73b
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\floating\__pycache__\test_comparison.cpython-313.pyc
test_comparison.cpython-313.pyc
Other
3,683
0.8
0
0
react-lib
962
2024-07-16T12:20:59.907724
GPL-3.0
true
45f5b7bc54ee5049261f50e1849e3afa
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\floating\__pycache__\test_concat.cpython-313.pyc
test_concat.cpython-313.pyc
Other
1,287
0.7
0
0
vue-tools
718
2024-05-21T14:12:16.445483
Apache-2.0
true
57b4d88b7bc4900dcb9bda1736a2c195
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\floating\__pycache__\test_construction.cpython-313.pyc
test_construction.cpython-313.pyc
Other
11,105
0.95
0.007692
0
python-kit
464
2025-05-17T08:33:12.726429
GPL-3.0
true
53fe303e415afada42f65224f8c17cf6
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\floating\__pycache__\test_contains.cpython-313.pyc
test_contains.cpython-313.pyc
Other
758
0.7
0
0
python-kit
828
2024-11-30T11:29:34.314473
BSD-3-Clause
true
a57186aef6f3c183056676abeddcb6a8
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\floating\__pycache__\test_function.cpython-313.pyc
test_function.cpython-313.pyc
Other
11,968
0.95
0
0.008333
awesome-app
412
2024-10-31T14:10:46.160163
Apache-2.0
true
25dbba4af2b7588799b3681ba63eff1f
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\floating\__pycache__\test_repr.cpython-313.pyc
test_repr.cpython-313.pyc
Other
2,187
0.8
0
0
awesome-app
810
2025-02-03T21:11:14.553824
BSD-3-Clause
true
413c7ebe5c059a7c81923f84637f40e0
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\floating\__pycache__\test_to_numpy.cpython-313.pyc
test_to_numpy.cpython-313.pyc
Other
8,062
0.8
0
0.038095
awesome-app
98
2024-09-03T21:57:19.512204
Apache-2.0
true
f7f2c99e371f28288ec0ebdb30e3a9bc
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\floating\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
203
0.7
0
0
vue-tools
614
2023-11-27T21:52:23.077342
Apache-2.0
true
1f6ba3b3878fc2f6e4e983c84afda645
import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas.core.arrays.integer import (\n Int8Dtype,\n Int16Dtype,\n Int32Dtype,\n Int64Dtype,\n UInt8Dtype,\n UInt16Dtype,\n UInt32Dtype,\n UInt64Dtype,\n)\n\n\n@pytest.fixture(\n params=[\n Int8Dtype,\n Int16Dtype,\n Int32Dtype,\n Int64Dtype,\n UInt8Dtype,\n UInt16Dtype,\n UInt32Dtype,\n UInt64Dtype,\n ]\n)\ndef dtype(request):\n """Parametrized fixture returning integer 'dtype'"""\n return request.param()\n\n\n@pytest.fixture\ndef data(dtype):\n """\n Fixture returning 'data' array with valid and missing values according to\n parametrized integer 'dtype'.\n\n Used to test dtype conversion with and without missing values.\n """\n return pd.array(\n list(range(8)) + [np.nan] + list(range(10, 98)) + [np.nan] + [99, 100],\n dtype=dtype,\n )\n\n\n@pytest.fixture\ndef data_missing(dtype):\n """\n Fixture returning array with exactly one NaN and one valid integer,\n according to parametrized integer 'dtype'.\n\n Used to test dtype conversion with and without missing values.\n """\n return pd.array([np.nan, 1], dtype=dtype)\n\n\n@pytest.fixture(params=["data", "data_missing"])\ndef all_data(request, data, data_missing):\n """Parametrized fixture returning 'data' or 'data_missing' integer arrays.\n\n Used to test dtype conversion with and without missing values.\n """\n if request.param == "data":\n return data\n elif request.param == "data_missing":\n return data_missing\n
.venv\Lib\site-packages\pandas\tests\arrays\integer\conftest.py
conftest.py
Python
1,555
0.85
0.073529
0
react-lib
601
2025-06-15T12:54:57.166684
BSD-3-Clause
true
060c201380d99dee842b979944b1adc3
import operator\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.core import ops\nfrom pandas.core.arrays import FloatingArray\n\n# Basic test for the arithmetic array ops\n# -----------------------------------------------------------------------------\n\n\n@pytest.mark.parametrize(\n "opname, exp",\n [("add", [1, 3, None, None, 9]), ("mul", [0, 2, None, None, 20])],\n ids=["add", "mul"],\n)\ndef test_add_mul(dtype, opname, exp):\n a = pd.array([0, 1, None, 3, 4], dtype=dtype)\n b = pd.array([1, 2, 3, None, 5], dtype=dtype)\n\n # array / array\n expected = pd.array(exp, dtype=dtype)\n\n op = getattr(operator, opname)\n result = op(a, b)\n tm.assert_extension_array_equal(result, expected)\n\n op = getattr(ops, "r" + opname)\n result = op(a, b)\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_sub(dtype):\n a = pd.array([1, 2, 3, None, 5], dtype=dtype)\n b = pd.array([0, 1, None, 3, 4], dtype=dtype)\n\n result = a - b\n expected = pd.array([1, 1, None, None, 1], dtype=dtype)\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_div(dtype):\n a = pd.array([1, 2, 3, None, 5], dtype=dtype)\n b = pd.array([0, 1, None, 3, 4], dtype=dtype)\n\n result = a / b\n expected = pd.array([np.inf, 2, None, None, 1.25], dtype="Float64")\n tm.assert_extension_array_equal(result, expected)\n\n\n@pytest.mark.parametrize("zero, negative", [(0, False), (0.0, False), (-0.0, True)])\ndef test_divide_by_zero(zero, negative):\n # https://github.com/pandas-dev/pandas/issues/27398, GH#22793\n a = pd.array([0, 1, -1, None], dtype="Int64")\n result = a / zero\n expected = FloatingArray(\n np.array([np.nan, np.inf, -np.inf, 1], dtype="float64"),\n np.array([False, False, False, True]),\n )\n if negative:\n expected *= -1\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_floordiv(dtype):\n a = pd.array([1, 2, 3, None, 5], dtype=dtype)\n b = pd.array([0, 1, None, 3, 4], dtype=dtype)\n\n result = a // b\n # Series op sets 1//0 to np.inf, which IntegerArray does not do (yet)\n expected = pd.array([0, 2, None, None, 1], dtype=dtype)\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_floordiv_by_int_zero_no_mask(any_int_ea_dtype):\n # GH 48223: Aligns with non-masked floordiv\n # but differs from numpy\n # https://github.com/pandas-dev/pandas/issues/30188#issuecomment-564452740\n ser = pd.Series([0, 1], dtype=any_int_ea_dtype)\n result = 1 // ser\n expected = pd.Series([np.inf, 1.0], dtype="Float64")\n tm.assert_series_equal(result, expected)\n\n ser_non_nullable = ser.astype(ser.dtype.numpy_dtype)\n result = 1 // ser_non_nullable\n expected = expected.astype(np.float64)\n tm.assert_series_equal(result, expected)\n\n\ndef test_mod(dtype):\n a = pd.array([1, 2, 3, None, 5], dtype=dtype)\n b = pd.array([0, 1, None, 3, 4], dtype=dtype)\n\n result = a % b\n expected = pd.array([0, 0, None, None, 1], dtype=dtype)\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_pow_scalar():\n a = pd.array([-1, 0, 1, None, 2], dtype="Int64")\n result = a**0\n expected = pd.array([1, 1, 1, 1, 1], dtype="Int64")\n tm.assert_extension_array_equal(result, expected)\n\n result = a**1\n expected = pd.array([-1, 0, 1, None, 2], dtype="Int64")\n tm.assert_extension_array_equal(result, expected)\n\n result = a**pd.NA\n expected = pd.array([None, None, 1, None, None], dtype="Int64")\n tm.assert_extension_array_equal(result, expected)\n\n result = a**np.nan\n expected = FloatingArray(\n np.array([np.nan, np.nan, 1, np.nan, np.nan], dtype="float64"),\n np.array([False, False, False, True, False]),\n )\n tm.assert_extension_array_equal(result, expected)\n\n # reversed\n a = a[1:] # Can't raise integers to negative powers.\n\n result = 0**a\n expected = pd.array([1, 0, None, 0], dtype="Int64")\n tm.assert_extension_array_equal(result, expected)\n\n result = 1**a\n expected = pd.array([1, 1, 1, 1], dtype="Int64")\n tm.assert_extension_array_equal(result, expected)\n\n result = pd.NA**a\n expected = pd.array([1, None, None, None], dtype="Int64")\n tm.assert_extension_array_equal(result, expected)\n\n result = np.nan**a\n expected = FloatingArray(\n np.array([1, np.nan, np.nan, np.nan], dtype="float64"),\n np.array([False, False, True, False]),\n )\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_pow_array():\n a = pd.array([0, 0, 0, 1, 1, 1, None, None, None])\n b = pd.array([0, 1, None, 0, 1, None, 0, 1, None])\n result = a**b\n expected = pd.array([1, 0, None, 1, 1, 1, 1, None, None])\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_rpow_one_to_na():\n # https://github.com/pandas-dev/pandas/issues/22022\n # https://github.com/pandas-dev/pandas/issues/29997\n arr = pd.array([np.nan, np.nan], dtype="Int64")\n result = np.array([1.0, 2.0]) ** arr\n expected = pd.array([1.0, np.nan], dtype="Float64")\n tm.assert_extension_array_equal(result, expected)\n\n\n@pytest.mark.parametrize("other", [0, 0.5])\ndef test_numpy_zero_dim_ndarray(other):\n arr = pd.array([1, None, 2])\n result = arr + np.array(other)\n expected = arr + other\n tm.assert_equal(result, expected)\n\n\n# Test generic characteristics / errors\n# -----------------------------------------------------------------------------\n\n\ndef test_error_invalid_values(data, all_arithmetic_operators):\n op = all_arithmetic_operators\n s = pd.Series(data)\n ops = getattr(s, op)\n\n # invalid scalars\n with tm.external_error_raised(TypeError):\n ops("foo")\n with tm.external_error_raised(TypeError):\n ops(pd.Timestamp("20180101"))\n\n # invalid array-likes\n str_ser = pd.Series("foo", index=s.index)\n # with pytest.raises(TypeError, match=msg):\n if all_arithmetic_operators in [\n "__mul__",\n "__rmul__",\n ]: # (data[~data.isna()] >= 0).all():\n res = ops(str_ser)\n expected = pd.Series(["foo" * x for x in data], index=s.index)\n expected = expected.fillna(np.nan)\n # TODO: doing this fillna to keep tests passing as we make\n # assert_almost_equal stricter, but the expected with pd.NA seems\n # more-correct than np.nan here.\n tm.assert_series_equal(res, expected)\n else:\n with tm.external_error_raised(TypeError):\n ops(str_ser)\n\n with tm.external_error_raised(TypeError):\n ops(pd.Series(pd.date_range("20180101", periods=len(s))))\n\n\n# Various\n# -----------------------------------------------------------------------------\n\n\n# TODO test unsigned overflow\n\n\ndef test_arith_coerce_scalar(data, all_arithmetic_operators):\n op = tm.get_op_from_name(all_arithmetic_operators)\n s = pd.Series(data)\n other = 0.01\n\n result = op(s, other)\n expected = op(s.astype(float), other)\n expected = expected.astype("Float64")\n\n # rmod results in NaN that wasn't NA in original nullable Series -> unmask it\n if all_arithmetic_operators == "__rmod__":\n mask = (s == 0).fillna(False).to_numpy(bool)\n expected.array._mask[mask] = False\n\n tm.assert_series_equal(result, expected)\n\n\n@pytest.mark.parametrize("other", [1.0, np.array(1.0)])\ndef test_arithmetic_conversion(all_arithmetic_operators, other):\n # if we have a float operand we should have a float result\n # if that is equal to an integer\n op = tm.get_op_from_name(all_arithmetic_operators)\n\n s = pd.Series([1, 2, 3], dtype="Int64")\n result = op(s, other)\n assert result.dtype == "Float64"\n\n\ndef test_cross_type_arithmetic():\n df = pd.DataFrame(\n {\n "A": pd.Series([1, 2, np.nan], dtype="Int64"),\n "B": pd.Series([1, np.nan, 3], dtype="UInt8"),\n "C": [1, 2, 3],\n }\n )\n\n result = df.A + df.C\n expected = pd.Series([2, 4, np.nan], dtype="Int64")\n tm.assert_series_equal(result, expected)\n\n result = (df.A + df.C) * 3 == 12\n expected = pd.Series([False, True, None], dtype="boolean")\n tm.assert_series_equal(result, expected)\n\n result = df.A + df.B\n expected = pd.Series([2, np.nan, np.nan], dtype="Int64")\n tm.assert_series_equal(result, expected)\n\n\n@pytest.mark.parametrize("op", ["mean"])\ndef test_reduce_to_float(op):\n # some reduce ops always return float, even if the result\n # is a rounded number\n df = pd.DataFrame(\n {\n "A": ["a", "b", "b"],\n "B": [1, None, 3],\n "C": pd.array([1, None, 3], dtype="Int64"),\n }\n )\n\n # op\n result = getattr(df.C, op)()\n assert isinstance(result, float)\n\n # groupby\n result = getattr(df.groupby("A"), op)()\n\n expected = pd.DataFrame(\n {"B": np.array([1.0, 3.0]), "C": pd.array([1, 3], dtype="Float64")},\n index=pd.Index(["a", "b"], name="A"),\n )\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "source, neg_target, abs_target",\n [\n ([1, 2, 3], [-1, -2, -3], [1, 2, 3]),\n ([1, 2, None], [-1, -2, None], [1, 2, None]),\n ([-1, 0, 1], [1, 0, -1], [1, 0, 1]),\n ],\n)\ndef test_unary_int_operators(any_signed_int_ea_dtype, source, neg_target, abs_target):\n dtype = any_signed_int_ea_dtype\n arr = pd.array(source, dtype=dtype)\n neg_result, pos_result, abs_result = -arr, +arr, abs(arr)\n neg_target = pd.array(neg_target, dtype=dtype)\n abs_target = pd.array(abs_target, dtype=dtype)\n\n tm.assert_extension_array_equal(neg_result, neg_target)\n tm.assert_extension_array_equal(pos_result, arr)\n assert not tm.shares_memory(pos_result, arr)\n tm.assert_extension_array_equal(abs_result, abs_target)\n\n\ndef test_values_multiplying_large_series_by_NA():\n # GH#33701\n\n result = pd.NA * pd.Series(np.zeros(10001))\n expected = pd.Series([pd.NA] * 10001)\n\n tm.assert_series_equal(result, expected)\n\n\ndef test_bitwise(dtype):\n left = pd.array([1, None, 3, 4], dtype=dtype)\n right = pd.array([None, 3, 5, 4], dtype=dtype)\n\n result = left | right\n expected = pd.array([None, None, 3 | 5, 4 | 4], dtype=dtype)\n tm.assert_extension_array_equal(result, expected)\n\n result = left & right\n expected = pd.array([None, None, 3 & 5, 4 & 4], dtype=dtype)\n tm.assert_extension_array_equal(result, expected)\n\n result = left ^ right\n expected = pd.array([None, None, 3 ^ 5, 4 ^ 4], dtype=dtype)\n tm.assert_extension_array_equal(result, expected)\n\n # TODO: desired behavior when operating with boolean? defer?\n\n floats = right.astype("Float64")\n with pytest.raises(TypeError, match="unsupported operand type"):\n left | floats\n with pytest.raises(TypeError, match="unsupported operand type"):\n left & floats\n with pytest.raises(TypeError, match="unsupported operand type"):\n left ^ floats\n
.venv\Lib\site-packages\pandas\tests\arrays\integer\test_arithmetic.py
test_arithmetic.py
Python
10,851
0.95
0.078261
0.118774
react-lib
208
2025-01-31T10:15:17.921385
GPL-3.0
true
eab226e2eb8b2448dae8a57b0cd0e714
import pytest\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.tests.arrays.masked_shared import (\n ComparisonOps,\n NumericOps,\n)\n\n\nclass TestComparisonOps(NumericOps, ComparisonOps):\n @pytest.mark.parametrize("other", [True, False, pd.NA, -1, 0, 1])\n def test_scalar(self, other, comparison_op, dtype):\n ComparisonOps.test_scalar(self, other, comparison_op, dtype)\n\n def test_compare_to_int(self, dtype, comparison_op):\n # GH 28930\n op_name = f"__{comparison_op.__name__}__"\n s1 = pd.Series([1, None, 3], dtype=dtype)\n s2 = pd.Series([1, None, 3], dtype="float")\n\n method = getattr(s1, op_name)\n result = method(2)\n\n method = getattr(s2, op_name)\n expected = method(2).astype("boolean")\n expected[s2.isna()] = pd.NA\n\n tm.assert_series_equal(result, expected)\n\n\ndef test_equals():\n # GH-30652\n # equals is generally tested in /tests/extension/base/methods, but this\n # specifically tests that two arrays of the same class but different dtype\n # do not evaluate equal\n a1 = pd.array([1, 2, None], dtype="Int64")\n a2 = pd.array([1, 2, None], dtype="Int32")\n assert a1.equals(a2) is False\n
.venv\Lib\site-packages\pandas\tests\arrays\integer\test_comparison.py
test_comparison.py
Python
1,212
0.95
0.128205
0.166667
react-lib
73
2023-09-13T00:27:11.122755
Apache-2.0
true
4cba12168e4d46eab7bdefa66fc9f79c
import numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\n\n\n@pytest.mark.parametrize(\n "to_concat_dtypes, result_dtype",\n [\n (["Int64", "Int64"], "Int64"),\n (["UInt64", "UInt64"], "UInt64"),\n (["Int8", "Int8"], "Int8"),\n (["Int8", "Int16"], "Int16"),\n (["UInt8", "Int8"], "Int16"),\n (["Int32", "UInt32"], "Int64"),\n (["Int64", "UInt64"], "Float64"),\n (["Int64", "boolean"], "object"),\n (["UInt8", "boolean"], "object"),\n ],\n)\ndef test_concat_series(to_concat_dtypes, result_dtype):\n # we expect the same dtypes as we would get with non-masked inputs,\n # just masked where available.\n\n result = pd.concat([pd.Series([0, 1, pd.NA], dtype=t) for t in to_concat_dtypes])\n expected = pd.concat([pd.Series([0, 1, pd.NA], dtype=object)] * 2).astype(\n result_dtype\n )\n tm.assert_series_equal(result, expected)\n\n # order doesn't matter for result\n result = pd.concat(\n [pd.Series([0, 1, pd.NA], dtype=t) for t in to_concat_dtypes[::-1]]\n )\n expected = pd.concat([pd.Series([0, 1, pd.NA], dtype=object)] * 2).astype(\n result_dtype\n )\n tm.assert_series_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "to_concat_dtypes, result_dtype",\n [\n (["Int64", "int64"], "Int64"),\n (["UInt64", "uint64"], "UInt64"),\n (["Int8", "int8"], "Int8"),\n (["Int8", "int16"], "Int16"),\n (["UInt8", "int8"], "Int16"),\n (["Int32", "uint32"], "Int64"),\n (["Int64", "uint64"], "Float64"),\n (["Int64", "bool"], "object"),\n (["UInt8", "bool"], "object"),\n ],\n)\ndef test_concat_series_with_numpy(to_concat_dtypes, result_dtype):\n # we expect the same dtypes as we would get with non-masked inputs,\n # just masked where available.\n\n s1 = pd.Series([0, 1, pd.NA], dtype=to_concat_dtypes[0])\n s2 = pd.Series(np.array([0, 1], dtype=to_concat_dtypes[1]))\n result = pd.concat([s1, s2], ignore_index=True)\n expected = pd.Series([0, 1, pd.NA, 0, 1], dtype=object).astype(result_dtype)\n tm.assert_series_equal(result, expected)\n\n # order doesn't matter for result\n result = pd.concat([s2, s1], ignore_index=True)\n expected = pd.Series([0, 1, 0, 1, pd.NA], dtype=object).astype(result_dtype)\n tm.assert_series_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\arrays\integer\test_concat.py
test_concat.py
Python
2,351
0.95
0.086957
0.1
vue-tools
139
2025-06-23T16:11:36.365193
BSD-3-Clause
true
3544d01150ea29055cc09ac3e204ca78
import numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.api.types import is_integer\nfrom pandas.core.arrays import IntegerArray\nfrom pandas.core.arrays.integer import (\n Int8Dtype,\n Int32Dtype,\n Int64Dtype,\n)\n\n\n@pytest.fixture(params=[pd.array, IntegerArray._from_sequence])\ndef constructor(request):\n """Fixture returning parametrized IntegerArray from given sequence.\n\n Used to test dtype conversions.\n """\n return request.param\n\n\ndef test_uses_pandas_na():\n a = pd.array([1, None], dtype=Int64Dtype())\n assert a[1] is pd.NA\n\n\ndef test_from_dtype_from_float(data):\n # construct from our dtype & string dtype\n dtype = data.dtype\n\n # from float\n expected = pd.Series(data)\n result = pd.Series(data.to_numpy(na_value=np.nan, dtype="float"), dtype=str(dtype))\n tm.assert_series_equal(result, expected)\n\n # from int / list\n expected = pd.Series(data)\n result = pd.Series(np.array(data).tolist(), dtype=str(dtype))\n tm.assert_series_equal(result, expected)\n\n # from int / array\n expected = pd.Series(data).dropna().reset_index(drop=True)\n dropped = np.array(data.dropna()).astype(np.dtype(dtype.type))\n result = pd.Series(dropped, dtype=str(dtype))\n tm.assert_series_equal(result, expected)\n\n\ndef test_conversions(data_missing):\n # astype to object series\n df = pd.DataFrame({"A": data_missing})\n result = df["A"].astype("object")\n expected = pd.Series(np.array([pd.NA, 1], dtype=object), name="A")\n tm.assert_series_equal(result, expected)\n\n # convert to object ndarray\n # we assert that we are exactly equal\n # including type conversions of scalars\n result = df["A"].astype("object").values\n expected = np.array([pd.NA, 1], dtype=object)\n tm.assert_numpy_array_equal(result, expected)\n\n for r, e in zip(result, expected):\n if pd.isnull(r):\n assert pd.isnull(e)\n elif is_integer(r):\n assert r == e\n assert is_integer(e)\n else:\n assert r == e\n assert type(r) == type(e)\n\n\ndef test_integer_array_constructor():\n values = np.array([1, 2, 3, 4], dtype="int64")\n mask = np.array([False, False, False, True], dtype="bool")\n\n result = IntegerArray(values, mask)\n expected = pd.array([1, 2, 3, np.nan], dtype="Int64")\n tm.assert_extension_array_equal(result, expected)\n\n msg = r".* should be .* numpy array. Use the 'pd.array' function instead"\n with pytest.raises(TypeError, match=msg):\n IntegerArray(values.tolist(), mask)\n\n with pytest.raises(TypeError, match=msg):\n IntegerArray(values, mask.tolist())\n\n with pytest.raises(TypeError, match=msg):\n IntegerArray(values.astype(float), mask)\n msg = r"__init__\(\) missing 1 required positional argument: 'mask'"\n with pytest.raises(TypeError, match=msg):\n IntegerArray(values)\n\n\ndef test_integer_array_constructor_copy():\n values = np.array([1, 2, 3, 4], dtype="int64")\n mask = np.array([False, False, False, True], dtype="bool")\n\n result = IntegerArray(values, mask)\n assert result._data is values\n assert result._mask is mask\n\n result = IntegerArray(values, mask, copy=True)\n assert result._data is not values\n assert result._mask is not mask\n\n\n@pytest.mark.parametrize(\n "a, b",\n [\n ([1, None], [1, np.nan]),\n ([None], [np.nan]),\n ([None, np.nan], [np.nan, np.nan]),\n ([np.nan, np.nan], [np.nan, np.nan]),\n ],\n)\ndef test_to_integer_array_none_is_nan(a, b):\n result = pd.array(a, dtype="Int64")\n expected = pd.array(b, dtype="Int64")\n tm.assert_extension_array_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "values",\n [\n ["foo", "bar"],\n "foo",\n 1,\n 1.0,\n pd.date_range("20130101", periods=2),\n np.array(["foo"]),\n [[1, 2], [3, 4]],\n [np.nan, {"a": 1}],\n ],\n)\ndef test_to_integer_array_error(values):\n # error in converting existing arrays to IntegerArrays\n msg = "|".join(\n [\n r"cannot be converted to IntegerDtype",\n r"invalid literal for int\(\) with base 10:",\n r"values must be a 1D list-like",\n r"Cannot pass scalar",\n r"int\(\) argument must be a string",\n ]\n )\n with pytest.raises((ValueError, TypeError), match=msg):\n pd.array(values, dtype="Int64")\n\n with pytest.raises((ValueError, TypeError), match=msg):\n IntegerArray._from_sequence(values)\n\n\ndef test_to_integer_array_inferred_dtype(constructor):\n # if values has dtype -> respect it\n result = constructor(np.array([1, 2], dtype="int8"))\n assert result.dtype == Int8Dtype()\n result = constructor(np.array([1, 2], dtype="int32"))\n assert result.dtype == Int32Dtype()\n\n # if values have no dtype -> always int64\n result = constructor([1, 2])\n assert result.dtype == Int64Dtype()\n\n\ndef test_to_integer_array_dtype_keyword(constructor):\n result = constructor([1, 2], dtype="Int8")\n assert result.dtype == Int8Dtype()\n\n # if values has dtype -> override it\n result = constructor(np.array([1, 2], dtype="int8"), dtype="Int32")\n assert result.dtype == Int32Dtype()\n\n\ndef test_to_integer_array_float():\n result = IntegerArray._from_sequence([1.0, 2.0], dtype="Int64")\n expected = pd.array([1, 2], dtype="Int64")\n tm.assert_extension_array_equal(result, expected)\n\n with pytest.raises(TypeError, match="cannot safely cast non-equivalent"):\n IntegerArray._from_sequence([1.5, 2.0], dtype="Int64")\n\n # for float dtypes, the itemsize is not preserved\n result = IntegerArray._from_sequence(\n np.array([1.0, 2.0], dtype="float32"), dtype="Int64"\n )\n assert result.dtype == Int64Dtype()\n\n\ndef test_to_integer_array_str():\n result = IntegerArray._from_sequence(["1", "2", None], dtype="Int64")\n expected = pd.array([1, 2, np.nan], dtype="Int64")\n tm.assert_extension_array_equal(result, expected)\n\n with pytest.raises(\n ValueError, match=r"invalid literal for int\(\) with base 10: .*"\n ):\n IntegerArray._from_sequence(["1", "2", ""], dtype="Int64")\n\n with pytest.raises(\n ValueError, match=r"invalid literal for int\(\) with base 10: .*"\n ):\n IntegerArray._from_sequence(["1.5", "2.0"], dtype="Int64")\n\n\n@pytest.mark.parametrize(\n "bool_values, int_values, target_dtype, expected_dtype",\n [\n ([False, True], [0, 1], Int64Dtype(), Int64Dtype()),\n ([False, True], [0, 1], "Int64", Int64Dtype()),\n ([False, True, np.nan], [0, 1, np.nan], Int64Dtype(), Int64Dtype()),\n ],\n)\ndef test_to_integer_array_bool(\n constructor, bool_values, int_values, target_dtype, expected_dtype\n):\n result = constructor(bool_values, dtype=target_dtype)\n assert result.dtype == expected_dtype\n expected = pd.array(int_values, dtype=target_dtype)\n tm.assert_extension_array_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "values, to_dtype, result_dtype",\n [\n (np.array([1], dtype="int64"), None, Int64Dtype),\n (np.array([1, np.nan]), None, Int64Dtype),\n (np.array([1, np.nan]), "int8", Int8Dtype),\n ],\n)\ndef test_to_integer_array(values, to_dtype, result_dtype):\n # convert existing arrays to IntegerArrays\n result = IntegerArray._from_sequence(values, dtype=to_dtype)\n assert result.dtype == result_dtype()\n expected = pd.array(values, dtype=result_dtype())\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_integer_array_from_boolean():\n # GH31104\n expected = pd.array(np.array([True, False]), dtype="Int64")\n result = pd.array(np.array([True, False], dtype=object), dtype="Int64")\n tm.assert_extension_array_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\arrays\integer\test_construction.py
test_construction.py
Python
7,768
0.95
0.102041
0.076923
node-utils
174
2025-06-16T10:32:30.201192
MIT
true
1ea0fef5389d23301b337fce1a68e0aa
import numpy as np\nimport pytest\n\nfrom pandas.core.dtypes.generic import ABCIndex\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.core.arrays.integer import (\n Int8Dtype,\n UInt32Dtype,\n)\n\n\ndef test_dtypes(dtype):\n # smoke tests on auto dtype construction\n\n if dtype.is_signed_integer:\n assert np.dtype(dtype.type).kind == "i"\n else:\n assert np.dtype(dtype.type).kind == "u"\n assert dtype.name is not None\n\n\n@pytest.mark.parametrize("op", ["sum", "min", "max", "prod"])\ndef test_preserve_dtypes(op):\n # for ops that enable (mean would actually work here\n # but generally it is a float return value)\n df = pd.DataFrame(\n {\n "A": ["a", "b", "b"],\n "B": [1, None, 3],\n "C": pd.array([1, None, 3], dtype="Int64"),\n }\n )\n\n # op\n result = getattr(df.C, op)()\n if op in {"sum", "prod", "min", "max"}:\n assert isinstance(result, np.int64)\n else:\n assert isinstance(result, int)\n\n # groupby\n result = getattr(df.groupby("A"), op)()\n\n expected = pd.DataFrame(\n {"B": np.array([1.0, 3.0]), "C": pd.array([1, 3], dtype="Int64")},\n index=pd.Index(["a", "b"], name="A"),\n )\n tm.assert_frame_equal(result, expected)\n\n\ndef test_astype_nansafe():\n # see gh-22343\n arr = pd.array([np.nan, 1, 2], dtype="Int8")\n msg = "cannot convert NA to integer"\n\n with pytest.raises(ValueError, match=msg):\n arr.astype("uint32")\n\n\n@pytest.mark.parametrize("dropna", [True, False])\ndef test_construct_index(all_data, dropna):\n # ensure that we do not coerce to different Index dtype or non-index\n\n all_data = all_data[:10]\n if dropna:\n other = np.array(all_data[~all_data.isna()])\n else:\n other = all_data\n\n result = pd.Index(pd.array(other, dtype=all_data.dtype))\n expected = pd.Index(other, dtype=all_data.dtype)\n assert all_data.dtype == expected.dtype # dont coerce to object\n\n tm.assert_index_equal(result, expected)\n\n\n@pytest.mark.parametrize("dropna", [True, False])\ndef test_astype_index(all_data, dropna):\n # as an int/uint index to Index\n\n all_data = all_data[:10]\n if dropna:\n other = all_data[~all_data.isna()]\n else:\n other = all_data\n\n dtype = all_data.dtype\n idx = pd.Index(np.array(other))\n assert isinstance(idx, ABCIndex)\n\n result = idx.astype(dtype)\n expected = idx.astype(object).astype(dtype)\n tm.assert_index_equal(result, expected)\n\n\ndef test_astype(all_data):\n all_data = all_data[:10]\n\n ints = all_data[~all_data.isna()]\n mixed = all_data\n dtype = Int8Dtype()\n\n # coerce to same type - ints\n s = pd.Series(ints)\n result = s.astype(all_data.dtype)\n expected = pd.Series(ints)\n tm.assert_series_equal(result, expected)\n\n # coerce to same other - ints\n s = pd.Series(ints)\n result = s.astype(dtype)\n expected = pd.Series(ints, dtype=dtype)\n tm.assert_series_equal(result, expected)\n\n # coerce to same numpy_dtype - ints\n s = pd.Series(ints)\n result = s.astype(all_data.dtype.numpy_dtype)\n expected = pd.Series(ints._data.astype(all_data.dtype.numpy_dtype))\n tm.assert_series_equal(result, expected)\n\n # coerce to same type - mixed\n s = pd.Series(mixed)\n result = s.astype(all_data.dtype)\n expected = pd.Series(mixed)\n tm.assert_series_equal(result, expected)\n\n # coerce to same other - mixed\n s = pd.Series(mixed)\n result = s.astype(dtype)\n expected = pd.Series(mixed, dtype=dtype)\n tm.assert_series_equal(result, expected)\n\n # coerce to same numpy_dtype - mixed\n s = pd.Series(mixed)\n msg = "cannot convert NA to integer"\n with pytest.raises(ValueError, match=msg):\n s.astype(all_data.dtype.numpy_dtype)\n\n # coerce to object\n s = pd.Series(mixed)\n result = s.astype("object")\n expected = pd.Series(np.asarray(mixed, dtype=object))\n tm.assert_series_equal(result, expected)\n\n\ndef test_astype_copy():\n arr = pd.array([1, 2, 3, None], dtype="Int64")\n orig = pd.array([1, 2, 3, None], dtype="Int64")\n\n # copy=True -> ensure both data and mask are actual copies\n result = arr.astype("Int64", copy=True)\n assert result is not arr\n assert not tm.shares_memory(result, arr)\n result[0] = 10\n tm.assert_extension_array_equal(arr, orig)\n result[0] = pd.NA\n tm.assert_extension_array_equal(arr, orig)\n\n # copy=False\n result = arr.astype("Int64", copy=False)\n assert result is arr\n assert np.shares_memory(result._data, arr._data)\n assert np.shares_memory(result._mask, arr._mask)\n result[0] = 10\n assert arr[0] == 10\n result[0] = pd.NA\n assert arr[0] is pd.NA\n\n # astype to different dtype -> always needs a copy -> even with copy=False\n # we need to ensure that also the mask is actually copied\n arr = pd.array([1, 2, 3, None], dtype="Int64")\n orig = pd.array([1, 2, 3, None], dtype="Int64")\n\n result = arr.astype("Int32", copy=False)\n assert not tm.shares_memory(result, arr)\n result[0] = 10\n tm.assert_extension_array_equal(arr, orig)\n result[0] = pd.NA\n tm.assert_extension_array_equal(arr, orig)\n\n\ndef test_astype_to_larger_numpy():\n a = pd.array([1, 2], dtype="Int32")\n result = a.astype("int64")\n expected = np.array([1, 2], dtype="int64")\n tm.assert_numpy_array_equal(result, expected)\n\n a = pd.array([1, 2], dtype="UInt32")\n result = a.astype("uint64")\n expected = np.array([1, 2], dtype="uint64")\n tm.assert_numpy_array_equal(result, expected)\n\n\n@pytest.mark.parametrize("dtype", [Int8Dtype(), "Int8", UInt32Dtype(), "UInt32"])\ndef test_astype_specific_casting(dtype):\n s = pd.Series([1, 2, 3], dtype="Int64")\n result = s.astype(dtype)\n expected = pd.Series([1, 2, 3], dtype=dtype)\n tm.assert_series_equal(result, expected)\n\n s = pd.Series([1, 2, 3, None], dtype="Int64")\n result = s.astype(dtype)\n expected = pd.Series([1, 2, 3, None], dtype=dtype)\n tm.assert_series_equal(result, expected)\n\n\ndef test_astype_floating():\n arr = pd.array([1, 2, None], dtype="Int64")\n result = arr.astype("Float64")\n expected = pd.array([1.0, 2.0, None], dtype="Float64")\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_astype_dt64():\n # GH#32435\n arr = pd.array([1, 2, 3, pd.NA]) * 10**9\n\n result = arr.astype("datetime64[ns]")\n\n expected = np.array([1, 2, 3, "NaT"], dtype="M8[s]").astype("M8[ns]")\n tm.assert_numpy_array_equal(result, expected)\n\n\ndef test_construct_cast_invalid(dtype):\n msg = "cannot safely"\n arr = [1.2, 2.3, 3.7]\n with pytest.raises(TypeError, match=msg):\n pd.array(arr, dtype=dtype)\n\n with pytest.raises(TypeError, match=msg):\n pd.Series(arr).astype(dtype)\n\n arr = [1.2, 2.3, 3.7, np.nan]\n with pytest.raises(TypeError, match=msg):\n pd.array(arr, dtype=dtype)\n\n with pytest.raises(TypeError, match=msg):\n pd.Series(arr).astype(dtype)\n\n\n@pytest.mark.parametrize("in_series", [True, False])\ndef test_to_numpy_na_nan(in_series):\n a = pd.array([0, 1, None], dtype="Int64")\n if in_series:\n a = pd.Series(a)\n\n result = a.to_numpy(dtype="float64", na_value=np.nan)\n expected = np.array([0.0, 1.0, np.nan], dtype="float64")\n tm.assert_numpy_array_equal(result, expected)\n\n result = a.to_numpy(dtype="int64", na_value=-1)\n expected = np.array([0, 1, -1], dtype="int64")\n tm.assert_numpy_array_equal(result, expected)\n\n result = a.to_numpy(dtype="bool", na_value=False)\n expected = np.array([False, True, False], dtype="bool")\n tm.assert_numpy_array_equal(result, expected)\n\n\n@pytest.mark.parametrize("in_series", [True, False])\n@pytest.mark.parametrize("dtype", ["int32", "int64", "bool"])\ndef test_to_numpy_dtype(dtype, in_series):\n a = pd.array([0, 1], dtype="Int64")\n if in_series:\n a = pd.Series(a)\n\n result = a.to_numpy(dtype=dtype)\n expected = np.array([0, 1], dtype=dtype)\n tm.assert_numpy_array_equal(result, expected)\n\n\n@pytest.mark.parametrize("dtype", ["int64", "bool"])\ndef test_to_numpy_na_raises(dtype):\n a = pd.array([0, 1, None], dtype="Int64")\n with pytest.raises(ValueError, match=dtype):\n a.to_numpy(dtype=dtype)\n\n\ndef test_astype_str(using_infer_string):\n a = pd.array([1, 2, None], dtype="Int64")\n\n if using_infer_string:\n expected = pd.array(["1", "2", None], dtype=pd.StringDtype(na_value=np.nan))\n\n tm.assert_extension_array_equal(a.astype(str), expected)\n tm.assert_extension_array_equal(a.astype("str"), expected)\n else:\n expected = np.array(["1", "2", "<NA>"], dtype=f"{tm.ENDIAN}U21")\n\n tm.assert_numpy_array_equal(a.astype(str), expected)\n tm.assert_numpy_array_equal(a.astype("str"), expected)\n\n\ndef test_astype_boolean():\n # https://github.com/pandas-dev/pandas/issues/31102\n a = pd.array([1, 0, -1, 2, None], dtype="Int64")\n result = a.astype("boolean")\n expected = pd.array([True, False, True, True, None], dtype="boolean")\n tm.assert_extension_array_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\arrays\integer\test_dtypes.py
test_dtypes.py
Python
9,042
0.95
0.083056
0.092105
node-utils
329
2024-01-16T06:26:25.880128
Apache-2.0
true
fae026b45ec789780e94c200203ac9ea
import numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.core.arrays import FloatingArray\n\n\n@pytest.mark.parametrize("ufunc", [np.abs, np.sign])\n# np.sign emits a warning with nans, <https://github.com/numpy/numpy/issues/15127>\n@pytest.mark.filterwarnings("ignore:invalid value encountered in sign:RuntimeWarning")\ndef test_ufuncs_single_int(ufunc):\n a = pd.array([1, 2, -3, np.nan])\n result = ufunc(a)\n expected = pd.array(ufunc(a.astype(float)), dtype="Int64")\n tm.assert_extension_array_equal(result, expected)\n\n s = pd.Series(a)\n result = ufunc(s)\n expected = pd.Series(pd.array(ufunc(a.astype(float)), dtype="Int64"))\n tm.assert_series_equal(result, expected)\n\n\n@pytest.mark.parametrize("ufunc", [np.log, np.exp, np.sin, np.cos, np.sqrt])\ndef test_ufuncs_single_float(ufunc):\n a = pd.array([1, 2, -3, np.nan])\n with np.errstate(invalid="ignore"):\n result = ufunc(a)\n expected = FloatingArray(ufunc(a.astype(float)), mask=a._mask)\n tm.assert_extension_array_equal(result, expected)\n\n s = pd.Series(a)\n with np.errstate(invalid="ignore"):\n result = ufunc(s)\n expected = pd.Series(expected)\n tm.assert_series_equal(result, expected)\n\n\n@pytest.mark.parametrize("ufunc", [np.add, np.subtract])\ndef test_ufuncs_binary_int(ufunc):\n # two IntegerArrays\n a = pd.array([1, 2, -3, np.nan])\n result = ufunc(a, a)\n expected = pd.array(ufunc(a.astype(float), a.astype(float)), dtype="Int64")\n tm.assert_extension_array_equal(result, expected)\n\n # IntegerArray with numpy array\n arr = np.array([1, 2, 3, 4])\n result = ufunc(a, arr)\n expected = pd.array(ufunc(a.astype(float), arr), dtype="Int64")\n tm.assert_extension_array_equal(result, expected)\n\n result = ufunc(arr, a)\n expected = pd.array(ufunc(arr, a.astype(float)), dtype="Int64")\n tm.assert_extension_array_equal(result, expected)\n\n # IntegerArray with scalar\n result = ufunc(a, 1)\n expected = pd.array(ufunc(a.astype(float), 1), dtype="Int64")\n tm.assert_extension_array_equal(result, expected)\n\n result = ufunc(1, a)\n expected = pd.array(ufunc(1, a.astype(float)), dtype="Int64")\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_ufunc_binary_output():\n a = pd.array([1, 2, np.nan])\n result = np.modf(a)\n expected = np.modf(a.to_numpy(na_value=np.nan, dtype="float"))\n expected = (pd.array(expected[0]), pd.array(expected[1]))\n\n assert isinstance(result, tuple)\n assert len(result) == 2\n\n for x, y in zip(result, expected):\n tm.assert_extension_array_equal(x, y)\n\n\n@pytest.mark.parametrize("values", [[0, 1], [0, None]])\ndef test_ufunc_reduce_raises(values):\n arr = pd.array(values)\n\n res = np.add.reduce(arr)\n expected = arr.sum(skipna=False)\n tm.assert_almost_equal(res, expected)\n\n\n@pytest.mark.parametrize(\n "pandasmethname, kwargs",\n [\n ("var", {"ddof": 0}),\n ("var", {"ddof": 1}),\n ("std", {"ddof": 0}),\n ("std", {"ddof": 1}),\n ("kurtosis", {}),\n ("skew", {}),\n ("sem", {}),\n ],\n)\ndef test_stat_method(pandasmethname, kwargs):\n s = pd.Series(data=[1, 2, 3, 4, 5, 6, np.nan, np.nan], dtype="Int64")\n pandasmeth = getattr(s, pandasmethname)\n result = pandasmeth(**kwargs)\n s2 = pd.Series(data=[1, 2, 3, 4, 5, 6], dtype="Int64")\n pandasmeth = getattr(s2, pandasmethname)\n expected = pandasmeth(**kwargs)\n assert expected == result\n\n\ndef test_value_counts_na():\n arr = pd.array([1, 2, 1, pd.NA], dtype="Int64")\n result = arr.value_counts(dropna=False)\n ex_index = pd.Index([1, 2, pd.NA], dtype="Int64")\n assert ex_index.dtype == "Int64"\n expected = pd.Series([2, 1, 1], index=ex_index, dtype="Int64", name="count")\n tm.assert_series_equal(result, expected)\n\n result = arr.value_counts(dropna=True)\n expected = pd.Series([2, 1], index=arr[:2], dtype="Int64", name="count")\n assert expected.index.dtype == arr.dtype\n tm.assert_series_equal(result, expected)\n\n\ndef test_value_counts_empty():\n # https://github.com/pandas-dev/pandas/issues/33317\n ser = pd.Series([], dtype="Int64")\n result = ser.value_counts()\n idx = pd.Index([], dtype=ser.dtype)\n assert idx.dtype == ser.dtype\n expected = pd.Series([], index=idx, dtype="Int64", name="count")\n tm.assert_series_equal(result, expected)\n\n\ndef test_value_counts_with_normalize():\n # GH 33172\n ser = pd.Series([1, 2, 1, pd.NA], dtype="Int64")\n result = ser.value_counts(normalize=True)\n expected = pd.Series([2, 1], index=ser[:2], dtype="Float64", name="proportion") / 3\n assert expected.index.dtype == ser.dtype\n tm.assert_series_equal(result, expected)\n\n\n@pytest.mark.parametrize("skipna", [True, False])\n@pytest.mark.parametrize("min_count", [0, 4])\ndef test_integer_array_sum(skipna, min_count, any_int_ea_dtype):\n dtype = any_int_ea_dtype\n arr = pd.array([1, 2, 3, None], dtype=dtype)\n result = arr.sum(skipna=skipna, min_count=min_count)\n if skipna and min_count == 0:\n assert result == 6\n else:\n assert result is pd.NA\n\n\n@pytest.mark.parametrize("skipna", [True, False])\n@pytest.mark.parametrize("method", ["min", "max"])\ndef test_integer_array_min_max(skipna, method, any_int_ea_dtype):\n dtype = any_int_ea_dtype\n arr = pd.array([0, 1, None], dtype=dtype)\n func = getattr(arr, method)\n result = func(skipna=skipna)\n if skipna:\n assert result == (0 if method == "min" else 1)\n else:\n assert result is pd.NA\n\n\n@pytest.mark.parametrize("skipna", [True, False])\n@pytest.mark.parametrize("min_count", [0, 9])\ndef test_integer_array_prod(skipna, min_count, any_int_ea_dtype):\n dtype = any_int_ea_dtype\n arr = pd.array([1, 2, None], dtype=dtype)\n result = arr.prod(skipna=skipna, min_count=min_count)\n if skipna and min_count == 0:\n assert result == 2\n else:\n assert result is pd.NA\n\n\n@pytest.mark.parametrize(\n "values, expected", [([1, 2, 3], 6), ([1, 2, 3, None], 6), ([None], 0)]\n)\ndef test_integer_array_numpy_sum(values, expected):\n arr = pd.array(values, dtype="Int64")\n result = np.sum(arr)\n assert result == expected\n\n\n@pytest.mark.parametrize("op", ["sum", "prod", "min", "max"])\ndef test_dataframe_reductions(op):\n # https://github.com/pandas-dev/pandas/pull/32867\n # ensure the integers are not cast to float during reductions\n df = pd.DataFrame({"a": pd.array([1, 2], dtype="Int64")})\n result = df.max()\n assert isinstance(result["a"], np.int64)\n\n\n# TODO(jreback) - these need testing / are broken\n\n# shift\n\n# set_index (destroys type)\n
.venv\Lib\site-packages\pandas\tests\arrays\integer\test_function.py
test_function.py
Python
6,627
0.95
0.093596
0.06875
react-lib
104
2024-08-22T17:15:13.219862
GPL-3.0
true
610155febb400a057f9ce630fcb608ee
import pandas as pd\nimport pandas._testing as tm\n\n\ndef test_array_setitem_nullable_boolean_mask():\n # GH 31446\n ser = pd.Series([1, 2], dtype="Int64")\n result = ser.where(ser > 1)\n expected = pd.Series([pd.NA, 2], dtype="Int64")\n tm.assert_series_equal(result, expected)\n\n\ndef test_array_setitem():\n # GH 31446\n arr = pd.Series([1, 2], dtype="Int64").array\n arr[arr > 1] = 1\n\n expected = pd.array([1, 1], dtype="Int64")\n tm.assert_extension_array_equal(arr, expected)\n
.venv\Lib\site-packages\pandas\tests\arrays\integer\test_indexing.py
test_indexing.py
Python
498
0.95
0.105263
0.142857
awesome-app
128
2024-04-19T07:54:46.031355
Apache-2.0
true
837b6c867bbf90ca39d448f5189996d9
import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n Series,\n array,\n)\nimport pandas._testing as tm\n\n\n@pytest.mark.parametrize(\n "op, expected",\n [\n ["sum", np.int64(3)],\n ["prod", np.int64(2)],\n ["min", np.int64(1)],\n ["max", np.int64(2)],\n ["mean", np.float64(1.5)],\n ["median", np.float64(1.5)],\n ["var", np.float64(0.5)],\n ["std", np.float64(0.5**0.5)],\n ["skew", pd.NA],\n ["kurt", pd.NA],\n ["any", True],\n ["all", True],\n ],\n)\ndef test_series_reductions(op, expected):\n ser = Series([1, 2], dtype="Int64")\n result = getattr(ser, op)()\n tm.assert_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "op, expected",\n [\n ["sum", Series([3], index=["a"], dtype="Int64")],\n ["prod", Series([2], index=["a"], dtype="Int64")],\n ["min", Series([1], index=["a"], dtype="Int64")],\n ["max", Series([2], index=["a"], dtype="Int64")],\n ["mean", Series([1.5], index=["a"], dtype="Float64")],\n ["median", Series([1.5], index=["a"], dtype="Float64")],\n ["var", Series([0.5], index=["a"], dtype="Float64")],\n ["std", Series([0.5**0.5], index=["a"], dtype="Float64")],\n ["skew", Series([pd.NA], index=["a"], dtype="Float64")],\n ["kurt", Series([pd.NA], index=["a"], dtype="Float64")],\n ["any", Series([True], index=["a"], dtype="boolean")],\n ["all", Series([True], index=["a"], dtype="boolean")],\n ],\n)\ndef test_dataframe_reductions(op, expected):\n df = DataFrame({"a": array([1, 2], dtype="Int64")})\n result = getattr(df, op)()\n tm.assert_series_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "op, expected",\n [\n ["sum", array([1, 3], dtype="Int64")],\n ["prod", array([1, 3], dtype="Int64")],\n ["min", array([1, 3], dtype="Int64")],\n ["max", array([1, 3], dtype="Int64")],\n ["mean", array([1, 3], dtype="Float64")],\n ["median", array([1, 3], dtype="Float64")],\n ["var", array([pd.NA], dtype="Float64")],\n ["std", array([pd.NA], dtype="Float64")],\n ["skew", array([pd.NA], dtype="Float64")],\n ["any", array([True, True], dtype="boolean")],\n ["all", array([True, True], dtype="boolean")],\n ],\n)\ndef test_groupby_reductions(op, expected):\n df = DataFrame(\n {\n "A": ["a", "b", "b"],\n "B": array([1, None, 3], dtype="Int64"),\n }\n )\n result = getattr(df.groupby("A"), op)()\n expected = DataFrame(expected, index=pd.Index(["a", "b"], name="A"), columns=["B"])\n\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "op, expected",\n [\n ["sum", Series([4, 4], index=["B", "C"], dtype="Float64")],\n ["prod", Series([3, 3], index=["B", "C"], dtype="Float64")],\n ["min", Series([1, 1], index=["B", "C"], dtype="Float64")],\n ["max", Series([3, 3], index=["B", "C"], dtype="Float64")],\n ["mean", Series([2, 2], index=["B", "C"], dtype="Float64")],\n ["median", Series([2, 2], index=["B", "C"], dtype="Float64")],\n ["var", Series([2, 2], index=["B", "C"], dtype="Float64")],\n ["std", Series([2**0.5, 2**0.5], index=["B", "C"], dtype="Float64")],\n ["skew", Series([pd.NA, pd.NA], index=["B", "C"], dtype="Float64")],\n ["kurt", Series([pd.NA, pd.NA], index=["B", "C"], dtype="Float64")],\n ["any", Series([True, True, True], index=["A", "B", "C"], dtype="boolean")],\n ["all", Series([True, True, True], index=["A", "B", "C"], dtype="boolean")],\n ],\n)\ndef test_mixed_reductions(op, expected):\n df = DataFrame(\n {\n "A": ["a", "b", "b"],\n "B": [1, None, 3],\n "C": array([1, None, 3], dtype="Int64"),\n }\n )\n\n # series\n result = getattr(df.C, op)()\n tm.assert_equal(result, expected["C"])\n\n # frame\n if op in ["any", "all"]:\n result = getattr(df, op)()\n else:\n result = getattr(df, op)(numeric_only=True)\n tm.assert_series_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\arrays\integer\test_reduction.py
test_reduction.py
Python
4,100
0.95
0.04065
0.018018
node-utils
591
2023-09-29T23:19:55.567734
GPL-3.0
true
51d2ab6cbfc1ade6ad44e77a2ad1ef51
import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas.core.arrays.integer import (\n Int8Dtype,\n Int16Dtype,\n Int32Dtype,\n Int64Dtype,\n UInt8Dtype,\n UInt16Dtype,\n UInt32Dtype,\n UInt64Dtype,\n)\n\n\ndef test_dtypes(dtype):\n # smoke tests on auto dtype construction\n\n if dtype.is_signed_integer:\n assert np.dtype(dtype.type).kind == "i"\n else:\n assert np.dtype(dtype.type).kind == "u"\n assert dtype.name is not None\n\n\n@pytest.mark.parametrize(\n "dtype, expected",\n [\n (Int8Dtype(), "Int8Dtype()"),\n (Int16Dtype(), "Int16Dtype()"),\n (Int32Dtype(), "Int32Dtype()"),\n (Int64Dtype(), "Int64Dtype()"),\n (UInt8Dtype(), "UInt8Dtype()"),\n (UInt16Dtype(), "UInt16Dtype()"),\n (UInt32Dtype(), "UInt32Dtype()"),\n (UInt64Dtype(), "UInt64Dtype()"),\n ],\n)\ndef test_repr_dtype(dtype, expected):\n assert repr(dtype) == expected\n\n\ndef test_repr_array():\n result = repr(pd.array([1, None, 3]))\n expected = "<IntegerArray>\n[1, <NA>, 3]\nLength: 3, dtype: Int64"\n assert result == expected\n\n\ndef test_repr_array_long():\n data = pd.array([1, 2, None] * 1000)\n expected = (\n "<IntegerArray>\n"\n "[ 1, 2, <NA>, 1, 2, <NA>, 1, 2, <NA>, 1,\n"\n " ...\n"\n " <NA>, 1, 2, <NA>, 1, 2, <NA>, 1, 2, <NA>]\n"\n "Length: 3000, dtype: Int64"\n )\n result = repr(data)\n assert result == expected\n\n\ndef test_frame_repr(data_missing):\n df = pd.DataFrame({"A": data_missing})\n result = repr(df)\n expected = " A\n0 <NA>\n1 1"\n assert result == expected\n
.venv\Lib\site-packages\pandas\tests\arrays\integer\test_repr.py
test_repr.py
Python
1,652
0.95
0.089552
0.018182
vue-tools
153
2024-02-14T03:59:00.933255
BSD-3-Clause
true
82f4a873c6ae047101285ec985657ff8
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\integer\__pycache__\conftest.cpython-313.pyc
conftest.cpython-313.pyc
Other
2,393
0.8
0
0
node-utils
685
2024-01-30T11:21:43.902241
Apache-2.0
true
fc6e777e0b99f6a19d2545c28f0e006b
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\integer\__pycache__\test_arithmetic.cpython-313.pyc
test_arithmetic.cpython-313.pyc
Other
16,634
0.8
0
0
node-utils
262
2024-06-06T18:59:30.502464
MIT
true
9db3c19e655274423f4d743661d3c11d
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\integer\__pycache__\test_comparison.cpython-313.pyc
test_comparison.cpython-313.pyc
Other
2,219
0.8
0
0
python-kit
900
2023-08-01T15:55:42.721954
MIT
true
e5b97bbc13370eacedc6e4a2185ad13a
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\integer\__pycache__\test_concat.cpython-313.pyc
test_concat.cpython-313.pyc
Other
3,429
0.8
0
0
node-utils
266
2025-03-31T20:25:47.296851
Apache-2.0
true
09a3d160ce310b0db00b7b9413d0d4b4
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\integer\__pycache__\test_construction.cpython-313.pyc
test_construction.cpython-313.pyc
Other
13,139
0.95
0.017751
0
node-utils
127
2024-02-28T09:28:41.602166
Apache-2.0
true
e2ca5f1812c0b1d390bd2df13959f585
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\integer\__pycache__\test_dtypes.cpython-313.pyc
test_dtypes.cpython-313.pyc
Other
15,904
0.8
0
0.021505
react-lib
251
2024-10-07T12:05:50.809595
BSD-3-Clause
true
8f1e5f58cb21c4385ed587927ffbdff5
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\integer\__pycache__\test_function.cpython-313.pyc
test_function.cpython-313.pyc
Other
12,275
0.95
0
0.007937
vue-tools
577
2024-07-29T10:57:43.559120
BSD-3-Clause
true
9878fecd2b97a9e5a606509091856133
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\integer\__pycache__\test_indexing.cpython-313.pyc
test_indexing.cpython-313.pyc
Other
1,197
0.8
0
0.142857
awesome-app
595
2024-12-30T19:15:13.307329
GPL-3.0
true
48b8e7c9776537af83579e4291874c7f
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\integer\__pycache__\test_reduction.cpython-313.pyc
test_reduction.cpython-313.pyc
Other
5,250
0.8
0
0
awesome-app
424
2024-04-13T05:54:23.488675
MIT
true
529b5f470dc6962f1bb17436582e62d4
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\integer\__pycache__\test_repr.cpython-313.pyc
test_repr.cpython-313.pyc
Other
2,745
0.8
0
0
node-utils
571
2025-01-20T10:22:01.818180
MIT
true
1110bd2aabb0575c447eb52a08c6031c
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\integer\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
202
0.7
0
0
react-lib
348
2024-02-28T18:37:51.399167
GPL-3.0
true
1e17d1a34b5e200331feee81d2ebe002
import pytest\n\nfrom pandas import (\n Categorical,\n CategoricalDtype,\n Index,\n IntervalIndex,\n)\nimport pandas._testing as tm\n\n\nclass TestAstype:\n @pytest.mark.parametrize("ordered", [True, False])\n def test_astype_categorical_retains_ordered(self, ordered):\n index = IntervalIndex.from_breaks(range(5))\n arr = index._data\n\n dtype = CategoricalDtype(None, ordered=ordered)\n\n expected = Categorical(list(arr), ordered=ordered)\n result = arr.astype(dtype)\n assert result.ordered is ordered\n tm.assert_categorical_equal(result, expected)\n\n # test IntervalIndex.astype while we're at it.\n result = index.astype(dtype)\n expected = Index(expected)\n tm.assert_index_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\arrays\interval\test_astype.py
test_astype.py
Python
776
0.95
0.107143
0.045455
react-lib
290
2024-08-16T00:17:02.874101
Apache-2.0
true
7a9800812179ed35a7837aead6b79492
from pandas.core.arrays import IntervalArray\n\n\ndef test_repr():\n # GH#25022\n arr = IntervalArray.from_tuples([(0, 1), (1, 2)])\n result = repr(arr)\n expected = (\n "<IntervalArray>\n"\n "[(0, 1], (1, 2]]\n"\n "Length: 2, dtype: interval[int64, right]"\n )\n assert result == expected\n
.venv\Lib\site-packages\pandas\tests\arrays\interval\test_formats.py
test_formats.py
Python
317
0.95
0.076923
0.090909
react-lib
631
2025-06-14T20:23:53.264332
Apache-2.0
true
1e04f3ab37f23bc0fd9f369a5c03123b
import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n Index,\n Interval,\n IntervalIndex,\n Timedelta,\n Timestamp,\n date_range,\n timedelta_range,\n)\nimport pandas._testing as tm\nfrom pandas.core.arrays import IntervalArray\n\n\n@pytest.fixture(\n params=[\n (Index([0, 2, 4]), Index([1, 3, 5])),\n (Index([0.0, 1.0, 2.0]), Index([1.0, 2.0, 3.0])),\n (timedelta_range("0 days", periods=3), timedelta_range("1 day", periods=3)),\n (date_range("20170101", periods=3), date_range("20170102", periods=3)),\n (\n date_range("20170101", periods=3, tz="US/Eastern"),\n date_range("20170102", periods=3, tz="US/Eastern"),\n ),\n ],\n ids=lambda x: str(x[0].dtype),\n)\ndef left_right_dtypes(request):\n """\n Fixture for building an IntervalArray from various dtypes\n """\n return request.param\n\n\nclass TestAttributes:\n @pytest.mark.parametrize(\n "left, right",\n [\n (0, 1),\n (Timedelta("0 days"), Timedelta("1 day")),\n (Timestamp("2018-01-01"), Timestamp("2018-01-02")),\n (\n Timestamp("2018-01-01", tz="US/Eastern"),\n Timestamp("2018-01-02", tz="US/Eastern"),\n ),\n ],\n )\n @pytest.mark.parametrize("constructor", [IntervalArray, IntervalIndex])\n def test_is_empty(self, constructor, left, right, closed):\n # GH27219\n tuples = [(left, left), (left, right), np.nan]\n expected = np.array([closed != "both", False, False])\n result = constructor.from_tuples(tuples, closed=closed).is_empty\n tm.assert_numpy_array_equal(result, expected)\n\n\nclass TestMethods:\n @pytest.mark.parametrize("new_closed", ["left", "right", "both", "neither"])\n def test_set_closed(self, closed, new_closed):\n # GH 21670\n array = IntervalArray.from_breaks(range(10), closed=closed)\n result = array.set_closed(new_closed)\n expected = IntervalArray.from_breaks(range(10), closed=new_closed)\n tm.assert_extension_array_equal(result, expected)\n\n @pytest.mark.parametrize(\n "other",\n [\n Interval(0, 1, closed="right"),\n IntervalArray.from_breaks([1, 2, 3, 4], closed="right"),\n ],\n )\n def test_where_raises(self, other):\n # GH#45768 The IntervalArray methods raises; the Series method coerces\n ser = pd.Series(IntervalArray.from_breaks([1, 2, 3, 4], closed="left"))\n mask = np.array([True, False, True])\n match = "'value.closed' is 'right', expected 'left'."\n with pytest.raises(ValueError, match=match):\n ser.array._where(mask, other)\n\n res = ser.where(mask, other=other)\n expected = ser.astype(object).where(mask, other)\n tm.assert_series_equal(res, expected)\n\n def test_shift(self):\n # https://github.com/pandas-dev/pandas/issues/31495, GH#22428, GH#31502\n a = IntervalArray.from_breaks([1, 2, 3])\n result = a.shift()\n # int -> float\n expected = IntervalArray.from_tuples([(np.nan, np.nan), (1.0, 2.0)])\n tm.assert_interval_array_equal(result, expected)\n\n msg = "can only insert Interval objects and NA into an IntervalArray"\n with pytest.raises(TypeError, match=msg):\n a.shift(1, fill_value=pd.NaT)\n\n def test_shift_datetime(self):\n # GH#31502, GH#31504\n a = IntervalArray.from_breaks(date_range("2000", periods=4))\n result = a.shift(2)\n expected = a.take([-1, -1, 0], allow_fill=True)\n tm.assert_interval_array_equal(result, expected)\n\n result = a.shift(-1)\n expected = a.take([1, 2, -1], allow_fill=True)\n tm.assert_interval_array_equal(result, expected)\n\n msg = "can only insert Interval objects and NA into an IntervalArray"\n with pytest.raises(TypeError, match=msg):\n a.shift(1, fill_value=np.timedelta64("NaT", "ns"))\n\n\nclass TestSetitem:\n def test_set_na(self, left_right_dtypes):\n left, right = left_right_dtypes\n left = left.copy(deep=True)\n right = right.copy(deep=True)\n result = IntervalArray.from_arrays(left, right)\n\n if result.dtype.subtype.kind not in ["m", "M"]:\n msg = "'value' should be an interval type, got <.*NaTType'> instead."\n with pytest.raises(TypeError, match=msg):\n result[0] = pd.NaT\n if result.dtype.subtype.kind in ["i", "u"]:\n msg = "Cannot set float NaN to integer-backed IntervalArray"\n # GH#45484 TypeError, not ValueError, matches what we get with\n # non-NA un-holdable value.\n with pytest.raises(TypeError, match=msg):\n result[0] = np.nan\n return\n\n result[0] = np.nan\n\n expected_left = Index([left._na_value] + list(left[1:]))\n expected_right = Index([right._na_value] + list(right[1:]))\n expected = IntervalArray.from_arrays(expected_left, expected_right)\n\n tm.assert_extension_array_equal(result, expected)\n\n def test_setitem_mismatched_closed(self):\n arr = IntervalArray.from_breaks(range(4))\n orig = arr.copy()\n other = arr.set_closed("both")\n\n msg = "'value.closed' is 'both', expected 'right'"\n with pytest.raises(ValueError, match=msg):\n arr[0] = other[0]\n with pytest.raises(ValueError, match=msg):\n arr[:1] = other[:1]\n with pytest.raises(ValueError, match=msg):\n arr[:0] = other[:0]\n with pytest.raises(ValueError, match=msg):\n arr[:] = other[::-1]\n with pytest.raises(ValueError, match=msg):\n arr[:] = list(other[::-1])\n with pytest.raises(ValueError, match=msg):\n arr[:] = other[::-1].astype(object)\n with pytest.raises(ValueError, match=msg):\n arr[:] = other[::-1].astype("category")\n\n # empty list should be no-op\n arr[:0] = []\n tm.assert_interval_array_equal(arr, orig)\n\n\nclass TestReductions:\n def test_min_max_invalid_axis(self, left_right_dtypes):\n left, right = left_right_dtypes\n left = left.copy(deep=True)\n right = right.copy(deep=True)\n arr = IntervalArray.from_arrays(left, right)\n\n msg = "`axis` must be fewer than the number of dimensions"\n for axis in [-2, 1]:\n with pytest.raises(ValueError, match=msg):\n arr.min(axis=axis)\n with pytest.raises(ValueError, match=msg):\n arr.max(axis=axis)\n\n msg = "'>=' not supported between"\n with pytest.raises(TypeError, match=msg):\n arr.min(axis="foo")\n with pytest.raises(TypeError, match=msg):\n arr.max(axis="foo")\n\n def test_min_max(self, left_right_dtypes, index_or_series_or_array):\n # GH#44746\n left, right = left_right_dtypes\n left = left.copy(deep=True)\n right = right.copy(deep=True)\n arr = IntervalArray.from_arrays(left, right)\n\n # The expected results below are only valid if monotonic\n assert left.is_monotonic_increasing\n assert Index(arr).is_monotonic_increasing\n\n MIN = arr[0]\n MAX = arr[-1]\n\n indexer = np.arange(len(arr))\n np.random.default_rng(2).shuffle(indexer)\n arr = arr.take(indexer)\n\n arr_na = arr.insert(2, np.nan)\n\n arr = index_or_series_or_array(arr)\n arr_na = index_or_series_or_array(arr_na)\n\n for skipna in [True, False]:\n res = arr.min(skipna=skipna)\n assert res == MIN\n assert type(res) == type(MIN)\n\n res = arr.max(skipna=skipna)\n assert res == MAX\n assert type(res) == type(MAX)\n\n res = arr_na.min(skipna=False)\n assert np.isnan(res)\n res = arr_na.max(skipna=False)\n assert np.isnan(res)\n\n res = arr_na.min(skipna=True)\n assert res == MIN\n assert type(res) == type(MIN)\n res = arr_na.max(skipna=True)\n assert res == MAX\n assert type(res) == type(MAX)\n
.venv\Lib\site-packages\pandas\tests\arrays\interval\test_interval.py
test_interval.py
Python
8,082
0.95
0.08658
0.056701
vue-tools
652
2024-07-29T18:47:12.718083
Apache-2.0
true
08eaae83c3390f77729e50d6eae4dc63