Commit ·
f488c76
1
Parent(s): 8ff5f90
Upload folder using huggingface_hub (part 11)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/categorical/test_astype.py +155 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/categorical/test_constructors.py +787 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/categorical/test_dtypes.py +139 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/categorical/test_indexing.py +388 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/categorical/test_map.py +154 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/categorical/test_missing.py +216 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/categorical/test_operators.py +414 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/categorical/test_replace.py +111 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/categorical/test_repr.py +545 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/categorical/test_sorting.py +128 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/categorical/test_subclass.py +26 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/categorical/test_take.py +89 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/categorical/test_warnings.py +19 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/datetimes/__init__.py +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/datetimes/test_constructors.py +284 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/datetimes/test_cumulative.py +44 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/datetimes/test_reductions.py +183 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/floating/__init__.py +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/floating/conftest.py +48 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/floating/test_arithmetic.py +240 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/floating/test_astype.py +135 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/floating/test_comparison.py +65 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/floating/test_concat.py +20 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/floating/test_construction.py +204 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/floating/test_contains.py +12 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/floating/test_function.py +194 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/floating/test_repr.py +47 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/floating/test_to_numpy.py +132 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/integer/__init__.py +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/integer/conftest.py +68 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/integer/test_arithmetic.py +345 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/integer/test_comparison.py +39 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/integer/test_concat.py +69 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/integer/test_construction.py +245 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/integer/test_dtypes.py +301 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/integer/test_function.py +203 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/integer/test_indexing.py +19 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/integer/test_reduction.py +123 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/integer/test_repr.py +67 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/interval/__init__.py +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/interval/test_astype.py +28 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/interval/test_formats.py +13 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/interval/test_interval.py +231 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/interval/test_interval_pyarrow.py +160 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/interval/test_overlaps.py +93 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/masked/__init__.py +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/masked/test_arithmetic.py +248 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/masked/test_arrow_compat.py +210 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/masked/test_function.py +74 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/masked/test_indexing.py +60 -0
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/categorical/test_astype.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
| 14 |
+
to_datetime,
|
| 15 |
+
)
|
| 16 |
+
import pandas._testing as tm
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class TestAstype:
|
| 20 |
+
@pytest.mark.parametrize("cls", [Categorical, CategoricalIndex])
|
| 21 |
+
@pytest.mark.parametrize("values", [[1, np.nan], [Timestamp("2000"), NaT]])
|
| 22 |
+
def test_astype_nan_to_int(self, cls, values):
|
| 23 |
+
# GH#28406
|
| 24 |
+
obj = cls(values)
|
| 25 |
+
|
| 26 |
+
msg = "Cannot (cast|convert)"
|
| 27 |
+
with pytest.raises((ValueError, TypeError), match=msg):
|
| 28 |
+
obj.astype(int)
|
| 29 |
+
|
| 30 |
+
@pytest.mark.parametrize(
|
| 31 |
+
"expected",
|
| 32 |
+
[
|
| 33 |
+
array(["2019", "2020"], dtype="datetime64[ns, UTC]"),
|
| 34 |
+
array([0, 0], dtype="timedelta64[ns]"),
|
| 35 |
+
array([Period("2019"), Period("2020")], dtype="period[Y-DEC]"),
|
| 36 |
+
array([Interval(0, 1), Interval(1, 2)], dtype="interval"),
|
| 37 |
+
array([1, np.nan], dtype="Int64"),
|
| 38 |
+
],
|
| 39 |
+
)
|
| 40 |
+
def test_astype_category_to_extension_dtype(self, expected):
|
| 41 |
+
# GH#28668
|
| 42 |
+
result = expected.astype("category").astype(expected.dtype)
|
| 43 |
+
|
| 44 |
+
tm.assert_extension_array_equal(result, expected)
|
| 45 |
+
|
| 46 |
+
@pytest.mark.parametrize(
|
| 47 |
+
"dtype, expected",
|
| 48 |
+
[
|
| 49 |
+
(
|
| 50 |
+
"datetime64[ns]",
|
| 51 |
+
np.array(["2015-01-01T00:00:00.000000000"], dtype="datetime64[ns]"),
|
| 52 |
+
),
|
| 53 |
+
(
|
| 54 |
+
"datetime64[ns, MET]",
|
| 55 |
+
DatetimeIndex([Timestamp("2015-01-01 00:00:00+0100", tz="MET")]).array,
|
| 56 |
+
),
|
| 57 |
+
],
|
| 58 |
+
)
|
| 59 |
+
def test_astype_to_datetime64(self, dtype, expected):
|
| 60 |
+
# GH#28448
|
| 61 |
+
result = Categorical(["2015-01-01"]).astype(dtype)
|
| 62 |
+
assert result == expected
|
| 63 |
+
|
| 64 |
+
def test_astype_str_int_categories_to_nullable_int(self):
|
| 65 |
+
# GH#39616
|
| 66 |
+
dtype = CategoricalDtype([str(i) for i in range(5)])
|
| 67 |
+
codes = np.random.default_rng(2).integers(5, size=20)
|
| 68 |
+
arr = Categorical.from_codes(codes, dtype=dtype)
|
| 69 |
+
|
| 70 |
+
res = arr.astype("Int64")
|
| 71 |
+
expected = array(codes, dtype="Int64")
|
| 72 |
+
tm.assert_extension_array_equal(res, expected)
|
| 73 |
+
|
| 74 |
+
def test_astype_str_int_categories_to_nullable_float(self):
|
| 75 |
+
# GH#39616
|
| 76 |
+
dtype = CategoricalDtype([str(i / 2) for i in range(5)])
|
| 77 |
+
codes = np.random.default_rng(2).integers(5, size=20)
|
| 78 |
+
arr = Categorical.from_codes(codes, dtype=dtype)
|
| 79 |
+
|
| 80 |
+
res = arr.astype("Float64")
|
| 81 |
+
expected = array(codes, dtype="Float64") / 2
|
| 82 |
+
tm.assert_extension_array_equal(res, expected)
|
| 83 |
+
|
| 84 |
+
@pytest.mark.parametrize("ordered", [True, False])
|
| 85 |
+
def test_astype(self, ordered):
|
| 86 |
+
# string
|
| 87 |
+
cat = Categorical(list("abbaaccc"), ordered=ordered)
|
| 88 |
+
result = cat.astype(object)
|
| 89 |
+
expected = np.array(cat)
|
| 90 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 91 |
+
|
| 92 |
+
msg = r"Cannot cast object|str dtype to float64"
|
| 93 |
+
with pytest.raises(ValueError, match=msg):
|
| 94 |
+
cat.astype(float)
|
| 95 |
+
|
| 96 |
+
# numeric
|
| 97 |
+
cat = Categorical([0, 1, 2, 2, 1, 0, 1, 0, 2], ordered=ordered)
|
| 98 |
+
result = cat.astype(object)
|
| 99 |
+
expected = np.array(cat, dtype=object)
|
| 100 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 101 |
+
|
| 102 |
+
result = cat.astype(int)
|
| 103 |
+
expected = np.array(cat, dtype="int")
|
| 104 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 105 |
+
|
| 106 |
+
result = cat.astype(float)
|
| 107 |
+
expected = np.array(cat, dtype=float)
|
| 108 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 109 |
+
|
| 110 |
+
@pytest.mark.parametrize("dtype_ordered", [True, False])
|
| 111 |
+
@pytest.mark.parametrize("cat_ordered", [True, False])
|
| 112 |
+
def test_astype_category(self, dtype_ordered, cat_ordered):
|
| 113 |
+
# GH#10696/GH#18593
|
| 114 |
+
data = list("abcaacbab")
|
| 115 |
+
cat = Categorical(data, categories=list("bac"), ordered=cat_ordered)
|
| 116 |
+
|
| 117 |
+
# standard categories
|
| 118 |
+
dtype = CategoricalDtype(ordered=dtype_ordered)
|
| 119 |
+
result = cat.astype(dtype)
|
| 120 |
+
expected = Categorical(data, categories=cat.categories, ordered=dtype_ordered)
|
| 121 |
+
tm.assert_categorical_equal(result, expected)
|
| 122 |
+
|
| 123 |
+
# non-standard categories
|
| 124 |
+
dtype = CategoricalDtype(list("adc"), dtype_ordered)
|
| 125 |
+
result = cat.astype(dtype)
|
| 126 |
+
expected = Categorical(data, dtype=dtype)
|
| 127 |
+
tm.assert_categorical_equal(result, expected)
|
| 128 |
+
|
| 129 |
+
if dtype_ordered is False:
|
| 130 |
+
# dtype='category' can't specify ordered, so only test once
|
| 131 |
+
result = cat.astype("category")
|
| 132 |
+
expected = cat
|
| 133 |
+
tm.assert_categorical_equal(result, expected)
|
| 134 |
+
|
| 135 |
+
def test_astype_object_datetime_categories(self):
|
| 136 |
+
# GH#40754
|
| 137 |
+
cat = Categorical(to_datetime(["2021-03-27", NaT]))
|
| 138 |
+
result = cat.astype(object)
|
| 139 |
+
expected = np.array([Timestamp("2021-03-27 00:00:00"), NaT], dtype="object")
|
| 140 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 141 |
+
|
| 142 |
+
def test_astype_object_timestamp_categories(self):
|
| 143 |
+
# GH#18024
|
| 144 |
+
cat = Categorical([Timestamp("2014-01-01")])
|
| 145 |
+
result = cat.astype(object)
|
| 146 |
+
expected = np.array([Timestamp("2014-01-01 00:00:00")], dtype="object")
|
| 147 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 148 |
+
|
| 149 |
+
def test_astype_category_readonly_mask_values(self):
|
| 150 |
+
# GH#53658
|
| 151 |
+
arr = array([0, 1, 2], dtype="Int64")
|
| 152 |
+
arr._mask.flags["WRITEABLE"] = False
|
| 153 |
+
result = arr.astype("category")
|
| 154 |
+
expected = array([0, 1, 2], dtype="Int64").astype("category")
|
| 155 |
+
tm.assert_extension_array_equal(result, expected)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/categorical/test_constructors.py
ADDED
|
@@ -0,0 +1,787 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import (
|
| 2 |
+
date,
|
| 3 |
+
datetime,
|
| 4 |
+
)
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pytest
|
| 8 |
+
|
| 9 |
+
from pandas._config import using_string_dtype
|
| 10 |
+
|
| 11 |
+
from pandas.compat import HAS_PYARROW
|
| 12 |
+
|
| 13 |
+
from pandas.core.dtypes.common import (
|
| 14 |
+
is_float_dtype,
|
| 15 |
+
is_integer_dtype,
|
| 16 |
+
)
|
| 17 |
+
from pandas.core.dtypes.dtypes import CategoricalDtype
|
| 18 |
+
|
| 19 |
+
import pandas as pd
|
| 20 |
+
from pandas import (
|
| 21 |
+
Categorical,
|
| 22 |
+
CategoricalIndex,
|
| 23 |
+
DatetimeIndex,
|
| 24 |
+
Index,
|
| 25 |
+
Interval,
|
| 26 |
+
IntervalIndex,
|
| 27 |
+
MultiIndex,
|
| 28 |
+
NaT,
|
| 29 |
+
Series,
|
| 30 |
+
Timestamp,
|
| 31 |
+
date_range,
|
| 32 |
+
period_range,
|
| 33 |
+
timedelta_range,
|
| 34 |
+
)
|
| 35 |
+
import pandas._testing as tm
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class TestCategoricalConstructors:
|
| 39 |
+
def test_fastpath_deprecated(self):
|
| 40 |
+
codes = np.array([1, 2, 3])
|
| 41 |
+
dtype = CategoricalDtype(categories=["a", "b", "c", "d"], ordered=False)
|
| 42 |
+
msg = "The 'fastpath' keyword in Categorical is deprecated"
|
| 43 |
+
with tm.assert_produces_warning(DeprecationWarning, match=msg):
|
| 44 |
+
Categorical(codes, dtype=dtype, fastpath=True)
|
| 45 |
+
|
| 46 |
+
def test_categorical_from_cat_and_dtype_str_preserve_ordered(self):
|
| 47 |
+
# GH#49309 we should preserve orderedness in `res`
|
| 48 |
+
cat = Categorical([3, 1], categories=[3, 2, 1], ordered=True)
|
| 49 |
+
|
| 50 |
+
res = Categorical(cat, dtype="category")
|
| 51 |
+
assert res.dtype.ordered
|
| 52 |
+
|
| 53 |
+
def test_categorical_disallows_scalar(self):
|
| 54 |
+
# GH#38433
|
| 55 |
+
with pytest.raises(TypeError, match="Categorical input must be list-like"):
|
| 56 |
+
Categorical("A", categories=["A", "B"])
|
| 57 |
+
|
| 58 |
+
def test_categorical_1d_only(self):
|
| 59 |
+
# ndim > 1
|
| 60 |
+
msg = "> 1 ndim Categorical are not supported at this time"
|
| 61 |
+
with pytest.raises(NotImplementedError, match=msg):
|
| 62 |
+
Categorical(np.array([list("abcd")]))
|
| 63 |
+
|
| 64 |
+
def test_validate_ordered(self):
|
| 65 |
+
# see gh-14058
|
| 66 |
+
exp_msg = "'ordered' must either be 'True' or 'False'"
|
| 67 |
+
exp_err = TypeError
|
| 68 |
+
|
| 69 |
+
# This should be a boolean.
|
| 70 |
+
ordered = np.array([0, 1, 2])
|
| 71 |
+
|
| 72 |
+
with pytest.raises(exp_err, match=exp_msg):
|
| 73 |
+
Categorical([1, 2, 3], ordered=ordered)
|
| 74 |
+
|
| 75 |
+
with pytest.raises(exp_err, match=exp_msg):
|
| 76 |
+
Categorical.from_codes(
|
| 77 |
+
[0, 0, 1], categories=["a", "b", "c"], ordered=ordered
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
def test_constructor_empty(self):
|
| 81 |
+
# GH 17248
|
| 82 |
+
c = Categorical([])
|
| 83 |
+
expected = Index([])
|
| 84 |
+
tm.assert_index_equal(c.categories, expected)
|
| 85 |
+
|
| 86 |
+
c = Categorical([], categories=[1, 2, 3])
|
| 87 |
+
expected = Index([1, 2, 3], dtype=np.int64)
|
| 88 |
+
tm.assert_index_equal(c.categories, expected)
|
| 89 |
+
|
| 90 |
+
def test_constructor_empty_boolean(self):
|
| 91 |
+
# see gh-22702
|
| 92 |
+
cat = Categorical([], categories=[True, False])
|
| 93 |
+
categories = sorted(cat.categories.tolist())
|
| 94 |
+
assert categories == [False, True]
|
| 95 |
+
|
| 96 |
+
def test_constructor_tuples(self):
|
| 97 |
+
values = np.array([(1,), (1, 2), (1,), (1, 2)], dtype=object)
|
| 98 |
+
result = Categorical(values)
|
| 99 |
+
expected = Index([(1,), (1, 2)], tupleize_cols=False)
|
| 100 |
+
tm.assert_index_equal(result.categories, expected)
|
| 101 |
+
assert result.ordered is False
|
| 102 |
+
|
| 103 |
+
def test_constructor_tuples_datetimes(self):
|
| 104 |
+
# numpy will auto reshape when all of the tuples are the
|
| 105 |
+
# same len, so add an extra one with 2 items and slice it off
|
| 106 |
+
values = np.array(
|
| 107 |
+
[
|
| 108 |
+
(Timestamp("2010-01-01"),),
|
| 109 |
+
(Timestamp("2010-01-02"),),
|
| 110 |
+
(Timestamp("2010-01-01"),),
|
| 111 |
+
(Timestamp("2010-01-02"),),
|
| 112 |
+
("a", "b"),
|
| 113 |
+
],
|
| 114 |
+
dtype=object,
|
| 115 |
+
)[:-1]
|
| 116 |
+
result = Categorical(values)
|
| 117 |
+
expected = Index(
|
| 118 |
+
[(Timestamp("2010-01-01"),), (Timestamp("2010-01-02"),)],
|
| 119 |
+
tupleize_cols=False,
|
| 120 |
+
)
|
| 121 |
+
tm.assert_index_equal(result.categories, expected)
|
| 122 |
+
|
| 123 |
+
def test_constructor_unsortable(self):
|
| 124 |
+
# it works!
|
| 125 |
+
arr = np.array([1, 2, 3, datetime.now()], dtype="O")
|
| 126 |
+
factor = Categorical(arr, ordered=False)
|
| 127 |
+
assert not factor.ordered
|
| 128 |
+
|
| 129 |
+
# this however will raise as cannot be sorted
|
| 130 |
+
msg = (
|
| 131 |
+
"'values' is not ordered, please explicitly specify the "
|
| 132 |
+
"categories order by passing in a categories argument."
|
| 133 |
+
)
|
| 134 |
+
with pytest.raises(TypeError, match=msg):
|
| 135 |
+
Categorical(arr, ordered=True)
|
| 136 |
+
|
| 137 |
+
def test_constructor_interval(self):
|
| 138 |
+
result = Categorical(
|
| 139 |
+
[Interval(1, 2), Interval(2, 3), Interval(3, 6)], ordered=True
|
| 140 |
+
)
|
| 141 |
+
ii = IntervalIndex([Interval(1, 2), Interval(2, 3), Interval(3, 6)])
|
| 142 |
+
exp = Categorical(ii, ordered=True)
|
| 143 |
+
tm.assert_categorical_equal(result, exp)
|
| 144 |
+
tm.assert_index_equal(result.categories, ii)
|
| 145 |
+
|
| 146 |
+
def test_constructor(self):
|
| 147 |
+
exp_arr = np.array(["a", "b", "c", "a", "b", "c"], dtype=np.object_)
|
| 148 |
+
c1 = Categorical(exp_arr)
|
| 149 |
+
tm.assert_numpy_array_equal(c1.__array__(), exp_arr)
|
| 150 |
+
c2 = Categorical(exp_arr, categories=["a", "b", "c"])
|
| 151 |
+
tm.assert_numpy_array_equal(c2.__array__(), exp_arr)
|
| 152 |
+
c2 = Categorical(exp_arr, categories=["c", "b", "a"])
|
| 153 |
+
tm.assert_numpy_array_equal(c2.__array__(), exp_arr)
|
| 154 |
+
|
| 155 |
+
# categories must be unique
|
| 156 |
+
msg = "Categorical categories must be unique"
|
| 157 |
+
with pytest.raises(ValueError, match=msg):
|
| 158 |
+
Categorical([1, 2], [1, 2, 2])
|
| 159 |
+
|
| 160 |
+
with pytest.raises(ValueError, match=msg):
|
| 161 |
+
Categorical(["a", "b"], ["a", "b", "b"])
|
| 162 |
+
|
| 163 |
+
# The default should be unordered
|
| 164 |
+
c1 = Categorical(["a", "b", "c", "a"])
|
| 165 |
+
assert not c1.ordered
|
| 166 |
+
|
| 167 |
+
# Categorical as input
|
| 168 |
+
c1 = Categorical(["a", "b", "c", "a"])
|
| 169 |
+
c2 = Categorical(c1)
|
| 170 |
+
tm.assert_categorical_equal(c1, c2)
|
| 171 |
+
|
| 172 |
+
c1 = Categorical(["a", "b", "c", "a"], categories=["a", "b", "c", "d"])
|
| 173 |
+
c2 = Categorical(c1)
|
| 174 |
+
tm.assert_categorical_equal(c1, c2)
|
| 175 |
+
|
| 176 |
+
c1 = Categorical(["a", "b", "c", "a"], categories=["a", "c", "b"])
|
| 177 |
+
c2 = Categorical(c1)
|
| 178 |
+
tm.assert_categorical_equal(c1, c2)
|
| 179 |
+
|
| 180 |
+
c1 = Categorical(["a", "b", "c", "a"], categories=["a", "c", "b"])
|
| 181 |
+
c2 = Categorical(c1, categories=["a", "b", "c"])
|
| 182 |
+
tm.assert_numpy_array_equal(c1.__array__(), c2.__array__())
|
| 183 |
+
tm.assert_index_equal(c2.categories, Index(["a", "b", "c"]))
|
| 184 |
+
|
| 185 |
+
# Series of dtype category
|
| 186 |
+
c1 = Categorical(["a", "b", "c", "a"], categories=["a", "b", "c", "d"])
|
| 187 |
+
c2 = Categorical(Series(c1))
|
| 188 |
+
tm.assert_categorical_equal(c1, c2)
|
| 189 |
+
|
| 190 |
+
c1 = Categorical(["a", "b", "c", "a"], categories=["a", "c", "b"])
|
| 191 |
+
c2 = Categorical(Series(c1))
|
| 192 |
+
tm.assert_categorical_equal(c1, c2)
|
| 193 |
+
|
| 194 |
+
# Series
|
| 195 |
+
c1 = Categorical(["a", "b", "c", "a"])
|
| 196 |
+
c2 = Categorical(Series(["a", "b", "c", "a"]))
|
| 197 |
+
tm.assert_categorical_equal(c1, c2)
|
| 198 |
+
|
| 199 |
+
c1 = Categorical(["a", "b", "c", "a"], categories=["a", "b", "c", "d"])
|
| 200 |
+
c2 = Categorical(Series(["a", "b", "c", "a"]), categories=["a", "b", "c", "d"])
|
| 201 |
+
tm.assert_categorical_equal(c1, c2)
|
| 202 |
+
|
| 203 |
+
# This should result in integer categories, not float!
|
| 204 |
+
cat = Categorical([1, 2, 3, np.nan], categories=[1, 2, 3])
|
| 205 |
+
assert is_integer_dtype(cat.categories)
|
| 206 |
+
|
| 207 |
+
# https://github.com/pandas-dev/pandas/issues/3678
|
| 208 |
+
cat = Categorical([np.nan, 1, 2, 3])
|
| 209 |
+
assert is_integer_dtype(cat.categories)
|
| 210 |
+
|
| 211 |
+
# this should result in floats
|
| 212 |
+
cat = Categorical([np.nan, 1, 2.0, 3])
|
| 213 |
+
assert is_float_dtype(cat.categories)
|
| 214 |
+
|
| 215 |
+
cat = Categorical([np.nan, 1.0, 2.0, 3.0])
|
| 216 |
+
assert is_float_dtype(cat.categories)
|
| 217 |
+
|
| 218 |
+
# This doesn't work -> this would probably need some kind of "remember
|
| 219 |
+
# the original type" feature to try to cast the array interface result
|
| 220 |
+
# to...
|
| 221 |
+
|
| 222 |
+
# vals = np.asarray(cat[cat.notna()])
|
| 223 |
+
# assert is_integer_dtype(vals)
|
| 224 |
+
|
| 225 |
+
# corner cases
|
| 226 |
+
cat = Categorical([1])
|
| 227 |
+
assert len(cat.categories) == 1
|
| 228 |
+
assert cat.categories[0] == 1
|
| 229 |
+
assert len(cat.codes) == 1
|
| 230 |
+
assert cat.codes[0] == 0
|
| 231 |
+
|
| 232 |
+
cat = Categorical(["a"])
|
| 233 |
+
assert len(cat.categories) == 1
|
| 234 |
+
assert cat.categories[0] == "a"
|
| 235 |
+
assert len(cat.codes) == 1
|
| 236 |
+
assert cat.codes[0] == 0
|
| 237 |
+
|
| 238 |
+
# two arrays
|
| 239 |
+
# - when the first is an integer dtype and the second is not
|
| 240 |
+
# - when the resulting codes are all -1/NaN
|
| 241 |
+
with tm.assert_produces_warning(None):
|
| 242 |
+
Categorical([0, 1, 2, 0, 1, 2], categories=["a", "b", "c"])
|
| 243 |
+
|
| 244 |
+
with tm.assert_produces_warning(None):
|
| 245 |
+
Categorical([0, 1, 2, 0, 1, 2], categories=[3, 4, 5])
|
| 246 |
+
|
| 247 |
+
# the next one are from the old docs
|
| 248 |
+
with tm.assert_produces_warning(None):
|
| 249 |
+
Categorical([0, 1, 2, 0, 1, 2], [1, 2, 3])
|
| 250 |
+
cat = Categorical([1, 2], categories=[1, 2, 3])
|
| 251 |
+
|
| 252 |
+
# this is a legitimate constructor
|
| 253 |
+
with tm.assert_produces_warning(None):
|
| 254 |
+
Categorical(np.array([], dtype="int64"), categories=[3, 2, 1], ordered=True)
|
| 255 |
+
|
| 256 |
+
def test_constructor_with_existing_categories(self):
|
| 257 |
+
# GH25318: constructing with pd.Series used to bogusly skip recoding
|
| 258 |
+
# categories
|
| 259 |
+
c0 = Categorical(["a", "b", "c", "a"])
|
| 260 |
+
c1 = Categorical(["a", "b", "c", "a"], categories=["b", "c"])
|
| 261 |
+
|
| 262 |
+
c2 = Categorical(c0, categories=c1.categories)
|
| 263 |
+
tm.assert_categorical_equal(c1, c2)
|
| 264 |
+
|
| 265 |
+
c3 = Categorical(Series(c0), categories=c1.categories)
|
| 266 |
+
tm.assert_categorical_equal(c1, c3)
|
| 267 |
+
|
| 268 |
+
def test_constructor_not_sequence(self):
|
| 269 |
+
# https://github.com/pandas-dev/pandas/issues/16022
|
| 270 |
+
msg = r"^Parameter 'categories' must be list-like, was"
|
| 271 |
+
with pytest.raises(TypeError, match=msg):
|
| 272 |
+
Categorical(["a", "b"], categories="a")
|
| 273 |
+
|
| 274 |
+
def test_constructor_with_null(self):
|
| 275 |
+
# Cannot have NaN in categories
|
| 276 |
+
msg = "Categorical categories cannot be null"
|
| 277 |
+
with pytest.raises(ValueError, match=msg):
|
| 278 |
+
Categorical([np.nan, "a", "b", "c"], categories=[np.nan, "a", "b", "c"])
|
| 279 |
+
|
| 280 |
+
with pytest.raises(ValueError, match=msg):
|
| 281 |
+
Categorical([None, "a", "b", "c"], categories=[None, "a", "b", "c"])
|
| 282 |
+
|
| 283 |
+
with pytest.raises(ValueError, match=msg):
|
| 284 |
+
Categorical(
|
| 285 |
+
DatetimeIndex(["nat", "20160101"]),
|
| 286 |
+
categories=[NaT, Timestamp("20160101")],
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
def test_constructor_with_index(self):
|
| 290 |
+
ci = CategoricalIndex(list("aabbca"), categories=list("cab"))
|
| 291 |
+
tm.assert_categorical_equal(ci.values, Categorical(ci))
|
| 292 |
+
|
| 293 |
+
ci = CategoricalIndex(list("aabbca"), categories=list("cab"))
|
| 294 |
+
tm.assert_categorical_equal(
|
| 295 |
+
ci.values, Categorical(ci.astype(object), categories=ci.categories)
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
def test_constructor_with_generator(self):
|
| 299 |
+
# This was raising an Error in isna(single_val).any() because isna
|
| 300 |
+
# returned a scalar for a generator
|
| 301 |
+
|
| 302 |
+
exp = Categorical([0, 1, 2])
|
| 303 |
+
cat = Categorical(x for x in [0, 1, 2])
|
| 304 |
+
tm.assert_categorical_equal(cat, exp)
|
| 305 |
+
cat = Categorical(range(3))
|
| 306 |
+
tm.assert_categorical_equal(cat, exp)
|
| 307 |
+
|
| 308 |
+
MultiIndex.from_product([range(5), ["a", "b", "c"]])
|
| 309 |
+
|
| 310 |
+
# check that categories accept generators and sequences
|
| 311 |
+
cat = Categorical([0, 1, 2], categories=(x for x in [0, 1, 2]))
|
| 312 |
+
tm.assert_categorical_equal(cat, exp)
|
| 313 |
+
cat = Categorical([0, 1, 2], categories=range(3))
|
| 314 |
+
tm.assert_categorical_equal(cat, exp)
|
| 315 |
+
|
| 316 |
+
def test_constructor_with_rangeindex(self):
|
| 317 |
+
# RangeIndex is preserved in Categories
|
| 318 |
+
rng = Index(range(3))
|
| 319 |
+
|
| 320 |
+
cat = Categorical(rng)
|
| 321 |
+
tm.assert_index_equal(cat.categories, rng, exact=True)
|
| 322 |
+
|
| 323 |
+
cat = Categorical([1, 2, 0], categories=rng)
|
| 324 |
+
tm.assert_index_equal(cat.categories, rng, exact=True)
|
| 325 |
+
|
| 326 |
+
@pytest.mark.parametrize(
|
| 327 |
+
"dtl",
|
| 328 |
+
[
|
| 329 |
+
date_range("1995-01-01 00:00:00", periods=5, freq="s"),
|
| 330 |
+
date_range("1995-01-01 00:00:00", periods=5, freq="s", tz="US/Eastern"),
|
| 331 |
+
timedelta_range("1 day", periods=5, freq="s"),
|
| 332 |
+
],
|
| 333 |
+
)
|
| 334 |
+
def test_constructor_with_datetimelike(self, dtl):
|
| 335 |
+
# see gh-12077
|
| 336 |
+
# constructor with a datetimelike and NaT
|
| 337 |
+
|
| 338 |
+
s = Series(dtl)
|
| 339 |
+
c = Categorical(s)
|
| 340 |
+
|
| 341 |
+
expected = type(dtl)(s)
|
| 342 |
+
expected._data.freq = None
|
| 343 |
+
|
| 344 |
+
tm.assert_index_equal(c.categories, expected)
|
| 345 |
+
tm.assert_numpy_array_equal(c.codes, np.arange(5, dtype="int8"))
|
| 346 |
+
|
| 347 |
+
# with NaT
|
| 348 |
+
s2 = s.copy()
|
| 349 |
+
s2.iloc[-1] = NaT
|
| 350 |
+
c = Categorical(s2)
|
| 351 |
+
|
| 352 |
+
expected = type(dtl)(s2.dropna())
|
| 353 |
+
expected._data.freq = None
|
| 354 |
+
|
| 355 |
+
tm.assert_index_equal(c.categories, expected)
|
| 356 |
+
|
| 357 |
+
exp = np.array([0, 1, 2, 3, -1], dtype=np.int8)
|
| 358 |
+
tm.assert_numpy_array_equal(c.codes, exp)
|
| 359 |
+
|
| 360 |
+
result = repr(c)
|
| 361 |
+
assert "NaT" in result
|
| 362 |
+
|
| 363 |
+
def test_constructor_from_index_series_datetimetz(self):
|
| 364 |
+
idx = date_range("2015-01-01 10:00", freq="D", periods=3, tz="US/Eastern")
|
| 365 |
+
idx = idx._with_freq(None) # freq not preserved in result.categories
|
| 366 |
+
result = Categorical(idx)
|
| 367 |
+
tm.assert_index_equal(result.categories, idx)
|
| 368 |
+
|
| 369 |
+
result = Categorical(Series(idx))
|
| 370 |
+
tm.assert_index_equal(result.categories, idx)
|
| 371 |
+
|
| 372 |
+
def test_constructor_date_objects(self):
|
| 373 |
+
# we dont cast date objects to timestamps, matching Index constructor
|
| 374 |
+
v = date.today()
|
| 375 |
+
|
| 376 |
+
cat = Categorical([v, v])
|
| 377 |
+
assert cat.categories.dtype == object
|
| 378 |
+
assert type(cat.categories[0]) is date
|
| 379 |
+
|
| 380 |
+
def test_constructor_from_index_series_timedelta(self):
|
| 381 |
+
idx = timedelta_range("1 days", freq="D", periods=3)
|
| 382 |
+
idx = idx._with_freq(None) # freq not preserved in result.categories
|
| 383 |
+
result = Categorical(idx)
|
| 384 |
+
tm.assert_index_equal(result.categories, idx)
|
| 385 |
+
|
| 386 |
+
result = Categorical(Series(idx))
|
| 387 |
+
tm.assert_index_equal(result.categories, idx)
|
| 388 |
+
|
| 389 |
+
def test_constructor_from_index_series_period(self):
|
| 390 |
+
idx = period_range("2015-01-01", freq="D", periods=3)
|
| 391 |
+
result = Categorical(idx)
|
| 392 |
+
tm.assert_index_equal(result.categories, idx)
|
| 393 |
+
|
| 394 |
+
result = Categorical(Series(idx))
|
| 395 |
+
tm.assert_index_equal(result.categories, idx)
|
| 396 |
+
|
| 397 |
+
@pytest.mark.parametrize(
|
| 398 |
+
"values",
|
| 399 |
+
[
|
| 400 |
+
np.array([1.0, 1.2, 1.8, np.nan]),
|
| 401 |
+
np.array([1, 2, 3], dtype="int64"),
|
| 402 |
+
["a", "b", "c", np.nan],
|
| 403 |
+
[pd.Period("2014-01"), pd.Period("2014-02"), NaT],
|
| 404 |
+
[Timestamp("2014-01-01"), Timestamp("2014-01-02"), NaT],
|
| 405 |
+
[
|
| 406 |
+
Timestamp("2014-01-01", tz="US/Eastern"),
|
| 407 |
+
Timestamp("2014-01-02", tz="US/Eastern"),
|
| 408 |
+
NaT,
|
| 409 |
+
],
|
| 410 |
+
],
|
| 411 |
+
)
|
| 412 |
+
def test_constructor_invariant(self, values):
|
| 413 |
+
# GH 14190
|
| 414 |
+
c = Categorical(values)
|
| 415 |
+
c2 = Categorical(c)
|
| 416 |
+
tm.assert_categorical_equal(c, c2)
|
| 417 |
+
|
| 418 |
+
@pytest.mark.parametrize("ordered", [True, False])
|
| 419 |
+
def test_constructor_with_dtype(self, ordered):
|
| 420 |
+
categories = ["b", "a", "c"]
|
| 421 |
+
dtype = CategoricalDtype(categories, ordered=ordered)
|
| 422 |
+
result = Categorical(["a", "b", "a", "c"], dtype=dtype)
|
| 423 |
+
expected = Categorical(
|
| 424 |
+
["a", "b", "a", "c"], categories=categories, ordered=ordered
|
| 425 |
+
)
|
| 426 |
+
tm.assert_categorical_equal(result, expected)
|
| 427 |
+
assert result.ordered is ordered
|
| 428 |
+
|
| 429 |
+
def test_constructor_dtype_and_others_raises(self):
|
| 430 |
+
dtype = CategoricalDtype(["a", "b"], ordered=True)
|
| 431 |
+
msg = "Cannot specify `categories` or `ordered` together with `dtype`."
|
| 432 |
+
with pytest.raises(ValueError, match=msg):
|
| 433 |
+
Categorical(["a", "b"], categories=["a", "b"], dtype=dtype)
|
| 434 |
+
|
| 435 |
+
with pytest.raises(ValueError, match=msg):
|
| 436 |
+
Categorical(["a", "b"], ordered=True, dtype=dtype)
|
| 437 |
+
|
| 438 |
+
with pytest.raises(ValueError, match=msg):
|
| 439 |
+
Categorical(["a", "b"], ordered=False, dtype=dtype)
|
| 440 |
+
|
| 441 |
+
@pytest.mark.parametrize("categories", [None, ["a", "b"], ["a", "c"]])
|
| 442 |
+
@pytest.mark.parametrize("ordered", [True, False])
|
| 443 |
+
def test_constructor_str_category(self, categories, ordered):
|
| 444 |
+
result = Categorical(
|
| 445 |
+
["a", "b"], categories=categories, ordered=ordered, dtype="category"
|
| 446 |
+
)
|
| 447 |
+
expected = Categorical(["a", "b"], categories=categories, ordered=ordered)
|
| 448 |
+
tm.assert_categorical_equal(result, expected)
|
| 449 |
+
|
| 450 |
+
def test_constructor_str_unknown(self):
|
| 451 |
+
with pytest.raises(ValueError, match="Unknown dtype"):
|
| 452 |
+
Categorical([1, 2], dtype="foo")
|
| 453 |
+
|
| 454 |
+
@pytest.mark.xfail(
|
| 455 |
+
using_string_dtype() and HAS_PYARROW, reason="Can't be NumPy strings"
|
| 456 |
+
)
|
| 457 |
+
def test_constructor_np_strs(self):
|
| 458 |
+
# GH#31499 Hashtable.map_locations needs to work on np.str_ objects
|
| 459 |
+
cat = Categorical(["1", "0", "1"], [np.str_("0"), np.str_("1")])
|
| 460 |
+
assert all(isinstance(x, np.str_) for x in cat.categories)
|
| 461 |
+
|
| 462 |
+
def test_constructor_from_categorical_with_dtype(self):
|
| 463 |
+
dtype = CategoricalDtype(["a", "b", "c"], ordered=True)
|
| 464 |
+
values = Categorical(["a", "b", "d"])
|
| 465 |
+
result = Categorical(values, dtype=dtype)
|
| 466 |
+
# We use dtype.categories, not values.categories
|
| 467 |
+
expected = Categorical(
|
| 468 |
+
["a", "b", "d"], categories=["a", "b", "c"], ordered=True
|
| 469 |
+
)
|
| 470 |
+
tm.assert_categorical_equal(result, expected)
|
| 471 |
+
|
| 472 |
+
def test_constructor_from_categorical_with_unknown_dtype(self):
|
| 473 |
+
dtype = CategoricalDtype(None, ordered=True)
|
| 474 |
+
values = Categorical(["a", "b", "d"])
|
| 475 |
+
result = Categorical(values, dtype=dtype)
|
| 476 |
+
# We use values.categories, not dtype.categories
|
| 477 |
+
expected = Categorical(
|
| 478 |
+
["a", "b", "d"], categories=["a", "b", "d"], ordered=True
|
| 479 |
+
)
|
| 480 |
+
tm.assert_categorical_equal(result, expected)
|
| 481 |
+
|
| 482 |
+
def test_constructor_from_categorical_string(self):
|
| 483 |
+
values = Categorical(["a", "b", "d"])
|
| 484 |
+
# use categories, ordered
|
| 485 |
+
result = Categorical(
|
| 486 |
+
values, categories=["a", "b", "c"], ordered=True, dtype="category"
|
| 487 |
+
)
|
| 488 |
+
expected = Categorical(
|
| 489 |
+
["a", "b", "d"], categories=["a", "b", "c"], ordered=True
|
| 490 |
+
)
|
| 491 |
+
tm.assert_categorical_equal(result, expected)
|
| 492 |
+
|
| 493 |
+
# No string
|
| 494 |
+
result = Categorical(values, categories=["a", "b", "c"], ordered=True)
|
| 495 |
+
tm.assert_categorical_equal(result, expected)
|
| 496 |
+
|
| 497 |
+
def test_constructor_with_categorical_categories(self):
|
| 498 |
+
# GH17884
|
| 499 |
+
expected = Categorical(["a", "b"], categories=["a", "b", "c"])
|
| 500 |
+
|
| 501 |
+
result = Categorical(["a", "b"], categories=Categorical(["a", "b", "c"]))
|
| 502 |
+
tm.assert_categorical_equal(result, expected)
|
| 503 |
+
|
| 504 |
+
result = Categorical(["a", "b"], categories=CategoricalIndex(["a", "b", "c"]))
|
| 505 |
+
tm.assert_categorical_equal(result, expected)
|
| 506 |
+
|
| 507 |
+
@pytest.mark.parametrize("klass", [lambda x: np.array(x, dtype=object), list])
|
| 508 |
+
def test_construction_with_null(self, klass, nulls_fixture):
|
| 509 |
+
# https://github.com/pandas-dev/pandas/issues/31927
|
| 510 |
+
values = klass(["a", nulls_fixture, "b"])
|
| 511 |
+
result = Categorical(values)
|
| 512 |
+
|
| 513 |
+
dtype = CategoricalDtype(["a", "b"])
|
| 514 |
+
codes = [0, -1, 1]
|
| 515 |
+
expected = Categorical.from_codes(codes=codes, dtype=dtype)
|
| 516 |
+
|
| 517 |
+
tm.assert_categorical_equal(result, expected)
|
| 518 |
+
|
| 519 |
+
@pytest.mark.parametrize("validate", [True, False])
|
| 520 |
+
def test_from_codes_nullable_int_categories(self, any_numeric_ea_dtype, validate):
|
| 521 |
+
# GH#39649
|
| 522 |
+
cats = pd.array(range(5), dtype=any_numeric_ea_dtype)
|
| 523 |
+
codes = np.random.default_rng(2).integers(5, size=3)
|
| 524 |
+
dtype = CategoricalDtype(cats)
|
| 525 |
+
arr = Categorical.from_codes(codes, dtype=dtype, validate=validate)
|
| 526 |
+
assert arr.categories.dtype == cats.dtype
|
| 527 |
+
tm.assert_index_equal(arr.categories, Index(cats))
|
| 528 |
+
|
| 529 |
+
def test_from_codes_empty(self):
|
| 530 |
+
cat = ["a", "b", "c"]
|
| 531 |
+
result = Categorical.from_codes([], categories=cat)
|
| 532 |
+
expected = Categorical([], categories=cat)
|
| 533 |
+
|
| 534 |
+
tm.assert_categorical_equal(result, expected)
|
| 535 |
+
|
| 536 |
+
@pytest.mark.parametrize("validate", [True, False])
|
| 537 |
+
def test_from_codes_validate(self, validate):
|
| 538 |
+
# GH53122
|
| 539 |
+
dtype = CategoricalDtype(["a", "b"])
|
| 540 |
+
if validate:
|
| 541 |
+
with pytest.raises(ValueError, match="codes need to be between "):
|
| 542 |
+
Categorical.from_codes([4, 5], dtype=dtype, validate=validate)
|
| 543 |
+
else:
|
| 544 |
+
# passes, though has incorrect codes, but that's the user responsibility
|
| 545 |
+
Categorical.from_codes([4, 5], dtype=dtype, validate=validate)
|
| 546 |
+
|
| 547 |
+
def test_from_codes_too_few_categories(self):
|
| 548 |
+
dtype = CategoricalDtype(categories=[1, 2])
|
| 549 |
+
msg = "codes need to be between "
|
| 550 |
+
with pytest.raises(ValueError, match=msg):
|
| 551 |
+
Categorical.from_codes([1, 2], categories=dtype.categories)
|
| 552 |
+
with pytest.raises(ValueError, match=msg):
|
| 553 |
+
Categorical.from_codes([1, 2], dtype=dtype)
|
| 554 |
+
|
| 555 |
+
def test_from_codes_non_int_codes(self):
|
| 556 |
+
dtype = CategoricalDtype(categories=[1, 2])
|
| 557 |
+
msg = "codes need to be array-like integers"
|
| 558 |
+
with pytest.raises(ValueError, match=msg):
|
| 559 |
+
Categorical.from_codes(["a"], categories=dtype.categories)
|
| 560 |
+
with pytest.raises(ValueError, match=msg):
|
| 561 |
+
Categorical.from_codes(["a"], dtype=dtype)
|
| 562 |
+
|
| 563 |
+
def test_from_codes_non_unique_categories(self):
|
| 564 |
+
with pytest.raises(ValueError, match="Categorical categories must be unique"):
|
| 565 |
+
Categorical.from_codes([0, 1, 2], categories=["a", "a", "b"])
|
| 566 |
+
|
| 567 |
+
def test_from_codes_nan_cat_included(self):
|
| 568 |
+
with pytest.raises(ValueError, match="Categorical categories cannot be null"):
|
| 569 |
+
Categorical.from_codes([0, 1, 2], categories=["a", "b", np.nan])
|
| 570 |
+
|
| 571 |
+
def test_from_codes_too_negative(self):
|
| 572 |
+
dtype = CategoricalDtype(categories=["a", "b", "c"])
|
| 573 |
+
msg = r"codes need to be between -1 and len\(categories\)-1"
|
| 574 |
+
with pytest.raises(ValueError, match=msg):
|
| 575 |
+
Categorical.from_codes([-2, 1, 2], categories=dtype.categories)
|
| 576 |
+
with pytest.raises(ValueError, match=msg):
|
| 577 |
+
Categorical.from_codes([-2, 1, 2], dtype=dtype)
|
| 578 |
+
|
| 579 |
+
def test_from_codes(self):
|
| 580 |
+
dtype = CategoricalDtype(categories=["a", "b", "c"])
|
| 581 |
+
exp = Categorical(["a", "b", "c"], ordered=False)
|
| 582 |
+
res = Categorical.from_codes([0, 1, 2], categories=dtype.categories)
|
| 583 |
+
tm.assert_categorical_equal(exp, res)
|
| 584 |
+
|
| 585 |
+
res = Categorical.from_codes([0, 1, 2], dtype=dtype)
|
| 586 |
+
tm.assert_categorical_equal(exp, res)
|
| 587 |
+
|
| 588 |
+
@pytest.mark.parametrize("klass", [Categorical, CategoricalIndex])
|
| 589 |
+
def test_from_codes_with_categorical_categories(self, klass):
|
| 590 |
+
# GH17884
|
| 591 |
+
expected = Categorical(["a", "b"], categories=["a", "b", "c"])
|
| 592 |
+
|
| 593 |
+
result = Categorical.from_codes([0, 1], categories=klass(["a", "b", "c"]))
|
| 594 |
+
tm.assert_categorical_equal(result, expected)
|
| 595 |
+
|
| 596 |
+
@pytest.mark.parametrize("klass", [Categorical, CategoricalIndex])
|
| 597 |
+
def test_from_codes_with_non_unique_categorical_categories(self, klass):
|
| 598 |
+
with pytest.raises(ValueError, match="Categorical categories must be unique"):
|
| 599 |
+
Categorical.from_codes([0, 1], klass(["a", "b", "a"]))
|
| 600 |
+
|
| 601 |
+
def test_from_codes_with_nan_code(self):
|
| 602 |
+
# GH21767
|
| 603 |
+
codes = [1, 2, np.nan]
|
| 604 |
+
dtype = CategoricalDtype(categories=["a", "b", "c"])
|
| 605 |
+
with pytest.raises(ValueError, match="codes need to be array-like integers"):
|
| 606 |
+
Categorical.from_codes(codes, categories=dtype.categories)
|
| 607 |
+
with pytest.raises(ValueError, match="codes need to be array-like integers"):
|
| 608 |
+
Categorical.from_codes(codes, dtype=dtype)
|
| 609 |
+
|
| 610 |
+
@pytest.mark.parametrize("codes", [[1.0, 2.0, 0], [1.1, 2.0, 0]])
|
| 611 |
+
def test_from_codes_with_float(self, codes):
|
| 612 |
+
# GH21767
|
| 613 |
+
# float codes should raise even if values are equal to integers
|
| 614 |
+
dtype = CategoricalDtype(categories=["a", "b", "c"])
|
| 615 |
+
|
| 616 |
+
msg = "codes need to be array-like integers"
|
| 617 |
+
with pytest.raises(ValueError, match=msg):
|
| 618 |
+
Categorical.from_codes(codes, dtype.categories)
|
| 619 |
+
with pytest.raises(ValueError, match=msg):
|
| 620 |
+
Categorical.from_codes(codes, dtype=dtype)
|
| 621 |
+
|
| 622 |
+
def test_from_codes_with_dtype_raises(self):
|
| 623 |
+
msg = "Cannot specify"
|
| 624 |
+
with pytest.raises(ValueError, match=msg):
|
| 625 |
+
Categorical.from_codes(
|
| 626 |
+
[0, 1], categories=["a", "b"], dtype=CategoricalDtype(["a", "b"])
|
| 627 |
+
)
|
| 628 |
+
|
| 629 |
+
with pytest.raises(ValueError, match=msg):
|
| 630 |
+
Categorical.from_codes(
|
| 631 |
+
[0, 1], ordered=True, dtype=CategoricalDtype(["a", "b"])
|
| 632 |
+
)
|
| 633 |
+
|
| 634 |
+
def test_from_codes_neither(self):
|
| 635 |
+
msg = "Both were None"
|
| 636 |
+
with pytest.raises(ValueError, match=msg):
|
| 637 |
+
Categorical.from_codes([0, 1])
|
| 638 |
+
|
| 639 |
+
def test_from_codes_with_nullable_int(self):
|
| 640 |
+
codes = pd.array([0, 1], dtype="Int64")
|
| 641 |
+
categories = ["a", "b"]
|
| 642 |
+
|
| 643 |
+
result = Categorical.from_codes(codes, categories=categories)
|
| 644 |
+
expected = Categorical.from_codes(codes.to_numpy(int), categories=categories)
|
| 645 |
+
|
| 646 |
+
tm.assert_categorical_equal(result, expected)
|
| 647 |
+
|
| 648 |
+
def test_from_codes_with_nullable_int_na_raises(self):
|
| 649 |
+
codes = pd.array([0, None], dtype="Int64")
|
| 650 |
+
categories = ["a", "b"]
|
| 651 |
+
|
| 652 |
+
msg = "codes cannot contain NA values"
|
| 653 |
+
with pytest.raises(ValueError, match=msg):
|
| 654 |
+
Categorical.from_codes(codes, categories=categories)
|
| 655 |
+
|
| 656 |
+
@pytest.mark.parametrize("dtype", [None, "category"])
|
| 657 |
+
def test_from_inferred_categories(self, dtype):
|
| 658 |
+
cats = ["a", "b"]
|
| 659 |
+
codes = np.array([0, 0, 1, 1], dtype="i8")
|
| 660 |
+
result = Categorical._from_inferred_categories(cats, codes, dtype)
|
| 661 |
+
expected = Categorical.from_codes(codes, cats)
|
| 662 |
+
tm.assert_categorical_equal(result, expected)
|
| 663 |
+
|
| 664 |
+
@pytest.mark.parametrize("dtype", [None, "category"])
|
| 665 |
+
def test_from_inferred_categories_sorts(self, dtype):
|
| 666 |
+
cats = ["b", "a"]
|
| 667 |
+
codes = np.array([0, 1, 1, 1], dtype="i8")
|
| 668 |
+
result = Categorical._from_inferred_categories(cats, codes, dtype)
|
| 669 |
+
expected = Categorical.from_codes([1, 0, 0, 0], ["a", "b"])
|
| 670 |
+
tm.assert_categorical_equal(result, expected)
|
| 671 |
+
|
| 672 |
+
def test_from_inferred_categories_dtype(self):
|
| 673 |
+
cats = ["a", "b", "d"]
|
| 674 |
+
codes = np.array([0, 1, 0, 2], dtype="i8")
|
| 675 |
+
dtype = CategoricalDtype(["c", "b", "a"], ordered=True)
|
| 676 |
+
result = Categorical._from_inferred_categories(cats, codes, dtype)
|
| 677 |
+
expected = Categorical(
|
| 678 |
+
["a", "b", "a", "d"], categories=["c", "b", "a"], ordered=True
|
| 679 |
+
)
|
| 680 |
+
tm.assert_categorical_equal(result, expected)
|
| 681 |
+
|
| 682 |
+
def test_from_inferred_categories_coerces(self):
|
| 683 |
+
cats = ["1", "2", "bad"]
|
| 684 |
+
codes = np.array([0, 0, 1, 2], dtype="i8")
|
| 685 |
+
dtype = CategoricalDtype([1, 2])
|
| 686 |
+
result = Categorical._from_inferred_categories(cats, codes, dtype)
|
| 687 |
+
expected = Categorical([1, 1, 2, np.nan])
|
| 688 |
+
tm.assert_categorical_equal(result, expected)
|
| 689 |
+
|
| 690 |
+
@pytest.mark.parametrize("ordered", [None, True, False])
|
| 691 |
+
def test_construction_with_ordered(self, ordered):
|
| 692 |
+
# GH 9347, 9190
|
| 693 |
+
cat = Categorical([0, 1, 2], ordered=ordered)
|
| 694 |
+
assert cat.ordered == bool(ordered)
|
| 695 |
+
|
| 696 |
+
def test_constructor_imaginary(self):
|
| 697 |
+
values = [1, 2, 3 + 1j]
|
| 698 |
+
c1 = Categorical(values)
|
| 699 |
+
tm.assert_index_equal(c1.categories, Index(values))
|
| 700 |
+
tm.assert_numpy_array_equal(np.array(c1), np.array(values))
|
| 701 |
+
|
| 702 |
+
def test_constructor_string_and_tuples(self):
|
| 703 |
+
# GH 21416
|
| 704 |
+
c = Categorical(np.array(["c", ("a", "b"), ("b", "a"), "c"], dtype=object))
|
| 705 |
+
expected_index = Index([("a", "b"), ("b", "a"), "c"])
|
| 706 |
+
assert c.categories.equals(expected_index)
|
| 707 |
+
|
| 708 |
+
def test_interval(self):
|
| 709 |
+
idx = pd.interval_range(0, 10, periods=10)
|
| 710 |
+
cat = Categorical(idx, categories=idx)
|
| 711 |
+
expected_codes = np.arange(10, dtype="int8")
|
| 712 |
+
tm.assert_numpy_array_equal(cat.codes, expected_codes)
|
| 713 |
+
tm.assert_index_equal(cat.categories, idx)
|
| 714 |
+
|
| 715 |
+
# infer categories
|
| 716 |
+
cat = Categorical(idx)
|
| 717 |
+
tm.assert_numpy_array_equal(cat.codes, expected_codes)
|
| 718 |
+
tm.assert_index_equal(cat.categories, idx)
|
| 719 |
+
|
| 720 |
+
# list values
|
| 721 |
+
cat = Categorical(list(idx))
|
| 722 |
+
tm.assert_numpy_array_equal(cat.codes, expected_codes)
|
| 723 |
+
tm.assert_index_equal(cat.categories, idx)
|
| 724 |
+
|
| 725 |
+
# list values, categories
|
| 726 |
+
cat = Categorical(list(idx), categories=list(idx))
|
| 727 |
+
tm.assert_numpy_array_equal(cat.codes, expected_codes)
|
| 728 |
+
tm.assert_index_equal(cat.categories, idx)
|
| 729 |
+
|
| 730 |
+
# shuffled
|
| 731 |
+
values = idx.take([1, 2, 0])
|
| 732 |
+
cat = Categorical(values, categories=idx)
|
| 733 |
+
tm.assert_numpy_array_equal(cat.codes, np.array([1, 2, 0], dtype="int8"))
|
| 734 |
+
tm.assert_index_equal(cat.categories, idx)
|
| 735 |
+
|
| 736 |
+
# extra
|
| 737 |
+
values = pd.interval_range(8, 11, periods=3)
|
| 738 |
+
cat = Categorical(values, categories=idx)
|
| 739 |
+
expected_codes = np.array([8, 9, -1], dtype="int8")
|
| 740 |
+
tm.assert_numpy_array_equal(cat.codes, expected_codes)
|
| 741 |
+
tm.assert_index_equal(cat.categories, idx)
|
| 742 |
+
|
| 743 |
+
# overlapping
|
| 744 |
+
idx = IntervalIndex([Interval(0, 2), Interval(0, 1)])
|
| 745 |
+
cat = Categorical(idx, categories=idx)
|
| 746 |
+
expected_codes = np.array([0, 1], dtype="int8")
|
| 747 |
+
tm.assert_numpy_array_equal(cat.codes, expected_codes)
|
| 748 |
+
tm.assert_index_equal(cat.categories, idx)
|
| 749 |
+
|
| 750 |
+
def test_categorical_extension_array_nullable(self, nulls_fixture):
|
| 751 |
+
# GH:
|
| 752 |
+
arr = pd.arrays.StringArray._from_sequence(
|
| 753 |
+
[nulls_fixture] * 2, dtype=pd.StringDtype()
|
| 754 |
+
)
|
| 755 |
+
result = Categorical(arr)
|
| 756 |
+
assert arr.dtype == result.categories.dtype
|
| 757 |
+
expected = Categorical(Series([pd.NA, pd.NA], dtype=arr.dtype))
|
| 758 |
+
tm.assert_categorical_equal(result, expected)
|
| 759 |
+
|
| 760 |
+
def test_from_sequence_copy(self):
|
| 761 |
+
cat = Categorical(np.arange(5).repeat(2))
|
| 762 |
+
result = Categorical._from_sequence(cat, dtype=cat.dtype, copy=False)
|
| 763 |
+
|
| 764 |
+
# more generally, we'd be OK with a view
|
| 765 |
+
assert result._codes is cat._codes
|
| 766 |
+
|
| 767 |
+
result = Categorical._from_sequence(cat, dtype=cat.dtype, copy=True)
|
| 768 |
+
|
| 769 |
+
assert not tm.shares_memory(result, cat)
|
| 770 |
+
|
| 771 |
+
def test_constructor_datetime64_non_nano(self):
|
| 772 |
+
categories = np.arange(10).view("M8[D]")
|
| 773 |
+
values = categories[::2].copy()
|
| 774 |
+
|
| 775 |
+
cat = Categorical(values, categories=categories)
|
| 776 |
+
assert (cat == values).all()
|
| 777 |
+
|
| 778 |
+
def test_constructor_preserves_freq(self):
|
| 779 |
+
# GH33830 freq retention in categorical
|
| 780 |
+
dti = date_range("2016-01-01", periods=5)
|
| 781 |
+
|
| 782 |
+
expected = dti.freq
|
| 783 |
+
|
| 784 |
+
cat = Categorical(dti)
|
| 785 |
+
result = cat.categories.freq
|
| 786 |
+
|
| 787 |
+
assert expected == result
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/categorical/test_dtypes.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from pandas.core.dtypes.dtypes import CategoricalDtype
|
| 5 |
+
|
| 6 |
+
from pandas import (
|
| 7 |
+
Categorical,
|
| 8 |
+
CategoricalIndex,
|
| 9 |
+
Index,
|
| 10 |
+
IntervalIndex,
|
| 11 |
+
Series,
|
| 12 |
+
Timestamp,
|
| 13 |
+
)
|
| 14 |
+
import pandas._testing as tm
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class TestCategoricalDtypes:
|
| 18 |
+
def test_categories_match_up_to_permutation(self):
|
| 19 |
+
# test dtype comparisons between cats
|
| 20 |
+
|
| 21 |
+
c1 = Categorical(list("aabca"), categories=list("abc"), ordered=False)
|
| 22 |
+
c2 = Categorical(list("aabca"), categories=list("cab"), ordered=False)
|
| 23 |
+
c3 = Categorical(list("aabca"), categories=list("cab"), ordered=True)
|
| 24 |
+
assert c1._categories_match_up_to_permutation(c1)
|
| 25 |
+
assert c2._categories_match_up_to_permutation(c2)
|
| 26 |
+
assert c3._categories_match_up_to_permutation(c3)
|
| 27 |
+
assert c1._categories_match_up_to_permutation(c2)
|
| 28 |
+
assert not c1._categories_match_up_to_permutation(c3)
|
| 29 |
+
assert not c1._categories_match_up_to_permutation(Index(list("aabca")))
|
| 30 |
+
assert not c1._categories_match_up_to_permutation(c1.astype(object))
|
| 31 |
+
assert c1._categories_match_up_to_permutation(CategoricalIndex(c1))
|
| 32 |
+
assert c1._categories_match_up_to_permutation(
|
| 33 |
+
CategoricalIndex(c1, categories=list("cab"))
|
| 34 |
+
)
|
| 35 |
+
assert not c1._categories_match_up_to_permutation(
|
| 36 |
+
CategoricalIndex(c1, ordered=True)
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
# GH 16659
|
| 40 |
+
s1 = Series(c1)
|
| 41 |
+
s2 = Series(c2)
|
| 42 |
+
s3 = Series(c3)
|
| 43 |
+
assert c1._categories_match_up_to_permutation(s1)
|
| 44 |
+
assert c2._categories_match_up_to_permutation(s2)
|
| 45 |
+
assert c3._categories_match_up_to_permutation(s3)
|
| 46 |
+
assert c1._categories_match_up_to_permutation(s2)
|
| 47 |
+
assert not c1._categories_match_up_to_permutation(s3)
|
| 48 |
+
assert not c1._categories_match_up_to_permutation(s1.astype(object))
|
| 49 |
+
|
| 50 |
+
def test_set_dtype_same(self):
|
| 51 |
+
c = Categorical(["a", "b", "c"])
|
| 52 |
+
result = c._set_dtype(CategoricalDtype(["a", "b", "c"]))
|
| 53 |
+
tm.assert_categorical_equal(result, c)
|
| 54 |
+
|
| 55 |
+
def test_set_dtype_new_categories(self):
|
| 56 |
+
c = Categorical(["a", "b", "c"])
|
| 57 |
+
result = c._set_dtype(CategoricalDtype(list("abcd")))
|
| 58 |
+
tm.assert_numpy_array_equal(result.codes, c.codes)
|
| 59 |
+
tm.assert_index_equal(result.dtype.categories, Index(list("abcd")))
|
| 60 |
+
|
| 61 |
+
@pytest.mark.parametrize(
|
| 62 |
+
"values, categories, new_categories",
|
| 63 |
+
[
|
| 64 |
+
# No NaNs, same cats, same order
|
| 65 |
+
(["a", "b", "a"], ["a", "b"], ["a", "b"]),
|
| 66 |
+
# No NaNs, same cats, different order
|
| 67 |
+
(["a", "b", "a"], ["a", "b"], ["b", "a"]),
|
| 68 |
+
# Same, unsorted
|
| 69 |
+
(["b", "a", "a"], ["a", "b"], ["a", "b"]),
|
| 70 |
+
# No NaNs, same cats, different order
|
| 71 |
+
(["b", "a", "a"], ["a", "b"], ["b", "a"]),
|
| 72 |
+
# NaNs
|
| 73 |
+
(["a", "b", "c"], ["a", "b"], ["a", "b"]),
|
| 74 |
+
(["a", "b", "c"], ["a", "b"], ["b", "a"]),
|
| 75 |
+
(["b", "a", "c"], ["a", "b"], ["a", "b"]),
|
| 76 |
+
(["b", "a", "c"], ["a", "b"], ["a", "b"]),
|
| 77 |
+
# Introduce NaNs
|
| 78 |
+
(["a", "b", "c"], ["a", "b"], ["a"]),
|
| 79 |
+
(["a", "b", "c"], ["a", "b"], ["b"]),
|
| 80 |
+
(["b", "a", "c"], ["a", "b"], ["a"]),
|
| 81 |
+
(["b", "a", "c"], ["a", "b"], ["a"]),
|
| 82 |
+
# No overlap
|
| 83 |
+
(["a", "b", "c"], ["a", "b"], ["d", "e"]),
|
| 84 |
+
],
|
| 85 |
+
)
|
| 86 |
+
@pytest.mark.parametrize("ordered", [True, False])
|
| 87 |
+
def test_set_dtype_many(self, values, categories, new_categories, ordered):
|
| 88 |
+
c = Categorical(values, categories)
|
| 89 |
+
expected = Categorical(values, new_categories, ordered)
|
| 90 |
+
result = c._set_dtype(expected.dtype)
|
| 91 |
+
tm.assert_categorical_equal(result, expected)
|
| 92 |
+
|
| 93 |
+
def test_set_dtype_no_overlap(self):
|
| 94 |
+
c = Categorical(["a", "b", "c"], ["d", "e"])
|
| 95 |
+
result = c._set_dtype(CategoricalDtype(["a", "b"]))
|
| 96 |
+
expected = Categorical([None, None, None], categories=["a", "b"])
|
| 97 |
+
tm.assert_categorical_equal(result, expected)
|
| 98 |
+
|
| 99 |
+
def test_codes_dtypes(self):
|
| 100 |
+
# GH 8453
|
| 101 |
+
result = Categorical(["foo", "bar", "baz"])
|
| 102 |
+
assert result.codes.dtype == "int8"
|
| 103 |
+
|
| 104 |
+
result = Categorical([f"foo{i:05d}" for i in range(400)])
|
| 105 |
+
assert result.codes.dtype == "int16"
|
| 106 |
+
|
| 107 |
+
result = Categorical([f"foo{i:05d}" for i in range(40000)])
|
| 108 |
+
assert result.codes.dtype == "int32"
|
| 109 |
+
|
| 110 |
+
# adding cats
|
| 111 |
+
result = Categorical(["foo", "bar", "baz"])
|
| 112 |
+
assert result.codes.dtype == "int8"
|
| 113 |
+
result = result.add_categories([f"foo{i:05d}" for i in range(400)])
|
| 114 |
+
assert result.codes.dtype == "int16"
|
| 115 |
+
|
| 116 |
+
# removing cats
|
| 117 |
+
result = result.remove_categories([f"foo{i:05d}" for i in range(300)])
|
| 118 |
+
assert result.codes.dtype == "int8"
|
| 119 |
+
|
| 120 |
+
def test_iter_python_types(self):
|
| 121 |
+
# GH-19909
|
| 122 |
+
cat = Categorical([1, 2])
|
| 123 |
+
assert isinstance(next(iter(cat)), int)
|
| 124 |
+
assert isinstance(cat.tolist()[0], int)
|
| 125 |
+
|
| 126 |
+
def test_iter_python_types_datetime(self):
|
| 127 |
+
cat = Categorical([Timestamp("2017-01-01"), Timestamp("2017-01-02")])
|
| 128 |
+
assert isinstance(next(iter(cat)), Timestamp)
|
| 129 |
+
assert isinstance(cat.tolist()[0], Timestamp)
|
| 130 |
+
|
| 131 |
+
def test_interval_index_category(self):
|
| 132 |
+
# GH 38316
|
| 133 |
+
index = IntervalIndex.from_breaks(np.arange(3, dtype="uint64"))
|
| 134 |
+
|
| 135 |
+
result = CategoricalIndex(index).dtype.categories
|
| 136 |
+
expected = IntervalIndex.from_arrays(
|
| 137 |
+
[0, 1], [1, 2], dtype="interval[uint64, right]"
|
| 138 |
+
)
|
| 139 |
+
tm.assert_index_equal(result, expected)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/categorical/test_indexing.py
ADDED
|
@@ -0,0 +1,388 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from pandas import (
|
| 7 |
+
NA,
|
| 8 |
+
Categorical,
|
| 9 |
+
CategoricalIndex,
|
| 10 |
+
Index,
|
| 11 |
+
Interval,
|
| 12 |
+
IntervalIndex,
|
| 13 |
+
NaT,
|
| 14 |
+
PeriodIndex,
|
| 15 |
+
Series,
|
| 16 |
+
Timedelta,
|
| 17 |
+
Timestamp,
|
| 18 |
+
)
|
| 19 |
+
import pandas._testing as tm
|
| 20 |
+
import pandas.core.common as com
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class TestCategoricalIndexingWithFactor:
|
| 24 |
+
def test_getitem(self):
|
| 25 |
+
factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)
|
| 26 |
+
assert factor[0] == "a"
|
| 27 |
+
assert factor[-1] == "c"
|
| 28 |
+
|
| 29 |
+
subf = factor[[0, 1, 2]]
|
| 30 |
+
tm.assert_numpy_array_equal(subf._codes, np.array([0, 1, 1], dtype=np.int8))
|
| 31 |
+
|
| 32 |
+
subf = factor[np.asarray(factor) == "c"]
|
| 33 |
+
tm.assert_numpy_array_equal(subf._codes, np.array([2, 2, 2], dtype=np.int8))
|
| 34 |
+
|
| 35 |
+
def test_setitem(self):
|
| 36 |
+
factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)
|
| 37 |
+
# int/positional
|
| 38 |
+
c = factor.copy()
|
| 39 |
+
c[0] = "b"
|
| 40 |
+
assert c[0] == "b"
|
| 41 |
+
c[-1] = "a"
|
| 42 |
+
assert c[-1] == "a"
|
| 43 |
+
|
| 44 |
+
# boolean
|
| 45 |
+
c = factor.copy()
|
| 46 |
+
indexer = np.zeros(len(c), dtype="bool")
|
| 47 |
+
indexer[0] = True
|
| 48 |
+
indexer[-1] = True
|
| 49 |
+
c[indexer] = "c"
|
| 50 |
+
expected = Categorical(["c", "b", "b", "a", "a", "c", "c", "c"], ordered=True)
|
| 51 |
+
|
| 52 |
+
tm.assert_categorical_equal(c, expected)
|
| 53 |
+
|
| 54 |
+
@pytest.mark.parametrize(
|
| 55 |
+
"other",
|
| 56 |
+
[Categorical(["b", "a"]), Categorical(["b", "a"], categories=["b", "a"])],
|
| 57 |
+
)
|
| 58 |
+
def test_setitem_same_but_unordered(self, other):
|
| 59 |
+
# GH-24142
|
| 60 |
+
target = Categorical(["a", "b"], categories=["a", "b"])
|
| 61 |
+
mask = np.array([True, False])
|
| 62 |
+
target[mask] = other[mask]
|
| 63 |
+
expected = Categorical(["b", "b"], categories=["a", "b"])
|
| 64 |
+
tm.assert_categorical_equal(target, expected)
|
| 65 |
+
|
| 66 |
+
@pytest.mark.parametrize(
|
| 67 |
+
"other",
|
| 68 |
+
[
|
| 69 |
+
Categorical(["b", "a"], categories=["b", "a", "c"]),
|
| 70 |
+
Categorical(["b", "a"], categories=["a", "b", "c"]),
|
| 71 |
+
Categorical(["a", "a"], categories=["a"]),
|
| 72 |
+
Categorical(["b", "b"], categories=["b"]),
|
| 73 |
+
],
|
| 74 |
+
)
|
| 75 |
+
def test_setitem_different_unordered_raises(self, other):
|
| 76 |
+
# GH-24142
|
| 77 |
+
target = Categorical(["a", "b"], categories=["a", "b"])
|
| 78 |
+
mask = np.array([True, False])
|
| 79 |
+
msg = "Cannot set a Categorical with another, without identical categories"
|
| 80 |
+
with pytest.raises(TypeError, match=msg):
|
| 81 |
+
target[mask] = other[mask]
|
| 82 |
+
|
| 83 |
+
@pytest.mark.parametrize(
|
| 84 |
+
"other",
|
| 85 |
+
[
|
| 86 |
+
Categorical(["b", "a"]),
|
| 87 |
+
Categorical(["b", "a"], categories=["b", "a"], ordered=True),
|
| 88 |
+
Categorical(["b", "a"], categories=["a", "b", "c"], ordered=True),
|
| 89 |
+
],
|
| 90 |
+
)
|
| 91 |
+
def test_setitem_same_ordered_raises(self, other):
|
| 92 |
+
# Gh-24142
|
| 93 |
+
target = Categorical(["a", "b"], categories=["a", "b"], ordered=True)
|
| 94 |
+
mask = np.array([True, False])
|
| 95 |
+
msg = "Cannot set a Categorical with another, without identical categories"
|
| 96 |
+
with pytest.raises(TypeError, match=msg):
|
| 97 |
+
target[mask] = other[mask]
|
| 98 |
+
|
| 99 |
+
def test_setitem_tuple(self):
|
| 100 |
+
# GH#20439
|
| 101 |
+
cat = Categorical([(0, 1), (0, 2), (0, 1)])
|
| 102 |
+
|
| 103 |
+
# This should not raise
|
| 104 |
+
cat[1] = cat[0]
|
| 105 |
+
assert cat[1] == (0, 1)
|
| 106 |
+
|
| 107 |
+
def test_setitem_listlike(self):
|
| 108 |
+
# GH#9469
|
| 109 |
+
# properly coerce the input indexers
|
| 110 |
+
|
| 111 |
+
cat = Categorical(
|
| 112 |
+
np.random.default_rng(2).integers(0, 5, size=150000).astype(np.int8)
|
| 113 |
+
).add_categories([-1000])
|
| 114 |
+
indexer = np.array([100000]).astype(np.int64)
|
| 115 |
+
cat[indexer] = -1000
|
| 116 |
+
|
| 117 |
+
# we are asserting the code result here
|
| 118 |
+
# which maps to the -1000 category
|
| 119 |
+
result = cat.codes[np.array([100000]).astype(np.int64)]
|
| 120 |
+
tm.assert_numpy_array_equal(result, np.array([5], dtype="int8"))
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
class TestCategoricalIndexing:
|
| 124 |
+
def test_getitem_slice(self):
|
| 125 |
+
cat = Categorical(["a", "b", "c", "d", "a", "b", "c"])
|
| 126 |
+
sliced = cat[3]
|
| 127 |
+
assert sliced == "d"
|
| 128 |
+
|
| 129 |
+
sliced = cat[3:5]
|
| 130 |
+
expected = Categorical(["d", "a"], categories=["a", "b", "c", "d"])
|
| 131 |
+
tm.assert_categorical_equal(sliced, expected)
|
| 132 |
+
|
| 133 |
+
def test_getitem_listlike(self):
|
| 134 |
+
# GH 9469
|
| 135 |
+
# properly coerce the input indexers
|
| 136 |
+
|
| 137 |
+
c = Categorical(
|
| 138 |
+
np.random.default_rng(2).integers(0, 5, size=150000).astype(np.int8)
|
| 139 |
+
)
|
| 140 |
+
result = c.codes[np.array([100000]).astype(np.int64)]
|
| 141 |
+
expected = c[np.array([100000]).astype(np.int64)].codes
|
| 142 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 143 |
+
|
| 144 |
+
def test_periodindex(self):
|
| 145 |
+
idx1 = PeriodIndex(
|
| 146 |
+
["2014-01", "2014-01", "2014-02", "2014-02", "2014-03", "2014-03"],
|
| 147 |
+
freq="M",
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
cat1 = Categorical(idx1)
|
| 151 |
+
str(cat1)
|
| 152 |
+
exp_arr = np.array([0, 0, 1, 1, 2, 2], dtype=np.int8)
|
| 153 |
+
exp_idx = PeriodIndex(["2014-01", "2014-02", "2014-03"], freq="M")
|
| 154 |
+
tm.assert_numpy_array_equal(cat1._codes, exp_arr)
|
| 155 |
+
tm.assert_index_equal(cat1.categories, exp_idx)
|
| 156 |
+
|
| 157 |
+
idx2 = PeriodIndex(
|
| 158 |
+
["2014-03", "2014-03", "2014-02", "2014-01", "2014-03", "2014-01"],
|
| 159 |
+
freq="M",
|
| 160 |
+
)
|
| 161 |
+
cat2 = Categorical(idx2, ordered=True)
|
| 162 |
+
str(cat2)
|
| 163 |
+
exp_arr = np.array([2, 2, 1, 0, 2, 0], dtype=np.int8)
|
| 164 |
+
exp_idx2 = PeriodIndex(["2014-01", "2014-02", "2014-03"], freq="M")
|
| 165 |
+
tm.assert_numpy_array_equal(cat2._codes, exp_arr)
|
| 166 |
+
tm.assert_index_equal(cat2.categories, exp_idx2)
|
| 167 |
+
|
| 168 |
+
idx3 = PeriodIndex(
|
| 169 |
+
[
|
| 170 |
+
"2013-12",
|
| 171 |
+
"2013-11",
|
| 172 |
+
"2013-10",
|
| 173 |
+
"2013-09",
|
| 174 |
+
"2013-08",
|
| 175 |
+
"2013-07",
|
| 176 |
+
"2013-05",
|
| 177 |
+
],
|
| 178 |
+
freq="M",
|
| 179 |
+
)
|
| 180 |
+
cat3 = Categorical(idx3, ordered=True)
|
| 181 |
+
exp_arr = np.array([6, 5, 4, 3, 2, 1, 0], dtype=np.int8)
|
| 182 |
+
exp_idx = PeriodIndex(
|
| 183 |
+
[
|
| 184 |
+
"2013-05",
|
| 185 |
+
"2013-07",
|
| 186 |
+
"2013-08",
|
| 187 |
+
"2013-09",
|
| 188 |
+
"2013-10",
|
| 189 |
+
"2013-11",
|
| 190 |
+
"2013-12",
|
| 191 |
+
],
|
| 192 |
+
freq="M",
|
| 193 |
+
)
|
| 194 |
+
tm.assert_numpy_array_equal(cat3._codes, exp_arr)
|
| 195 |
+
tm.assert_index_equal(cat3.categories, exp_idx)
|
| 196 |
+
|
| 197 |
+
@pytest.mark.parametrize(
|
| 198 |
+
"null_val",
|
| 199 |
+
[None, np.nan, NaT, NA, math.nan, "NaT", "nat", "NAT", "nan", "NaN", "NAN"],
|
| 200 |
+
)
|
| 201 |
+
def test_periodindex_on_null_types(self, null_val):
|
| 202 |
+
# GH 46673
|
| 203 |
+
result = PeriodIndex(["2022-04-06", "2022-04-07", null_val], freq="D")
|
| 204 |
+
expected = PeriodIndex(["2022-04-06", "2022-04-07", "NaT"], dtype="period[D]")
|
| 205 |
+
assert result[2] is NaT
|
| 206 |
+
tm.assert_index_equal(result, expected)
|
| 207 |
+
|
| 208 |
+
@pytest.mark.parametrize("new_categories", [[1, 2, 3, 4], [1, 2]])
|
| 209 |
+
def test_categories_assignments_wrong_length_raises(self, new_categories):
|
| 210 |
+
cat = Categorical(["a", "b", "c", "a"])
|
| 211 |
+
msg = (
|
| 212 |
+
"new categories need to have the same number of items "
|
| 213 |
+
"as the old categories!"
|
| 214 |
+
)
|
| 215 |
+
with pytest.raises(ValueError, match=msg):
|
| 216 |
+
cat.rename_categories(new_categories)
|
| 217 |
+
|
| 218 |
+
# Combinations of sorted/unique:
|
| 219 |
+
@pytest.mark.parametrize(
|
| 220 |
+
"idx_values", [[1, 2, 3, 4], [1, 3, 2, 4], [1, 3, 3, 4], [1, 2, 2, 4]]
|
| 221 |
+
)
|
| 222 |
+
# Combinations of missing/unique
|
| 223 |
+
@pytest.mark.parametrize("key_values", [[1, 2], [1, 5], [1, 1], [5, 5]])
|
| 224 |
+
@pytest.mark.parametrize("key_class", [Categorical, CategoricalIndex])
|
| 225 |
+
@pytest.mark.parametrize("dtype", [None, "category", "key"])
|
| 226 |
+
def test_get_indexer_non_unique(self, idx_values, key_values, key_class, dtype):
|
| 227 |
+
# GH 21448
|
| 228 |
+
key = key_class(key_values, categories=range(1, 5))
|
| 229 |
+
|
| 230 |
+
if dtype == "key":
|
| 231 |
+
dtype = key.dtype
|
| 232 |
+
|
| 233 |
+
# Test for flat index and CategoricalIndex with same/different cats:
|
| 234 |
+
idx = Index(idx_values, dtype=dtype)
|
| 235 |
+
expected, exp_miss = idx.get_indexer_non_unique(key_values)
|
| 236 |
+
result, res_miss = idx.get_indexer_non_unique(key)
|
| 237 |
+
|
| 238 |
+
tm.assert_numpy_array_equal(expected, result)
|
| 239 |
+
tm.assert_numpy_array_equal(exp_miss, res_miss)
|
| 240 |
+
|
| 241 |
+
exp_unique = idx.unique().get_indexer(key_values)
|
| 242 |
+
res_unique = idx.unique().get_indexer(key)
|
| 243 |
+
tm.assert_numpy_array_equal(res_unique, exp_unique)
|
| 244 |
+
|
| 245 |
+
def test_where_unobserved_nan(self):
|
| 246 |
+
ser = Series(Categorical(["a", "b"]))
|
| 247 |
+
result = ser.where([True, False])
|
| 248 |
+
expected = Series(Categorical(["a", None], categories=["a", "b"]))
|
| 249 |
+
tm.assert_series_equal(result, expected)
|
| 250 |
+
|
| 251 |
+
# all NA
|
| 252 |
+
ser = Series(Categorical(["a", "b"]))
|
| 253 |
+
result = ser.where([False, False])
|
| 254 |
+
expected = Series(Categorical([None, None], categories=["a", "b"]))
|
| 255 |
+
tm.assert_series_equal(result, expected)
|
| 256 |
+
|
| 257 |
+
def test_where_unobserved_categories(self):
|
| 258 |
+
ser = Series(Categorical(["a", "b", "c"], categories=["d", "c", "b", "a"]))
|
| 259 |
+
result = ser.where([True, True, False], other="b")
|
| 260 |
+
expected = Series(Categorical(["a", "b", "b"], categories=ser.cat.categories))
|
| 261 |
+
tm.assert_series_equal(result, expected)
|
| 262 |
+
|
| 263 |
+
def test_where_other_categorical(self):
|
| 264 |
+
ser = Series(Categorical(["a", "b", "c"], categories=["d", "c", "b", "a"]))
|
| 265 |
+
other = Categorical(["b", "c", "a"], categories=["a", "c", "b", "d"])
|
| 266 |
+
result = ser.where([True, False, True], other)
|
| 267 |
+
expected = Series(Categorical(["a", "c", "c"], dtype=ser.dtype))
|
| 268 |
+
tm.assert_series_equal(result, expected)
|
| 269 |
+
|
| 270 |
+
def test_where_new_category_raises(self):
|
| 271 |
+
ser = Series(Categorical(["a", "b", "c"]))
|
| 272 |
+
msg = "Cannot setitem on a Categorical with a new category"
|
| 273 |
+
with pytest.raises(TypeError, match=msg):
|
| 274 |
+
ser.where([True, False, True], "d")
|
| 275 |
+
|
| 276 |
+
def test_where_ordered_differs_rasies(self):
|
| 277 |
+
ser = Series(
|
| 278 |
+
Categorical(["a", "b", "c"], categories=["d", "c", "b", "a"], ordered=True)
|
| 279 |
+
)
|
| 280 |
+
other = Categorical(
|
| 281 |
+
["b", "c", "a"], categories=["a", "c", "b", "d"], ordered=True
|
| 282 |
+
)
|
| 283 |
+
with pytest.raises(TypeError, match="without identical categories"):
|
| 284 |
+
ser.where([True, False, True], other)
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
class TestContains:
|
| 288 |
+
def test_contains(self):
|
| 289 |
+
# GH#21508
|
| 290 |
+
cat = Categorical(list("aabbca"), categories=list("cab"))
|
| 291 |
+
|
| 292 |
+
assert "b" in cat
|
| 293 |
+
assert "z" not in cat
|
| 294 |
+
assert np.nan not in cat
|
| 295 |
+
with pytest.raises(TypeError, match="unhashable type: 'list'"):
|
| 296 |
+
assert [1] in cat
|
| 297 |
+
|
| 298 |
+
# assert codes NOT in index
|
| 299 |
+
assert 0 not in cat
|
| 300 |
+
assert 1 not in cat
|
| 301 |
+
|
| 302 |
+
cat = Categorical(list("aabbca") + [np.nan], categories=list("cab"))
|
| 303 |
+
assert np.nan in cat
|
| 304 |
+
|
| 305 |
+
@pytest.mark.parametrize(
|
| 306 |
+
"item, expected",
|
| 307 |
+
[
|
| 308 |
+
(Interval(0, 1), True),
|
| 309 |
+
(1.5, True),
|
| 310 |
+
(Interval(0.5, 1.5), False),
|
| 311 |
+
("a", False),
|
| 312 |
+
(Timestamp(1), False),
|
| 313 |
+
(Timedelta(1), False),
|
| 314 |
+
],
|
| 315 |
+
ids=str,
|
| 316 |
+
)
|
| 317 |
+
def test_contains_interval(self, item, expected):
|
| 318 |
+
# GH#23705
|
| 319 |
+
cat = Categorical(IntervalIndex.from_breaks(range(3)))
|
| 320 |
+
result = item in cat
|
| 321 |
+
assert result is expected
|
| 322 |
+
|
| 323 |
+
def test_contains_list(self):
|
| 324 |
+
# GH#21729
|
| 325 |
+
cat = Categorical([1, 2, 3])
|
| 326 |
+
|
| 327 |
+
assert "a" not in cat
|
| 328 |
+
|
| 329 |
+
with pytest.raises(TypeError, match="unhashable type"):
|
| 330 |
+
["a"] in cat
|
| 331 |
+
|
| 332 |
+
with pytest.raises(TypeError, match="unhashable type"):
|
| 333 |
+
["a", "b"] in cat
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
@pytest.mark.parametrize("index", [True, False])
|
| 337 |
+
def test_mask_with_boolean(index):
|
| 338 |
+
ser = Series(range(3))
|
| 339 |
+
idx = Categorical([True, False, True])
|
| 340 |
+
if index:
|
| 341 |
+
idx = CategoricalIndex(idx)
|
| 342 |
+
|
| 343 |
+
assert com.is_bool_indexer(idx)
|
| 344 |
+
result = ser[idx]
|
| 345 |
+
expected = ser[idx.astype("object")]
|
| 346 |
+
tm.assert_series_equal(result, expected)
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
@pytest.mark.parametrize("index", [True, False])
|
| 350 |
+
def test_mask_with_boolean_na_treated_as_false(index):
|
| 351 |
+
# https://github.com/pandas-dev/pandas/issues/31503
|
| 352 |
+
ser = Series(range(3))
|
| 353 |
+
idx = Categorical([True, False, None])
|
| 354 |
+
if index:
|
| 355 |
+
idx = CategoricalIndex(idx)
|
| 356 |
+
|
| 357 |
+
result = ser[idx]
|
| 358 |
+
expected = ser[idx.fillna(False)]
|
| 359 |
+
|
| 360 |
+
tm.assert_series_equal(result, expected)
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
@pytest.fixture
|
| 364 |
+
def non_coercible_categorical(monkeypatch):
|
| 365 |
+
"""
|
| 366 |
+
Monkeypatch Categorical.__array__ to ensure no implicit conversion.
|
| 367 |
+
|
| 368 |
+
Raises
|
| 369 |
+
------
|
| 370 |
+
ValueError
|
| 371 |
+
When Categorical.__array__ is called.
|
| 372 |
+
"""
|
| 373 |
+
|
| 374 |
+
# TODO(Categorical): identify other places where this may be
|
| 375 |
+
# useful and move to a conftest.py
|
| 376 |
+
def array(self, dtype=None):
|
| 377 |
+
raise ValueError("I cannot be converted.")
|
| 378 |
+
|
| 379 |
+
with monkeypatch.context() as m:
|
| 380 |
+
m.setattr(Categorical, "__array__", array)
|
| 381 |
+
yield
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
def test_series_at():
|
| 385 |
+
arr = Categorical(["a", "b", "c"])
|
| 386 |
+
ser = Series(arr)
|
| 387 |
+
result = ser.at[0]
|
| 388 |
+
assert result == "a"
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/categorical/test_map.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 |
+
@pytest.fixture(params=[None, "ignore"])
|
| 14 |
+
def na_action(request):
|
| 15 |
+
return request.param
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@pytest.mark.parametrize(
|
| 19 |
+
"data, categories",
|
| 20 |
+
[
|
| 21 |
+
(list("abcbca"), list("cab")),
|
| 22 |
+
(pd.interval_range(0, 3).repeat(3), pd.interval_range(0, 3)),
|
| 23 |
+
],
|
| 24 |
+
ids=["string", "interval"],
|
| 25 |
+
)
|
| 26 |
+
def test_map_str(data, categories, ordered, na_action):
|
| 27 |
+
# GH 31202 - override base class since we want to maintain categorical/ordered
|
| 28 |
+
cat = Categorical(data, categories=categories, ordered=ordered)
|
| 29 |
+
result = cat.map(str, na_action=na_action)
|
| 30 |
+
expected = Categorical(
|
| 31 |
+
map(str, data), categories=map(str, categories), ordered=ordered
|
| 32 |
+
)
|
| 33 |
+
tm.assert_categorical_equal(result, expected)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def test_map(na_action):
|
| 37 |
+
cat = Categorical(list("ABABC"), categories=list("CBA"), ordered=True)
|
| 38 |
+
result = cat.map(lambda x: x.lower(), na_action=na_action)
|
| 39 |
+
exp = Categorical(list("ababc"), categories=list("cba"), ordered=True)
|
| 40 |
+
tm.assert_categorical_equal(result, exp)
|
| 41 |
+
|
| 42 |
+
cat = Categorical(list("ABABC"), categories=list("BAC"), ordered=False)
|
| 43 |
+
result = cat.map(lambda x: x.lower(), na_action=na_action)
|
| 44 |
+
exp = Categorical(list("ababc"), categories=list("bac"), ordered=False)
|
| 45 |
+
tm.assert_categorical_equal(result, exp)
|
| 46 |
+
|
| 47 |
+
# GH 12766: Return an index not an array
|
| 48 |
+
result = cat.map(lambda x: 1, na_action=na_action)
|
| 49 |
+
exp = Index(np.array([1] * 5, dtype=np.int64))
|
| 50 |
+
tm.assert_index_equal(result, exp)
|
| 51 |
+
|
| 52 |
+
# change categories dtype
|
| 53 |
+
cat = Categorical(list("ABABC"), categories=list("BAC"), ordered=False)
|
| 54 |
+
|
| 55 |
+
def f(x):
|
| 56 |
+
return {"A": 10, "B": 20, "C": 30}.get(x)
|
| 57 |
+
|
| 58 |
+
result = cat.map(f, na_action=na_action)
|
| 59 |
+
exp = Categorical([10, 20, 10, 20, 30], categories=[20, 10, 30], ordered=False)
|
| 60 |
+
tm.assert_categorical_equal(result, exp)
|
| 61 |
+
|
| 62 |
+
mapper = Series([10, 20, 30], index=["A", "B", "C"])
|
| 63 |
+
result = cat.map(mapper, na_action=na_action)
|
| 64 |
+
tm.assert_categorical_equal(result, exp)
|
| 65 |
+
|
| 66 |
+
result = cat.map({"A": 10, "B": 20, "C": 30}, na_action=na_action)
|
| 67 |
+
tm.assert_categorical_equal(result, exp)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@pytest.mark.parametrize(
|
| 71 |
+
("data", "f", "expected"),
|
| 72 |
+
(
|
| 73 |
+
([1, 1, np.nan], pd.isna, Index([False, False, True])),
|
| 74 |
+
([1, 2, np.nan], pd.isna, Index([False, False, True])),
|
| 75 |
+
([1, 1, np.nan], {1: False}, Categorical([False, False, np.nan])),
|
| 76 |
+
([1, 2, np.nan], {1: False, 2: False}, Index([False, False, np.nan])),
|
| 77 |
+
(
|
| 78 |
+
[1, 1, np.nan],
|
| 79 |
+
Series([False, False]),
|
| 80 |
+
Categorical([False, False, np.nan]),
|
| 81 |
+
),
|
| 82 |
+
(
|
| 83 |
+
[1, 2, np.nan],
|
| 84 |
+
Series([False] * 3),
|
| 85 |
+
Index([False, False, np.nan]),
|
| 86 |
+
),
|
| 87 |
+
),
|
| 88 |
+
)
|
| 89 |
+
def test_map_with_nan_none(data, f, expected): # GH 24241
|
| 90 |
+
values = Categorical(data)
|
| 91 |
+
result = values.map(f, na_action=None)
|
| 92 |
+
if isinstance(expected, Categorical):
|
| 93 |
+
tm.assert_categorical_equal(result, expected)
|
| 94 |
+
else:
|
| 95 |
+
tm.assert_index_equal(result, expected)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
@pytest.mark.parametrize(
|
| 99 |
+
("data", "f", "expected"),
|
| 100 |
+
(
|
| 101 |
+
([1, 1, np.nan], pd.isna, Categorical([False, False, np.nan])),
|
| 102 |
+
([1, 2, np.nan], pd.isna, Index([False, False, np.nan])),
|
| 103 |
+
([1, 1, np.nan], {1: False}, Categorical([False, False, np.nan])),
|
| 104 |
+
([1, 2, np.nan], {1: False, 2: False}, Index([False, False, np.nan])),
|
| 105 |
+
(
|
| 106 |
+
[1, 1, np.nan],
|
| 107 |
+
Series([False, False]),
|
| 108 |
+
Categorical([False, False, np.nan]),
|
| 109 |
+
),
|
| 110 |
+
(
|
| 111 |
+
[1, 2, np.nan],
|
| 112 |
+
Series([False, False, False]),
|
| 113 |
+
Index([False, False, np.nan]),
|
| 114 |
+
),
|
| 115 |
+
),
|
| 116 |
+
)
|
| 117 |
+
def test_map_with_nan_ignore(data, f, expected): # GH 24241
|
| 118 |
+
values = Categorical(data)
|
| 119 |
+
result = values.map(f, na_action="ignore")
|
| 120 |
+
if data[1] == 1:
|
| 121 |
+
tm.assert_categorical_equal(result, expected)
|
| 122 |
+
else:
|
| 123 |
+
tm.assert_index_equal(result, expected)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def test_map_with_dict_or_series(na_action):
|
| 127 |
+
orig_values = ["a", "B", 1, "a"]
|
| 128 |
+
new_values = ["one", 2, 3.0, "one"]
|
| 129 |
+
cat = Categorical(orig_values)
|
| 130 |
+
|
| 131 |
+
mapper = Series(new_values[:-1], index=orig_values[:-1])
|
| 132 |
+
result = cat.map(mapper, na_action=na_action)
|
| 133 |
+
|
| 134 |
+
# Order of categories in result can be different
|
| 135 |
+
expected = Categorical(new_values, categories=[3.0, 2, "one"])
|
| 136 |
+
tm.assert_categorical_equal(result, expected)
|
| 137 |
+
|
| 138 |
+
mapper = dict(zip(orig_values[:-1], new_values[:-1]))
|
| 139 |
+
result = cat.map(mapper, na_action=na_action)
|
| 140 |
+
# Order of categories in result can be different
|
| 141 |
+
tm.assert_categorical_equal(result, expected)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def test_map_na_action_no_default_deprecated():
|
| 145 |
+
# GH51645
|
| 146 |
+
cat = Categorical(["a", "b", "c"])
|
| 147 |
+
msg = (
|
| 148 |
+
"The default value of 'ignore' for the `na_action` parameter in "
|
| 149 |
+
"pandas.Categorical.map is deprecated and will be "
|
| 150 |
+
"changed to 'None' in a future version. Please set na_action to the "
|
| 151 |
+
"desired value to avoid seeing this warning"
|
| 152 |
+
)
|
| 153 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 154 |
+
cat.map(lambda x: x)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/categorical/test_missing.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import collections
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from pandas.core.dtypes.dtypes import CategoricalDtype
|
| 7 |
+
|
| 8 |
+
import pandas as pd
|
| 9 |
+
from pandas import (
|
| 10 |
+
Categorical,
|
| 11 |
+
DataFrame,
|
| 12 |
+
Index,
|
| 13 |
+
Series,
|
| 14 |
+
isna,
|
| 15 |
+
)
|
| 16 |
+
import pandas._testing as tm
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class TestCategoricalMissing:
|
| 20 |
+
def test_isna(self):
|
| 21 |
+
exp = np.array([False, False, True])
|
| 22 |
+
cat = Categorical(["a", "b", np.nan])
|
| 23 |
+
res = cat.isna()
|
| 24 |
+
|
| 25 |
+
tm.assert_numpy_array_equal(res, exp)
|
| 26 |
+
|
| 27 |
+
def test_na_flags_int_categories(self):
|
| 28 |
+
# #1457
|
| 29 |
+
|
| 30 |
+
categories = list(range(10))
|
| 31 |
+
labels = np.random.default_rng(2).integers(0, 10, 20)
|
| 32 |
+
labels[::5] = -1
|
| 33 |
+
|
| 34 |
+
cat = Categorical(labels, categories)
|
| 35 |
+
repr(cat)
|
| 36 |
+
|
| 37 |
+
tm.assert_numpy_array_equal(isna(cat), labels == -1)
|
| 38 |
+
|
| 39 |
+
def test_nan_handling(self):
|
| 40 |
+
# Nans are represented as -1 in codes
|
| 41 |
+
c = Categorical(["a", "b", np.nan, "a"])
|
| 42 |
+
tm.assert_index_equal(c.categories, Index(["a", "b"]))
|
| 43 |
+
tm.assert_numpy_array_equal(c._codes, np.array([0, 1, -1, 0], dtype=np.int8))
|
| 44 |
+
c[1] = np.nan
|
| 45 |
+
tm.assert_index_equal(c.categories, Index(["a", "b"]))
|
| 46 |
+
tm.assert_numpy_array_equal(c._codes, np.array([0, -1, -1, 0], dtype=np.int8))
|
| 47 |
+
|
| 48 |
+
# Adding nan to categories should make assigned nan point to the
|
| 49 |
+
# category!
|
| 50 |
+
c = Categorical(["a", "b", np.nan, "a"])
|
| 51 |
+
tm.assert_index_equal(c.categories, Index(["a", "b"]))
|
| 52 |
+
tm.assert_numpy_array_equal(c._codes, np.array([0, 1, -1, 0], dtype=np.int8))
|
| 53 |
+
|
| 54 |
+
def test_set_dtype_nans(self):
|
| 55 |
+
c = Categorical(["a", "b", np.nan])
|
| 56 |
+
result = c._set_dtype(CategoricalDtype(["a", "c"]))
|
| 57 |
+
tm.assert_numpy_array_equal(result.codes, np.array([0, -1, -1], dtype="int8"))
|
| 58 |
+
|
| 59 |
+
def test_set_item_nan(self):
|
| 60 |
+
cat = Categorical([1, 2, 3])
|
| 61 |
+
cat[1] = np.nan
|
| 62 |
+
|
| 63 |
+
exp = Categorical([1, np.nan, 3], categories=[1, 2, 3])
|
| 64 |
+
tm.assert_categorical_equal(cat, exp)
|
| 65 |
+
|
| 66 |
+
@pytest.mark.parametrize(
|
| 67 |
+
"fillna_kwargs, msg",
|
| 68 |
+
[
|
| 69 |
+
(
|
| 70 |
+
{"value": 1, "method": "ffill"},
|
| 71 |
+
"Cannot specify both 'value' and 'method'.",
|
| 72 |
+
),
|
| 73 |
+
({}, "Must specify a fill 'value' or 'method'."),
|
| 74 |
+
({"method": "bad"}, "Invalid fill method. Expecting .* bad"),
|
| 75 |
+
(
|
| 76 |
+
{"value": Series([1, 2, 3, 4, "a"])},
|
| 77 |
+
"Cannot setitem on a Categorical with a new category",
|
| 78 |
+
),
|
| 79 |
+
],
|
| 80 |
+
)
|
| 81 |
+
def test_fillna_raises(self, fillna_kwargs, msg):
|
| 82 |
+
# https://github.com/pandas-dev/pandas/issues/19682
|
| 83 |
+
# https://github.com/pandas-dev/pandas/issues/13628
|
| 84 |
+
cat = Categorical([1, 2, 3, None, None])
|
| 85 |
+
|
| 86 |
+
if len(fillna_kwargs) == 1 and "value" in fillna_kwargs:
|
| 87 |
+
err = TypeError
|
| 88 |
+
else:
|
| 89 |
+
err = ValueError
|
| 90 |
+
|
| 91 |
+
with pytest.raises(err, match=msg):
|
| 92 |
+
cat.fillna(**fillna_kwargs)
|
| 93 |
+
|
| 94 |
+
@pytest.mark.parametrize("named", [True, False])
|
| 95 |
+
def test_fillna_iterable_category(self, named):
|
| 96 |
+
# https://github.com/pandas-dev/pandas/issues/21097
|
| 97 |
+
if named:
|
| 98 |
+
Point = collections.namedtuple("Point", "x y")
|
| 99 |
+
else:
|
| 100 |
+
Point = lambda *args: args # tuple
|
| 101 |
+
cat = Categorical(np.array([Point(0, 0), Point(0, 1), None], dtype=object))
|
| 102 |
+
result = cat.fillna(Point(0, 0))
|
| 103 |
+
expected = Categorical([Point(0, 0), Point(0, 1), Point(0, 0)])
|
| 104 |
+
|
| 105 |
+
tm.assert_categorical_equal(result, expected)
|
| 106 |
+
|
| 107 |
+
# Case where the Point is not among our categories; we want ValueError,
|
| 108 |
+
# not NotImplementedError GH#41914
|
| 109 |
+
cat = Categorical(np.array([Point(1, 0), Point(0, 1), None], dtype=object))
|
| 110 |
+
msg = "Cannot setitem on a Categorical with a new category"
|
| 111 |
+
with pytest.raises(TypeError, match=msg):
|
| 112 |
+
cat.fillna(Point(0, 0))
|
| 113 |
+
|
| 114 |
+
def test_fillna_array(self):
|
| 115 |
+
# accept Categorical or ndarray value if it holds appropriate values
|
| 116 |
+
cat = Categorical(["A", "B", "C", None, None])
|
| 117 |
+
|
| 118 |
+
other = cat.fillna("C")
|
| 119 |
+
result = cat.fillna(other)
|
| 120 |
+
tm.assert_categorical_equal(result, other)
|
| 121 |
+
assert isna(cat[-1]) # didn't modify original inplace
|
| 122 |
+
|
| 123 |
+
other = np.array(["A", "B", "C", "B", "A"])
|
| 124 |
+
result = cat.fillna(other)
|
| 125 |
+
expected = Categorical(["A", "B", "C", "B", "A"], dtype=cat.dtype)
|
| 126 |
+
tm.assert_categorical_equal(result, expected)
|
| 127 |
+
assert isna(cat[-1]) # didn't modify original inplace
|
| 128 |
+
|
| 129 |
+
@pytest.mark.parametrize(
|
| 130 |
+
"values, expected",
|
| 131 |
+
[
|
| 132 |
+
([1, 2, 3], np.array([False, False, False])),
|
| 133 |
+
([1, 2, np.nan], np.array([False, False, True])),
|
| 134 |
+
([1, 2, np.inf], np.array([False, False, True])),
|
| 135 |
+
([1, 2, pd.NA], np.array([False, False, True])),
|
| 136 |
+
],
|
| 137 |
+
)
|
| 138 |
+
def test_use_inf_as_na(self, values, expected):
|
| 139 |
+
# https://github.com/pandas-dev/pandas/issues/33594
|
| 140 |
+
msg = "use_inf_as_na option is deprecated"
|
| 141 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 142 |
+
with pd.option_context("mode.use_inf_as_na", True):
|
| 143 |
+
cat = Categorical(values)
|
| 144 |
+
result = cat.isna()
|
| 145 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 146 |
+
|
| 147 |
+
result = Series(cat).isna()
|
| 148 |
+
expected = Series(expected)
|
| 149 |
+
tm.assert_series_equal(result, expected)
|
| 150 |
+
|
| 151 |
+
result = DataFrame(cat).isna()
|
| 152 |
+
expected = DataFrame(expected)
|
| 153 |
+
tm.assert_frame_equal(result, expected)
|
| 154 |
+
|
| 155 |
+
@pytest.mark.parametrize(
|
| 156 |
+
"values, expected",
|
| 157 |
+
[
|
| 158 |
+
([1, 2, 3], np.array([False, False, False])),
|
| 159 |
+
([1, 2, np.nan], np.array([False, False, True])),
|
| 160 |
+
([1, 2, np.inf], np.array([False, False, True])),
|
| 161 |
+
([1, 2, pd.NA], np.array([False, False, True])),
|
| 162 |
+
],
|
| 163 |
+
)
|
| 164 |
+
def test_use_inf_as_na_outside_context(self, values, expected):
|
| 165 |
+
# https://github.com/pandas-dev/pandas/issues/33594
|
| 166 |
+
# Using isna directly for Categorical will fail in general here
|
| 167 |
+
cat = Categorical(values)
|
| 168 |
+
|
| 169 |
+
msg = "use_inf_as_na option is deprecated"
|
| 170 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 171 |
+
with pd.option_context("mode.use_inf_as_na", True):
|
| 172 |
+
result = isna(cat)
|
| 173 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 174 |
+
|
| 175 |
+
result = isna(Series(cat))
|
| 176 |
+
expected = Series(expected)
|
| 177 |
+
tm.assert_series_equal(result, expected)
|
| 178 |
+
|
| 179 |
+
result = isna(DataFrame(cat))
|
| 180 |
+
expected = DataFrame(expected)
|
| 181 |
+
tm.assert_frame_equal(result, expected)
|
| 182 |
+
|
| 183 |
+
@pytest.mark.parametrize(
|
| 184 |
+
"a1, a2, categories",
|
| 185 |
+
[
|
| 186 |
+
(["a", "b", "c"], [np.nan, "a", "b"], ["a", "b", "c"]),
|
| 187 |
+
([1, 2, 3], [np.nan, 1, 2], [1, 2, 3]),
|
| 188 |
+
],
|
| 189 |
+
)
|
| 190 |
+
def test_compare_categorical_with_missing(self, a1, a2, categories):
|
| 191 |
+
# GH 28384
|
| 192 |
+
cat_type = CategoricalDtype(categories)
|
| 193 |
+
|
| 194 |
+
# !=
|
| 195 |
+
result = Series(a1, dtype=cat_type) != Series(a2, dtype=cat_type)
|
| 196 |
+
expected = Series(a1) != Series(a2)
|
| 197 |
+
tm.assert_series_equal(result, expected)
|
| 198 |
+
|
| 199 |
+
# ==
|
| 200 |
+
result = Series(a1, dtype=cat_type) == Series(a2, dtype=cat_type)
|
| 201 |
+
expected = Series(a1) == Series(a2)
|
| 202 |
+
tm.assert_series_equal(result, expected)
|
| 203 |
+
|
| 204 |
+
@pytest.mark.parametrize(
|
| 205 |
+
"na_value, dtype",
|
| 206 |
+
[
|
| 207 |
+
(pd.NaT, "datetime64[ns]"),
|
| 208 |
+
(None, "float64"),
|
| 209 |
+
(np.nan, "float64"),
|
| 210 |
+
(pd.NA, "float64"),
|
| 211 |
+
],
|
| 212 |
+
)
|
| 213 |
+
def test_categorical_only_missing_values_no_cast(self, na_value, dtype):
|
| 214 |
+
# GH#44900
|
| 215 |
+
result = Categorical([na_value, na_value])
|
| 216 |
+
tm.assert_index_equal(result.categories, Index([], dtype=dtype))
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/categorical/test_operators.py
ADDED
|
@@ -0,0 +1,414 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from pandas import (
|
| 6 |
+
Categorical,
|
| 7 |
+
DataFrame,
|
| 8 |
+
Series,
|
| 9 |
+
Timestamp,
|
| 10 |
+
date_range,
|
| 11 |
+
)
|
| 12 |
+
import pandas._testing as tm
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class TestCategoricalOpsWithFactor:
|
| 16 |
+
def test_categories_none_comparisons(self):
|
| 17 |
+
factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)
|
| 18 |
+
tm.assert_categorical_equal(factor, factor)
|
| 19 |
+
|
| 20 |
+
def test_comparisons(self):
|
| 21 |
+
factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)
|
| 22 |
+
result = factor[factor == "a"]
|
| 23 |
+
expected = factor[np.asarray(factor) == "a"]
|
| 24 |
+
tm.assert_categorical_equal(result, expected)
|
| 25 |
+
|
| 26 |
+
result = factor[factor != "a"]
|
| 27 |
+
expected = factor[np.asarray(factor) != "a"]
|
| 28 |
+
tm.assert_categorical_equal(result, expected)
|
| 29 |
+
|
| 30 |
+
result = factor[factor < "c"]
|
| 31 |
+
expected = factor[np.asarray(factor) < "c"]
|
| 32 |
+
tm.assert_categorical_equal(result, expected)
|
| 33 |
+
|
| 34 |
+
result = factor[factor > "a"]
|
| 35 |
+
expected = factor[np.asarray(factor) > "a"]
|
| 36 |
+
tm.assert_categorical_equal(result, expected)
|
| 37 |
+
|
| 38 |
+
result = factor[factor >= "b"]
|
| 39 |
+
expected = factor[np.asarray(factor) >= "b"]
|
| 40 |
+
tm.assert_categorical_equal(result, expected)
|
| 41 |
+
|
| 42 |
+
result = factor[factor <= "b"]
|
| 43 |
+
expected = factor[np.asarray(factor) <= "b"]
|
| 44 |
+
tm.assert_categorical_equal(result, expected)
|
| 45 |
+
|
| 46 |
+
n = len(factor)
|
| 47 |
+
|
| 48 |
+
other = factor[np.random.default_rng(2).permutation(n)]
|
| 49 |
+
result = factor == other
|
| 50 |
+
expected = np.asarray(factor) == np.asarray(other)
|
| 51 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 52 |
+
|
| 53 |
+
result = factor == "d"
|
| 54 |
+
expected = np.zeros(len(factor), dtype=bool)
|
| 55 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 56 |
+
|
| 57 |
+
# comparisons with categoricals
|
| 58 |
+
cat_rev = Categorical(["a", "b", "c"], categories=["c", "b", "a"], ordered=True)
|
| 59 |
+
cat_rev_base = Categorical(
|
| 60 |
+
["b", "b", "b"], categories=["c", "b", "a"], ordered=True
|
| 61 |
+
)
|
| 62 |
+
cat = Categorical(["a", "b", "c"], ordered=True)
|
| 63 |
+
cat_base = Categorical(["b", "b", "b"], categories=cat.categories, ordered=True)
|
| 64 |
+
|
| 65 |
+
# comparisons need to take categories ordering into account
|
| 66 |
+
res_rev = cat_rev > cat_rev_base
|
| 67 |
+
exp_rev = np.array([True, False, False])
|
| 68 |
+
tm.assert_numpy_array_equal(res_rev, exp_rev)
|
| 69 |
+
|
| 70 |
+
res_rev = cat_rev < cat_rev_base
|
| 71 |
+
exp_rev = np.array([False, False, True])
|
| 72 |
+
tm.assert_numpy_array_equal(res_rev, exp_rev)
|
| 73 |
+
|
| 74 |
+
res = cat > cat_base
|
| 75 |
+
exp = np.array([False, False, True])
|
| 76 |
+
tm.assert_numpy_array_equal(res, exp)
|
| 77 |
+
|
| 78 |
+
# Only categories with same categories can be compared
|
| 79 |
+
msg = "Categoricals can only be compared if 'categories' are the same"
|
| 80 |
+
with pytest.raises(TypeError, match=msg):
|
| 81 |
+
cat > cat_rev
|
| 82 |
+
|
| 83 |
+
cat_rev_base2 = Categorical(["b", "b", "b"], categories=["c", "b", "a", "d"])
|
| 84 |
+
|
| 85 |
+
with pytest.raises(TypeError, match=msg):
|
| 86 |
+
cat_rev > cat_rev_base2
|
| 87 |
+
|
| 88 |
+
# Only categories with same ordering information can be compared
|
| 89 |
+
cat_unordered = cat.set_ordered(False)
|
| 90 |
+
assert not (cat > cat).any()
|
| 91 |
+
|
| 92 |
+
with pytest.raises(TypeError, match=msg):
|
| 93 |
+
cat > cat_unordered
|
| 94 |
+
|
| 95 |
+
# comparison (in both directions) with Series will raise
|
| 96 |
+
s = Series(["b", "b", "b"], dtype=object)
|
| 97 |
+
msg = (
|
| 98 |
+
"Cannot compare a Categorical for op __gt__ with type "
|
| 99 |
+
r"<class 'numpy\.ndarray'>"
|
| 100 |
+
)
|
| 101 |
+
with pytest.raises(TypeError, match=msg):
|
| 102 |
+
cat > s
|
| 103 |
+
with pytest.raises(TypeError, match=msg):
|
| 104 |
+
cat_rev > s
|
| 105 |
+
with pytest.raises(TypeError, match=msg):
|
| 106 |
+
s < cat
|
| 107 |
+
with pytest.raises(TypeError, match=msg):
|
| 108 |
+
s < cat_rev
|
| 109 |
+
|
| 110 |
+
# comparison with numpy.array will raise in both direction, but only on
|
| 111 |
+
# newer numpy versions
|
| 112 |
+
a = np.array(["b", "b", "b"], dtype=object)
|
| 113 |
+
with pytest.raises(TypeError, match=msg):
|
| 114 |
+
cat > a
|
| 115 |
+
with pytest.raises(TypeError, match=msg):
|
| 116 |
+
cat_rev > a
|
| 117 |
+
|
| 118 |
+
# Make sure that unequal comparison take the categories order in
|
| 119 |
+
# account
|
| 120 |
+
cat_rev = Categorical(list("abc"), categories=list("cba"), ordered=True)
|
| 121 |
+
exp = np.array([True, False, False])
|
| 122 |
+
res = cat_rev > "b"
|
| 123 |
+
tm.assert_numpy_array_equal(res, exp)
|
| 124 |
+
|
| 125 |
+
# check that zero-dim array gets unboxed
|
| 126 |
+
res = cat_rev > np.array("b")
|
| 127 |
+
tm.assert_numpy_array_equal(res, exp)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
class TestCategoricalOps:
|
| 131 |
+
@pytest.mark.parametrize(
|
| 132 |
+
"categories",
|
| 133 |
+
[["a", "b"], [0, 1], [Timestamp("2019"), Timestamp("2020")]],
|
| 134 |
+
)
|
| 135 |
+
def test_not_equal_with_na(self, categories):
|
| 136 |
+
# https://github.com/pandas-dev/pandas/issues/32276
|
| 137 |
+
c1 = Categorical.from_codes([-1, 0], categories=categories)
|
| 138 |
+
c2 = Categorical.from_codes([0, 1], categories=categories)
|
| 139 |
+
|
| 140 |
+
result = c1 != c2
|
| 141 |
+
|
| 142 |
+
assert result.all()
|
| 143 |
+
|
| 144 |
+
def test_compare_frame(self):
|
| 145 |
+
# GH#24282 check that Categorical.__cmp__(DataFrame) defers to frame
|
| 146 |
+
data = ["a", "b", 2, "a"]
|
| 147 |
+
cat = Categorical(data)
|
| 148 |
+
|
| 149 |
+
df = DataFrame(cat)
|
| 150 |
+
|
| 151 |
+
result = cat == df.T
|
| 152 |
+
expected = DataFrame([[True, True, True, True]])
|
| 153 |
+
tm.assert_frame_equal(result, expected)
|
| 154 |
+
|
| 155 |
+
result = cat[::-1] != df.T
|
| 156 |
+
expected = DataFrame([[False, True, True, False]])
|
| 157 |
+
tm.assert_frame_equal(result, expected)
|
| 158 |
+
|
| 159 |
+
def test_compare_frame_raises(self, comparison_op):
|
| 160 |
+
# alignment raises unless we transpose
|
| 161 |
+
op = comparison_op
|
| 162 |
+
cat = Categorical(["a", "b", 2, "a"])
|
| 163 |
+
df = DataFrame(cat)
|
| 164 |
+
msg = "Unable to coerce to Series, length must be 1: given 4"
|
| 165 |
+
with pytest.raises(ValueError, match=msg):
|
| 166 |
+
op(cat, df)
|
| 167 |
+
|
| 168 |
+
def test_datetime_categorical_comparison(self):
|
| 169 |
+
dt_cat = Categorical(date_range("2014-01-01", periods=3), ordered=True)
|
| 170 |
+
tm.assert_numpy_array_equal(dt_cat > dt_cat[0], np.array([False, True, True]))
|
| 171 |
+
tm.assert_numpy_array_equal(dt_cat[0] < dt_cat, np.array([False, True, True]))
|
| 172 |
+
|
| 173 |
+
def test_reflected_comparison_with_scalars(self):
|
| 174 |
+
# GH8658
|
| 175 |
+
cat = Categorical([1, 2, 3], ordered=True)
|
| 176 |
+
tm.assert_numpy_array_equal(cat > cat[0], np.array([False, True, True]))
|
| 177 |
+
tm.assert_numpy_array_equal(cat[0] < cat, np.array([False, True, True]))
|
| 178 |
+
|
| 179 |
+
def test_comparison_with_unknown_scalars(self):
|
| 180 |
+
# https://github.com/pandas-dev/pandas/issues/9836#issuecomment-92123057
|
| 181 |
+
# and following comparisons with scalars not in categories should raise
|
| 182 |
+
# for unequal comps, but not for equal/not equal
|
| 183 |
+
cat = Categorical([1, 2, 3], ordered=True)
|
| 184 |
+
|
| 185 |
+
msg = "Invalid comparison between dtype=category and int"
|
| 186 |
+
with pytest.raises(TypeError, match=msg):
|
| 187 |
+
cat < 4
|
| 188 |
+
with pytest.raises(TypeError, match=msg):
|
| 189 |
+
cat > 4
|
| 190 |
+
with pytest.raises(TypeError, match=msg):
|
| 191 |
+
4 < cat
|
| 192 |
+
with pytest.raises(TypeError, match=msg):
|
| 193 |
+
4 > cat
|
| 194 |
+
|
| 195 |
+
tm.assert_numpy_array_equal(cat == 4, np.array([False, False, False]))
|
| 196 |
+
tm.assert_numpy_array_equal(cat != 4, np.array([True, True, True]))
|
| 197 |
+
|
| 198 |
+
def test_comparison_with_tuple(self):
|
| 199 |
+
cat = Categorical(np.array(["foo", (0, 1), 3, (0, 1)], dtype=object))
|
| 200 |
+
|
| 201 |
+
result = cat == "foo"
|
| 202 |
+
expected = np.array([True, False, False, False], dtype=bool)
|
| 203 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 204 |
+
|
| 205 |
+
result = cat == (0, 1)
|
| 206 |
+
expected = np.array([False, True, False, True], dtype=bool)
|
| 207 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 208 |
+
|
| 209 |
+
result = cat != (0, 1)
|
| 210 |
+
tm.assert_numpy_array_equal(result, ~expected)
|
| 211 |
+
|
| 212 |
+
@pytest.mark.filterwarnings("ignore::RuntimeWarning")
|
| 213 |
+
def test_comparison_of_ordered_categorical_with_nan_to_scalar(
|
| 214 |
+
self, compare_operators_no_eq_ne
|
| 215 |
+
):
|
| 216 |
+
# https://github.com/pandas-dev/pandas/issues/26504
|
| 217 |
+
# BUG: fix ordered categorical comparison with missing values (#26504 )
|
| 218 |
+
# and following comparisons with scalars in categories with missing
|
| 219 |
+
# values should be evaluated as False
|
| 220 |
+
|
| 221 |
+
cat = Categorical([1, 2, 3, None], categories=[1, 2, 3], ordered=True)
|
| 222 |
+
scalar = 2
|
| 223 |
+
expected = getattr(np.array(cat), compare_operators_no_eq_ne)(scalar)
|
| 224 |
+
actual = getattr(cat, compare_operators_no_eq_ne)(scalar)
|
| 225 |
+
tm.assert_numpy_array_equal(actual, expected)
|
| 226 |
+
|
| 227 |
+
@pytest.mark.filterwarnings("ignore::RuntimeWarning")
|
| 228 |
+
def test_comparison_of_ordered_categorical_with_nan_to_listlike(
|
| 229 |
+
self, compare_operators_no_eq_ne
|
| 230 |
+
):
|
| 231 |
+
# https://github.com/pandas-dev/pandas/issues/26504
|
| 232 |
+
# and following comparisons of missing values in ordered Categorical
|
| 233 |
+
# with listlike should be evaluated as False
|
| 234 |
+
|
| 235 |
+
cat = Categorical([1, 2, 3, None], categories=[1, 2, 3], ordered=True)
|
| 236 |
+
other = Categorical([2, 2, 2, 2], categories=[1, 2, 3], ordered=True)
|
| 237 |
+
expected = getattr(np.array(cat), compare_operators_no_eq_ne)(2)
|
| 238 |
+
actual = getattr(cat, compare_operators_no_eq_ne)(other)
|
| 239 |
+
tm.assert_numpy_array_equal(actual, expected)
|
| 240 |
+
|
| 241 |
+
@pytest.mark.parametrize(
|
| 242 |
+
"data,reverse,base",
|
| 243 |
+
[(list("abc"), list("cba"), list("bbb")), ([1, 2, 3], [3, 2, 1], [2, 2, 2])],
|
| 244 |
+
)
|
| 245 |
+
def test_comparisons(self, data, reverse, base):
|
| 246 |
+
cat_rev = Series(Categorical(data, categories=reverse, ordered=True))
|
| 247 |
+
cat_rev_base = Series(Categorical(base, categories=reverse, ordered=True))
|
| 248 |
+
cat = Series(Categorical(data, ordered=True))
|
| 249 |
+
cat_base = Series(
|
| 250 |
+
Categorical(base, categories=cat.cat.categories, ordered=True)
|
| 251 |
+
)
|
| 252 |
+
s = Series(base, dtype=object if base == list("bbb") else None)
|
| 253 |
+
a = np.array(base)
|
| 254 |
+
|
| 255 |
+
# comparisons need to take categories ordering into account
|
| 256 |
+
res_rev = cat_rev > cat_rev_base
|
| 257 |
+
exp_rev = Series([True, False, False])
|
| 258 |
+
tm.assert_series_equal(res_rev, exp_rev)
|
| 259 |
+
|
| 260 |
+
res_rev = cat_rev < cat_rev_base
|
| 261 |
+
exp_rev = Series([False, False, True])
|
| 262 |
+
tm.assert_series_equal(res_rev, exp_rev)
|
| 263 |
+
|
| 264 |
+
res = cat > cat_base
|
| 265 |
+
exp = Series([False, False, True])
|
| 266 |
+
tm.assert_series_equal(res, exp)
|
| 267 |
+
|
| 268 |
+
scalar = base[1]
|
| 269 |
+
res = cat > scalar
|
| 270 |
+
exp = Series([False, False, True])
|
| 271 |
+
exp2 = cat.values > scalar
|
| 272 |
+
tm.assert_series_equal(res, exp)
|
| 273 |
+
tm.assert_numpy_array_equal(res.values, exp2)
|
| 274 |
+
res_rev = cat_rev > scalar
|
| 275 |
+
exp_rev = Series([True, False, False])
|
| 276 |
+
exp_rev2 = cat_rev.values > scalar
|
| 277 |
+
tm.assert_series_equal(res_rev, exp_rev)
|
| 278 |
+
tm.assert_numpy_array_equal(res_rev.values, exp_rev2)
|
| 279 |
+
|
| 280 |
+
# Only categories with same categories can be compared
|
| 281 |
+
msg = "Categoricals can only be compared if 'categories' are the same"
|
| 282 |
+
with pytest.raises(TypeError, match=msg):
|
| 283 |
+
cat > cat_rev
|
| 284 |
+
|
| 285 |
+
# categorical cannot be compared to Series or numpy array, and also
|
| 286 |
+
# not the other way around
|
| 287 |
+
msg = (
|
| 288 |
+
"Cannot compare a Categorical for op __gt__ with type "
|
| 289 |
+
r"<class 'numpy\.ndarray'>"
|
| 290 |
+
)
|
| 291 |
+
with pytest.raises(TypeError, match=msg):
|
| 292 |
+
cat > s
|
| 293 |
+
with pytest.raises(TypeError, match=msg):
|
| 294 |
+
cat_rev > s
|
| 295 |
+
with pytest.raises(TypeError, match=msg):
|
| 296 |
+
cat > a
|
| 297 |
+
with pytest.raises(TypeError, match=msg):
|
| 298 |
+
cat_rev > a
|
| 299 |
+
|
| 300 |
+
with pytest.raises(TypeError, match=msg):
|
| 301 |
+
s < cat
|
| 302 |
+
with pytest.raises(TypeError, match=msg):
|
| 303 |
+
s < cat_rev
|
| 304 |
+
|
| 305 |
+
with pytest.raises(TypeError, match=msg):
|
| 306 |
+
a < cat
|
| 307 |
+
with pytest.raises(TypeError, match=msg):
|
| 308 |
+
a < cat_rev
|
| 309 |
+
|
| 310 |
+
@pytest.mark.parametrize(
|
| 311 |
+
"ctor",
|
| 312 |
+
[
|
| 313 |
+
lambda *args, **kwargs: Categorical(*args, **kwargs),
|
| 314 |
+
lambda *args, **kwargs: Series(Categorical(*args, **kwargs)),
|
| 315 |
+
],
|
| 316 |
+
)
|
| 317 |
+
def test_unordered_different_order_equal(self, ctor):
|
| 318 |
+
# https://github.com/pandas-dev/pandas/issues/16014
|
| 319 |
+
c1 = ctor(["a", "b"], categories=["a", "b"], ordered=False)
|
| 320 |
+
c2 = ctor(["a", "b"], categories=["b", "a"], ordered=False)
|
| 321 |
+
assert (c1 == c2).all()
|
| 322 |
+
|
| 323 |
+
c1 = ctor(["a", "b"], categories=["a", "b"], ordered=False)
|
| 324 |
+
c2 = ctor(["b", "a"], categories=["b", "a"], ordered=False)
|
| 325 |
+
assert (c1 != c2).all()
|
| 326 |
+
|
| 327 |
+
c1 = ctor(["a", "a"], categories=["a", "b"], ordered=False)
|
| 328 |
+
c2 = ctor(["b", "b"], categories=["b", "a"], ordered=False)
|
| 329 |
+
assert (c1 != c2).all()
|
| 330 |
+
|
| 331 |
+
c1 = ctor(["a", "a"], categories=["a", "b"], ordered=False)
|
| 332 |
+
c2 = ctor(["a", "b"], categories=["b", "a"], ordered=False)
|
| 333 |
+
result = c1 == c2
|
| 334 |
+
tm.assert_numpy_array_equal(np.array(result), np.array([True, False]))
|
| 335 |
+
|
| 336 |
+
def test_unordered_different_categories_raises(self):
|
| 337 |
+
c1 = Categorical(["a", "b"], categories=["a", "b"], ordered=False)
|
| 338 |
+
c2 = Categorical(["a", "c"], categories=["c", "a"], ordered=False)
|
| 339 |
+
|
| 340 |
+
with pytest.raises(TypeError, match=("Categoricals can only be compared")):
|
| 341 |
+
c1 == c2
|
| 342 |
+
|
| 343 |
+
def test_compare_different_lengths(self):
|
| 344 |
+
c1 = Categorical([], categories=["a", "b"])
|
| 345 |
+
c2 = Categorical([], categories=["a"])
|
| 346 |
+
|
| 347 |
+
msg = "Categoricals can only be compared if 'categories' are the same."
|
| 348 |
+
with pytest.raises(TypeError, match=msg):
|
| 349 |
+
c1 == c2
|
| 350 |
+
|
| 351 |
+
def test_compare_unordered_different_order(self):
|
| 352 |
+
# https://github.com/pandas-dev/pandas/issues/16603#issuecomment-
|
| 353 |
+
# 349290078
|
| 354 |
+
a = Categorical(["a"], categories=["a", "b"])
|
| 355 |
+
b = Categorical(["b"], categories=["b", "a"])
|
| 356 |
+
assert not a.equals(b)
|
| 357 |
+
|
| 358 |
+
def test_numeric_like_ops(self):
|
| 359 |
+
df = DataFrame({"value": np.random.default_rng(2).integers(0, 10000, 100)})
|
| 360 |
+
labels = [f"{i} - {i + 499}" for i in range(0, 10000, 500)]
|
| 361 |
+
cat_labels = Categorical(labels, labels)
|
| 362 |
+
|
| 363 |
+
df = df.sort_values(by=["value"], ascending=True)
|
| 364 |
+
df["value_group"] = pd.cut(
|
| 365 |
+
df.value, range(0, 10500, 500), right=False, labels=cat_labels
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
# numeric ops should not succeed
|
| 369 |
+
for op, str_rep in [
|
| 370 |
+
("__add__", r"\+"),
|
| 371 |
+
("__sub__", "-"),
|
| 372 |
+
("__mul__", r"\*"),
|
| 373 |
+
("__truediv__", "/"),
|
| 374 |
+
]:
|
| 375 |
+
msg = f"Series cannot perform the operation {str_rep}|unsupported operand"
|
| 376 |
+
with pytest.raises(TypeError, match=msg):
|
| 377 |
+
getattr(df, op)(df)
|
| 378 |
+
|
| 379 |
+
# reduction ops should not succeed (unless specifically defined, e.g.
|
| 380 |
+
# min/max)
|
| 381 |
+
s = df["value_group"]
|
| 382 |
+
for op in ["kurt", "skew", "var", "std", "mean", "sum", "median"]:
|
| 383 |
+
msg = f"does not support reduction '{op}'"
|
| 384 |
+
with pytest.raises(TypeError, match=msg):
|
| 385 |
+
getattr(s, op)(numeric_only=False)
|
| 386 |
+
|
| 387 |
+
def test_numeric_like_ops_series(self):
|
| 388 |
+
# numpy ops
|
| 389 |
+
s = Series(Categorical([1, 2, 3, 4]))
|
| 390 |
+
with pytest.raises(TypeError, match="does not support reduction 'sum'"):
|
| 391 |
+
np.sum(s)
|
| 392 |
+
|
| 393 |
+
@pytest.mark.parametrize(
|
| 394 |
+
"op, str_rep",
|
| 395 |
+
[
|
| 396 |
+
("__add__", r"\+"),
|
| 397 |
+
("__sub__", "-"),
|
| 398 |
+
("__mul__", r"\*"),
|
| 399 |
+
("__truediv__", "/"),
|
| 400 |
+
],
|
| 401 |
+
)
|
| 402 |
+
def test_numeric_like_ops_series_arith(self, op, str_rep):
|
| 403 |
+
# numeric ops on a Series
|
| 404 |
+
s = Series(Categorical([1, 2, 3, 4]))
|
| 405 |
+
msg = f"Series cannot perform the operation {str_rep}|unsupported operand"
|
| 406 |
+
with pytest.raises(TypeError, match=msg):
|
| 407 |
+
getattr(s, op)(2)
|
| 408 |
+
|
| 409 |
+
def test_numeric_like_ops_series_invalid(self):
|
| 410 |
+
# invalid ufunc
|
| 411 |
+
s = Series(Categorical([1, 2, 3, 4]))
|
| 412 |
+
msg = "Object with dtype category cannot perform the numpy op log"
|
| 413 |
+
with pytest.raises(TypeError, match=msg):
|
| 414 |
+
np.log(s)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/categorical/test_replace.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
import pandas as pd
|
| 4 |
+
from pandas import Categorical
|
| 5 |
+
import pandas._testing as tm
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@pytest.mark.parametrize(
|
| 9 |
+
"to_replace,value,expected,flip_categories",
|
| 10 |
+
[
|
| 11 |
+
# one-to-one
|
| 12 |
+
(1, 2, [2, 2, 3], False),
|
| 13 |
+
(1, 4, [4, 2, 3], False),
|
| 14 |
+
(4, 1, [1, 2, 3], False),
|
| 15 |
+
(5, 6, [1, 2, 3], False),
|
| 16 |
+
# many-to-one
|
| 17 |
+
([1], 2, [2, 2, 3], False),
|
| 18 |
+
([1, 2], 3, [3, 3, 3], False),
|
| 19 |
+
([1, 2], 4, [4, 4, 3], False),
|
| 20 |
+
((1, 2, 4), 5, [5, 5, 3], False),
|
| 21 |
+
((5, 6), 2, [1, 2, 3], False),
|
| 22 |
+
([1], [2], [2, 2, 3], False),
|
| 23 |
+
([1, 4], [5, 2], [5, 2, 3], False),
|
| 24 |
+
# GH49404: overlap between to_replace and value
|
| 25 |
+
([1, 2, 3], [2, 3, 4], [2, 3, 4], False),
|
| 26 |
+
# GH50872, GH46884: replace with null
|
| 27 |
+
(1, None, [None, 2, 3], False),
|
| 28 |
+
(1, pd.NA, [None, 2, 3], False),
|
| 29 |
+
# check_categorical sorts categories, which crashes on mixed dtypes
|
| 30 |
+
(3, "4", [1, 2, "4"], False),
|
| 31 |
+
([1, 2, "3"], "5", ["5", "5", 3], True),
|
| 32 |
+
],
|
| 33 |
+
)
|
| 34 |
+
@pytest.mark.filterwarnings(
|
| 35 |
+
"ignore:.*with CategoricalDtype is deprecated:FutureWarning"
|
| 36 |
+
)
|
| 37 |
+
def test_replace_categorical_series(to_replace, value, expected, flip_categories):
|
| 38 |
+
# GH 31720
|
| 39 |
+
|
| 40 |
+
ser = pd.Series([1, 2, 3], dtype="category")
|
| 41 |
+
result = ser.replace(to_replace, value)
|
| 42 |
+
expected = pd.Series(expected, dtype="category")
|
| 43 |
+
ser.replace(to_replace, value, inplace=True)
|
| 44 |
+
|
| 45 |
+
if flip_categories:
|
| 46 |
+
expected = expected.cat.set_categories(expected.cat.categories[::-1])
|
| 47 |
+
|
| 48 |
+
tm.assert_series_equal(expected, result, check_category_order=False)
|
| 49 |
+
tm.assert_series_equal(expected, ser, check_category_order=False)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@pytest.mark.parametrize(
|
| 53 |
+
"to_replace, value, result, expected_error_msg",
|
| 54 |
+
[
|
| 55 |
+
("b", "c", ["a", "c"], "Categorical.categories are different"),
|
| 56 |
+
("c", "d", ["a", "b"], None),
|
| 57 |
+
# https://github.com/pandas-dev/pandas/issues/33288
|
| 58 |
+
("a", "a", ["a", "b"], None),
|
| 59 |
+
("b", None, ["a", None], "Categorical.categories length are different"),
|
| 60 |
+
],
|
| 61 |
+
)
|
| 62 |
+
def test_replace_categorical(to_replace, value, result, expected_error_msg):
|
| 63 |
+
# GH#26988
|
| 64 |
+
cat = Categorical(["a", "b"])
|
| 65 |
+
expected = Categorical(result)
|
| 66 |
+
msg = (
|
| 67 |
+
r"The behavior of Series\.replace \(and DataFrame.replace\) "
|
| 68 |
+
"with CategoricalDtype"
|
| 69 |
+
)
|
| 70 |
+
warn = FutureWarning if expected_error_msg is not None else None
|
| 71 |
+
with tm.assert_produces_warning(warn, match=msg):
|
| 72 |
+
result = pd.Series(cat, copy=False).replace(to_replace, value)._values
|
| 73 |
+
|
| 74 |
+
tm.assert_categorical_equal(result, expected)
|
| 75 |
+
if to_replace == "b": # the "c" test is supposed to be unchanged
|
| 76 |
+
with pytest.raises(AssertionError, match=expected_error_msg):
|
| 77 |
+
# ensure non-inplace call does not affect original
|
| 78 |
+
tm.assert_categorical_equal(cat, expected)
|
| 79 |
+
|
| 80 |
+
ser = pd.Series(cat, copy=False)
|
| 81 |
+
with tm.assert_produces_warning(warn, match=msg):
|
| 82 |
+
ser.replace(to_replace, value, inplace=True)
|
| 83 |
+
tm.assert_categorical_equal(cat, expected)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def test_replace_categorical_ea_dtype():
|
| 87 |
+
# GH49404
|
| 88 |
+
cat = Categorical(pd.array(["a", "b"], dtype="string"))
|
| 89 |
+
msg = (
|
| 90 |
+
r"The behavior of Series\.replace \(and DataFrame.replace\) "
|
| 91 |
+
"with CategoricalDtype"
|
| 92 |
+
)
|
| 93 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 94 |
+
result = pd.Series(cat).replace(["a", "b"], ["c", pd.NA])._values
|
| 95 |
+
expected = Categorical(pd.array(["c", pd.NA], dtype="string"))
|
| 96 |
+
tm.assert_categorical_equal(result, expected)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def test_replace_maintain_ordering():
|
| 100 |
+
# GH51016
|
| 101 |
+
dtype = pd.CategoricalDtype([0, 1, 2], ordered=True)
|
| 102 |
+
ser = pd.Series([0, 1, 2], dtype=dtype)
|
| 103 |
+
msg = (
|
| 104 |
+
r"The behavior of Series\.replace \(and DataFrame.replace\) "
|
| 105 |
+
"with CategoricalDtype"
|
| 106 |
+
)
|
| 107 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 108 |
+
result = ser.replace(0, 2)
|
| 109 |
+
expected_dtype = pd.CategoricalDtype([1, 2], ordered=True)
|
| 110 |
+
expected = pd.Series([2, 1, 2], dtype=expected_dtype)
|
| 111 |
+
tm.assert_series_equal(expected, result, check_category_order=True)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/categorical/test_repr.py
ADDED
|
@@ -0,0 +1,545 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 8 |
+
CategoricalDtype,
|
| 9 |
+
CategoricalIndex,
|
| 10 |
+
Index,
|
| 11 |
+
Series,
|
| 12 |
+
date_range,
|
| 13 |
+
option_context,
|
| 14 |
+
period_range,
|
| 15 |
+
timedelta_range,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class TestCategoricalReprWithFactor:
|
| 20 |
+
def test_print(self, using_infer_string):
|
| 21 |
+
factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)
|
| 22 |
+
dtype = "str" if using_infer_string else "object"
|
| 23 |
+
expected = [
|
| 24 |
+
"['a', 'b', 'b', 'a', 'a', 'c', 'c', 'c']",
|
| 25 |
+
f"Categories (3, {dtype}): ['a' < 'b' < 'c']",
|
| 26 |
+
]
|
| 27 |
+
expected = "\n".join(expected)
|
| 28 |
+
actual = repr(factor)
|
| 29 |
+
assert actual == expected
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class TestCategoricalRepr:
|
| 33 |
+
def test_big_print(self):
|
| 34 |
+
codes = np.array([0, 1, 2, 0, 1, 2] * 100)
|
| 35 |
+
dtype = CategoricalDtype(categories=Index(["a", "b", "c"], dtype=object))
|
| 36 |
+
factor = Categorical.from_codes(codes, dtype=dtype)
|
| 37 |
+
expected = [
|
| 38 |
+
"['a', 'b', 'c', 'a', 'b', ..., 'b', 'c', 'a', 'b', 'c']",
|
| 39 |
+
"Length: 600",
|
| 40 |
+
"Categories (3, object): ['a', 'b', 'c']",
|
| 41 |
+
]
|
| 42 |
+
expected = "\n".join(expected)
|
| 43 |
+
|
| 44 |
+
actual = repr(factor)
|
| 45 |
+
|
| 46 |
+
assert actual == expected
|
| 47 |
+
|
| 48 |
+
def test_empty_print(self):
|
| 49 |
+
factor = Categorical([], Index(["a", "b", "c"], dtype=object))
|
| 50 |
+
expected = "[], Categories (3, object): ['a', 'b', 'c']"
|
| 51 |
+
actual = repr(factor)
|
| 52 |
+
assert actual == expected
|
| 53 |
+
|
| 54 |
+
assert expected == actual
|
| 55 |
+
factor = Categorical([], Index(["a", "b", "c"], dtype=object), ordered=True)
|
| 56 |
+
expected = "[], Categories (3, object): ['a' < 'b' < 'c']"
|
| 57 |
+
actual = repr(factor)
|
| 58 |
+
assert expected == actual
|
| 59 |
+
|
| 60 |
+
factor = Categorical([], [])
|
| 61 |
+
expected = "[], Categories (0, object): []"
|
| 62 |
+
assert expected == repr(factor)
|
| 63 |
+
|
| 64 |
+
def test_print_none_width(self):
|
| 65 |
+
# GH10087
|
| 66 |
+
a = Series(Categorical([1, 2, 3, 4]))
|
| 67 |
+
exp = (
|
| 68 |
+
"0 1\n1 2\n2 3\n3 4\n"
|
| 69 |
+
"dtype: category\nCategories (4, int64): [1, 2, 3, 4]"
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
with option_context("display.width", None):
|
| 73 |
+
assert exp == repr(a)
|
| 74 |
+
|
| 75 |
+
@pytest.mark.skipif(
|
| 76 |
+
using_string_dtype(),
|
| 77 |
+
reason="Change once infer_string is set to True by default",
|
| 78 |
+
)
|
| 79 |
+
def test_unicode_print(self):
|
| 80 |
+
c = Categorical(["aaaaa", "bb", "cccc"] * 20)
|
| 81 |
+
expected = """\
|
| 82 |
+
['aaaaa', 'bb', 'cccc', 'aaaaa', 'bb', ..., 'bb', 'cccc', 'aaaaa', 'bb', 'cccc']
|
| 83 |
+
Length: 60
|
| 84 |
+
Categories (3, object): ['aaaaa', 'bb', 'cccc']"""
|
| 85 |
+
|
| 86 |
+
assert repr(c) == expected
|
| 87 |
+
|
| 88 |
+
c = Categorical(["ああああ", "いいいいい", "ううううううう"] * 20)
|
| 89 |
+
expected = """\
|
| 90 |
+
['ああああ', 'いいいいい', 'ううううううう', 'ああああ', 'いいいいい', ..., 'いいいいい', 'ううううううう', 'ああああ', 'いいいいい', 'ううううううう']
|
| 91 |
+
Length: 60
|
| 92 |
+
Categories (3, object): ['ああああ', 'いいいいい', 'ううううううう']""" # noqa: E501
|
| 93 |
+
|
| 94 |
+
assert repr(c) == expected
|
| 95 |
+
|
| 96 |
+
# unicode option should not affect to Categorical, as it doesn't care
|
| 97 |
+
# the repr width
|
| 98 |
+
with option_context("display.unicode.east_asian_width", True):
|
| 99 |
+
c = Categorical(["ああああ", "いいいいい", "ううううううう"] * 20)
|
| 100 |
+
expected = """['ああああ', 'いいいいい', 'ううううううう', 'ああああ', 'いいいいい', ..., 'いいいいい', 'ううううううう', 'ああああ', 'いいいいい', 'ううううううう']
|
| 101 |
+
Length: 60
|
| 102 |
+
Categories (3, object): ['ああああ', 'いいいいい', 'ううううううう']""" # noqa: E501
|
| 103 |
+
|
| 104 |
+
assert repr(c) == expected
|
| 105 |
+
|
| 106 |
+
def test_categorical_repr(self):
|
| 107 |
+
c = Categorical([1, 2, 3])
|
| 108 |
+
exp = """[1, 2, 3]
|
| 109 |
+
Categories (3, int64): [1, 2, 3]"""
|
| 110 |
+
|
| 111 |
+
assert repr(c) == exp
|
| 112 |
+
|
| 113 |
+
c = Categorical([1, 2, 3, 1, 2, 3], categories=[1, 2, 3])
|
| 114 |
+
exp = """[1, 2, 3, 1, 2, 3]
|
| 115 |
+
Categories (3, int64): [1, 2, 3]"""
|
| 116 |
+
|
| 117 |
+
assert repr(c) == exp
|
| 118 |
+
|
| 119 |
+
c = Categorical([1, 2, 3, 4, 5] * 10)
|
| 120 |
+
exp = """[1, 2, 3, 4, 5, ..., 1, 2, 3, 4, 5]
|
| 121 |
+
Length: 50
|
| 122 |
+
Categories (5, int64): [1, 2, 3, 4, 5]"""
|
| 123 |
+
|
| 124 |
+
assert repr(c) == exp
|
| 125 |
+
|
| 126 |
+
c = Categorical(np.arange(20, dtype=np.int64))
|
| 127 |
+
exp = """[0, 1, 2, 3, 4, ..., 15, 16, 17, 18, 19]
|
| 128 |
+
Length: 20
|
| 129 |
+
Categories (20, int64): [0, 1, 2, 3, ..., 16, 17, 18, 19]"""
|
| 130 |
+
|
| 131 |
+
assert repr(c) == exp
|
| 132 |
+
|
| 133 |
+
def test_categorical_repr_ordered(self):
|
| 134 |
+
c = Categorical([1, 2, 3], ordered=True)
|
| 135 |
+
exp = """[1, 2, 3]
|
| 136 |
+
Categories (3, int64): [1 < 2 < 3]"""
|
| 137 |
+
|
| 138 |
+
assert repr(c) == exp
|
| 139 |
+
|
| 140 |
+
c = Categorical([1, 2, 3, 1, 2, 3], categories=[1, 2, 3], ordered=True)
|
| 141 |
+
exp = """[1, 2, 3, 1, 2, 3]
|
| 142 |
+
Categories (3, int64): [1 < 2 < 3]"""
|
| 143 |
+
|
| 144 |
+
assert repr(c) == exp
|
| 145 |
+
|
| 146 |
+
c = Categorical([1, 2, 3, 4, 5] * 10, ordered=True)
|
| 147 |
+
exp = """[1, 2, 3, 4, 5, ..., 1, 2, 3, 4, 5]
|
| 148 |
+
Length: 50
|
| 149 |
+
Categories (5, int64): [1 < 2 < 3 < 4 < 5]"""
|
| 150 |
+
|
| 151 |
+
assert repr(c) == exp
|
| 152 |
+
|
| 153 |
+
c = Categorical(np.arange(20, dtype=np.int64), ordered=True)
|
| 154 |
+
exp = """[0, 1, 2, 3, 4, ..., 15, 16, 17, 18, 19]
|
| 155 |
+
Length: 20
|
| 156 |
+
Categories (20, int64): [0 < 1 < 2 < 3 ... 16 < 17 < 18 < 19]"""
|
| 157 |
+
|
| 158 |
+
assert repr(c) == exp
|
| 159 |
+
|
| 160 |
+
def test_categorical_repr_datetime(self):
|
| 161 |
+
idx = date_range("2011-01-01 09:00", freq="h", periods=5)
|
| 162 |
+
c = Categorical(idx)
|
| 163 |
+
|
| 164 |
+
exp = (
|
| 165 |
+
"[2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, "
|
| 166 |
+
"2011-01-01 12:00:00, 2011-01-01 13:00:00]\n"
|
| 167 |
+
"Categories (5, datetime64[ns]): [2011-01-01 09:00:00, "
|
| 168 |
+
"2011-01-01 10:00:00, 2011-01-01 11:00:00,\n"
|
| 169 |
+
" 2011-01-01 12:00:00, "
|
| 170 |
+
"2011-01-01 13:00:00]"
|
| 171 |
+
""
|
| 172 |
+
)
|
| 173 |
+
assert repr(c) == exp
|
| 174 |
+
|
| 175 |
+
c = Categorical(idx.append(idx), categories=idx)
|
| 176 |
+
exp = (
|
| 177 |
+
"[2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, "
|
| 178 |
+
"2011-01-01 12:00:00, 2011-01-01 13:00:00, 2011-01-01 09:00:00, "
|
| 179 |
+
"2011-01-01 10:00:00, 2011-01-01 11:00:00, 2011-01-01 12:00:00, "
|
| 180 |
+
"2011-01-01 13:00:00]\n"
|
| 181 |
+
"Categories (5, datetime64[ns]): [2011-01-01 09:00:00, "
|
| 182 |
+
"2011-01-01 10:00:00, 2011-01-01 11:00:00,\n"
|
| 183 |
+
" 2011-01-01 12:00:00, "
|
| 184 |
+
"2011-01-01 13:00:00]"
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
assert repr(c) == exp
|
| 188 |
+
|
| 189 |
+
idx = date_range("2011-01-01 09:00", freq="h", periods=5, tz="US/Eastern")
|
| 190 |
+
c = Categorical(idx)
|
| 191 |
+
exp = (
|
| 192 |
+
"[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, "
|
| 193 |
+
"2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, "
|
| 194 |
+
"2011-01-01 13:00:00-05:00]\n"
|
| 195 |
+
"Categories (5, datetime64[ns, US/Eastern]): "
|
| 196 |
+
"[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00,\n"
|
| 197 |
+
" "
|
| 198 |
+
"2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00,\n"
|
| 199 |
+
" "
|
| 200 |
+
"2011-01-01 13:00:00-05:00]"
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
assert repr(c) == exp
|
| 204 |
+
|
| 205 |
+
c = Categorical(idx.append(idx), categories=idx)
|
| 206 |
+
exp = (
|
| 207 |
+
"[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, "
|
| 208 |
+
"2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, "
|
| 209 |
+
"2011-01-01 13:00:00-05:00, 2011-01-01 09:00:00-05:00, "
|
| 210 |
+
"2011-01-01 10:00:00-05:00, 2011-01-01 11:00:00-05:00, "
|
| 211 |
+
"2011-01-01 12:00:00-05:00, 2011-01-01 13:00:00-05:00]\n"
|
| 212 |
+
"Categories (5, datetime64[ns, US/Eastern]): "
|
| 213 |
+
"[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00,\n"
|
| 214 |
+
" "
|
| 215 |
+
"2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00,\n"
|
| 216 |
+
" "
|
| 217 |
+
"2011-01-01 13:00:00-05:00]"
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
assert repr(c) == exp
|
| 221 |
+
|
| 222 |
+
def test_categorical_repr_datetime_ordered(self):
|
| 223 |
+
idx = date_range("2011-01-01 09:00", freq="h", periods=5)
|
| 224 |
+
c = Categorical(idx, ordered=True)
|
| 225 |
+
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]
|
| 226 |
+
Categories (5, datetime64[ns]): [2011-01-01 09:00:00 < 2011-01-01 10:00:00 < 2011-01-01 11:00:00 <
|
| 227 |
+
2011-01-01 12:00:00 < 2011-01-01 13:00:00]""" # noqa: E501
|
| 228 |
+
|
| 229 |
+
assert repr(c) == exp
|
| 230 |
+
|
| 231 |
+
c = Categorical(idx.append(idx), categories=idx, ordered=True)
|
| 232 |
+
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]
|
| 233 |
+
Categories (5, datetime64[ns]): [2011-01-01 09:00:00 < 2011-01-01 10:00:00 < 2011-01-01 11:00:00 <
|
| 234 |
+
2011-01-01 12:00:00 < 2011-01-01 13:00:00]""" # noqa: E501
|
| 235 |
+
|
| 236 |
+
assert repr(c) == exp
|
| 237 |
+
|
| 238 |
+
idx = date_range("2011-01-01 09:00", freq="h", periods=5, tz="US/Eastern")
|
| 239 |
+
c = Categorical(idx, ordered=True)
|
| 240 |
+
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]
|
| 241 |
+
Categories (5, datetime64[ns, US/Eastern]): [2011-01-01 09:00:00-05:00 < 2011-01-01 10:00:00-05:00 <
|
| 242 |
+
2011-01-01 11:00:00-05:00 < 2011-01-01 12:00:00-05:00 <
|
| 243 |
+
2011-01-01 13:00:00-05:00]""" # noqa: E501
|
| 244 |
+
|
| 245 |
+
assert repr(c) == exp
|
| 246 |
+
|
| 247 |
+
c = Categorical(idx.append(idx), categories=idx, ordered=True)
|
| 248 |
+
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]
|
| 249 |
+
Categories (5, datetime64[ns, US/Eastern]): [2011-01-01 09:00:00-05:00 < 2011-01-01 10:00:00-05:00 <
|
| 250 |
+
2011-01-01 11:00:00-05:00 < 2011-01-01 12:00:00-05:00 <
|
| 251 |
+
2011-01-01 13:00:00-05:00]""" # noqa: E501
|
| 252 |
+
|
| 253 |
+
assert repr(c) == exp
|
| 254 |
+
|
| 255 |
+
def test_categorical_repr_int_with_nan(self):
|
| 256 |
+
c = Categorical([1, 2, np.nan])
|
| 257 |
+
c_exp = """[1, 2, NaN]\nCategories (2, int64): [1, 2]"""
|
| 258 |
+
assert repr(c) == c_exp
|
| 259 |
+
|
| 260 |
+
s = Series([1, 2, np.nan], dtype="object").astype("category")
|
| 261 |
+
s_exp = """0 1\n1 2\n2 NaN
|
| 262 |
+
dtype: category
|
| 263 |
+
Categories (2, int64): [1, 2]"""
|
| 264 |
+
assert repr(s) == s_exp
|
| 265 |
+
|
| 266 |
+
def test_categorical_repr_period(self):
|
| 267 |
+
idx = period_range("2011-01-01 09:00", freq="h", periods=5)
|
| 268 |
+
c = Categorical(idx)
|
| 269 |
+
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]
|
| 270 |
+
Categories (5, period[h]): [2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00,
|
| 271 |
+
2011-01-01 13:00]""" # noqa: E501
|
| 272 |
+
|
| 273 |
+
assert repr(c) == exp
|
| 274 |
+
|
| 275 |
+
c = Categorical(idx.append(idx), categories=idx)
|
| 276 |
+
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]
|
| 277 |
+
Categories (5, period[h]): [2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00,
|
| 278 |
+
2011-01-01 13:00]""" # noqa: E501
|
| 279 |
+
|
| 280 |
+
assert repr(c) == exp
|
| 281 |
+
|
| 282 |
+
idx = period_range("2011-01", freq="M", periods=5)
|
| 283 |
+
c = Categorical(idx)
|
| 284 |
+
exp = """[2011-01, 2011-02, 2011-03, 2011-04, 2011-05]
|
| 285 |
+
Categories (5, period[M]): [2011-01, 2011-02, 2011-03, 2011-04, 2011-05]"""
|
| 286 |
+
|
| 287 |
+
assert repr(c) == exp
|
| 288 |
+
|
| 289 |
+
c = Categorical(idx.append(idx), categories=idx)
|
| 290 |
+
exp = """[2011-01, 2011-02, 2011-03, 2011-04, 2011-05, 2011-01, 2011-02, 2011-03, 2011-04, 2011-05]
|
| 291 |
+
Categories (5, period[M]): [2011-01, 2011-02, 2011-03, 2011-04, 2011-05]""" # noqa: E501
|
| 292 |
+
|
| 293 |
+
assert repr(c) == exp
|
| 294 |
+
|
| 295 |
+
def test_categorical_repr_period_ordered(self):
|
| 296 |
+
idx = period_range("2011-01-01 09:00", freq="h", periods=5)
|
| 297 |
+
c = Categorical(idx, ordered=True)
|
| 298 |
+
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]
|
| 299 |
+
Categories (5, period[h]): [2011-01-01 09:00 < 2011-01-01 10:00 < 2011-01-01 11:00 < 2011-01-01 12:00 <
|
| 300 |
+
2011-01-01 13:00]""" # noqa: E501
|
| 301 |
+
|
| 302 |
+
assert repr(c) == exp
|
| 303 |
+
|
| 304 |
+
c = Categorical(idx.append(idx), categories=idx, ordered=True)
|
| 305 |
+
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]
|
| 306 |
+
Categories (5, period[h]): [2011-01-01 09:00 < 2011-01-01 10:00 < 2011-01-01 11:00 < 2011-01-01 12:00 <
|
| 307 |
+
2011-01-01 13:00]""" # noqa: E501
|
| 308 |
+
|
| 309 |
+
assert repr(c) == exp
|
| 310 |
+
|
| 311 |
+
idx = period_range("2011-01", freq="M", periods=5)
|
| 312 |
+
c = Categorical(idx, ordered=True)
|
| 313 |
+
exp = """[2011-01, 2011-02, 2011-03, 2011-04, 2011-05]
|
| 314 |
+
Categories (5, period[M]): [2011-01 < 2011-02 < 2011-03 < 2011-04 < 2011-05]"""
|
| 315 |
+
|
| 316 |
+
assert repr(c) == exp
|
| 317 |
+
|
| 318 |
+
c = Categorical(idx.append(idx), categories=idx, ordered=True)
|
| 319 |
+
exp = """[2011-01, 2011-02, 2011-03, 2011-04, 2011-05, 2011-01, 2011-02, 2011-03, 2011-04, 2011-05]
|
| 320 |
+
Categories (5, period[M]): [2011-01 < 2011-02 < 2011-03 < 2011-04 < 2011-05]""" # noqa: E501
|
| 321 |
+
|
| 322 |
+
assert repr(c) == exp
|
| 323 |
+
|
| 324 |
+
def test_categorical_repr_timedelta(self):
|
| 325 |
+
idx = timedelta_range("1 days", periods=5)
|
| 326 |
+
c = Categorical(idx)
|
| 327 |
+
exp = """[1 days, 2 days, 3 days, 4 days, 5 days]
|
| 328 |
+
Categories (5, timedelta64[ns]): [1 days, 2 days, 3 days, 4 days, 5 days]"""
|
| 329 |
+
|
| 330 |
+
assert repr(c) == exp
|
| 331 |
+
|
| 332 |
+
c = Categorical(idx.append(idx), categories=idx)
|
| 333 |
+
exp = """[1 days, 2 days, 3 days, 4 days, 5 days, 1 days, 2 days, 3 days, 4 days, 5 days]
|
| 334 |
+
Categories (5, timedelta64[ns]): [1 days, 2 days, 3 days, 4 days, 5 days]""" # noqa: E501
|
| 335 |
+
|
| 336 |
+
assert repr(c) == exp
|
| 337 |
+
|
| 338 |
+
idx = timedelta_range("1 hours", periods=20)
|
| 339 |
+
c = Categorical(idx)
|
| 340 |
+
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]
|
| 341 |
+
Length: 20
|
| 342 |
+
Categories (20, timedelta64[ns]): [0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00,
|
| 343 |
+
3 days 01:00:00, ..., 16 days 01:00:00, 17 days 01:00:00,
|
| 344 |
+
18 days 01:00:00, 19 days 01:00:00]""" # noqa: E501
|
| 345 |
+
|
| 346 |
+
assert repr(c) == exp
|
| 347 |
+
|
| 348 |
+
c = Categorical(idx.append(idx), categories=idx)
|
| 349 |
+
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]
|
| 350 |
+
Length: 40
|
| 351 |
+
Categories (20, timedelta64[ns]): [0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00,
|
| 352 |
+
3 days 01:00:00, ..., 16 days 01:00:00, 17 days 01:00:00,
|
| 353 |
+
18 days 01:00:00, 19 days 01:00:00]""" # noqa: E501
|
| 354 |
+
|
| 355 |
+
assert repr(c) == exp
|
| 356 |
+
|
| 357 |
+
def test_categorical_repr_timedelta_ordered(self):
|
| 358 |
+
idx = timedelta_range("1 days", periods=5)
|
| 359 |
+
c = Categorical(idx, ordered=True)
|
| 360 |
+
exp = """[1 days, 2 days, 3 days, 4 days, 5 days]
|
| 361 |
+
Categories (5, timedelta64[ns]): [1 days < 2 days < 3 days < 4 days < 5 days]"""
|
| 362 |
+
|
| 363 |
+
assert repr(c) == exp
|
| 364 |
+
|
| 365 |
+
c = Categorical(idx.append(idx), categories=idx, ordered=True)
|
| 366 |
+
exp = """[1 days, 2 days, 3 days, 4 days, 5 days, 1 days, 2 days, 3 days, 4 days, 5 days]
|
| 367 |
+
Categories (5, timedelta64[ns]): [1 days < 2 days < 3 days < 4 days < 5 days]""" # noqa: E501
|
| 368 |
+
|
| 369 |
+
assert repr(c) == exp
|
| 370 |
+
|
| 371 |
+
idx = timedelta_range("1 hours", periods=20)
|
| 372 |
+
c = Categorical(idx, ordered=True)
|
| 373 |
+
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]
|
| 374 |
+
Length: 20
|
| 375 |
+
Categories (20, timedelta64[ns]): [0 days 01:00:00 < 1 days 01:00:00 < 2 days 01:00:00 <
|
| 376 |
+
3 days 01:00:00 ... 16 days 01:00:00 < 17 days 01:00:00 <
|
| 377 |
+
18 days 01:00:00 < 19 days 01:00:00]""" # noqa: E501
|
| 378 |
+
|
| 379 |
+
assert repr(c) == exp
|
| 380 |
+
|
| 381 |
+
c = Categorical(idx.append(idx), categories=idx, ordered=True)
|
| 382 |
+
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]
|
| 383 |
+
Length: 40
|
| 384 |
+
Categories (20, timedelta64[ns]): [0 days 01:00:00 < 1 days 01:00:00 < 2 days 01:00:00 <
|
| 385 |
+
3 days 01:00:00 ... 16 days 01:00:00 < 17 days 01:00:00 <
|
| 386 |
+
18 days 01:00:00 < 19 days 01:00:00]""" # noqa: E501
|
| 387 |
+
|
| 388 |
+
assert repr(c) == exp
|
| 389 |
+
|
| 390 |
+
def test_categorical_index_repr(self):
|
| 391 |
+
idx = CategoricalIndex(Categorical([1, 2, 3]))
|
| 392 |
+
exp = """CategoricalIndex([1, 2, 3], categories=[1, 2, 3], ordered=False, dtype='category')""" # noqa: E501
|
| 393 |
+
assert repr(idx) == exp
|
| 394 |
+
|
| 395 |
+
i = CategoricalIndex(Categorical(np.arange(10, dtype=np.int64)))
|
| 396 |
+
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
|
| 397 |
+
assert repr(i) == exp
|
| 398 |
+
|
| 399 |
+
def test_categorical_index_repr_ordered(self):
|
| 400 |
+
i = CategoricalIndex(Categorical([1, 2, 3], ordered=True))
|
| 401 |
+
exp = """CategoricalIndex([1, 2, 3], categories=[1, 2, 3], ordered=True, dtype='category')""" # noqa: E501
|
| 402 |
+
assert repr(i) == exp
|
| 403 |
+
|
| 404 |
+
i = CategoricalIndex(Categorical(np.arange(10, dtype=np.int64), ordered=True))
|
| 405 |
+
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
|
| 406 |
+
assert repr(i) == exp
|
| 407 |
+
|
| 408 |
+
def test_categorical_index_repr_datetime(self):
|
| 409 |
+
idx = date_range("2011-01-01 09:00", freq="h", periods=5)
|
| 410 |
+
i = CategoricalIndex(Categorical(idx))
|
| 411 |
+
exp = """CategoricalIndex(['2011-01-01 09:00:00', '2011-01-01 10:00:00',
|
| 412 |
+
'2011-01-01 11:00:00', '2011-01-01 12:00:00',
|
| 413 |
+
'2011-01-01 13:00:00'],
|
| 414 |
+
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
|
| 415 |
+
|
| 416 |
+
assert repr(i) == exp
|
| 417 |
+
|
| 418 |
+
idx = date_range("2011-01-01 09:00", freq="h", periods=5, tz="US/Eastern")
|
| 419 |
+
i = CategoricalIndex(Categorical(idx))
|
| 420 |
+
exp = """CategoricalIndex(['2011-01-01 09:00:00-05:00', '2011-01-01 10:00:00-05:00',
|
| 421 |
+
'2011-01-01 11:00:00-05:00', '2011-01-01 12:00:00-05:00',
|
| 422 |
+
'2011-01-01 13:00:00-05:00'],
|
| 423 |
+
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
|
| 424 |
+
|
| 425 |
+
assert repr(i) == exp
|
| 426 |
+
|
| 427 |
+
def test_categorical_index_repr_datetime_ordered(self):
|
| 428 |
+
idx = date_range("2011-01-01 09:00", freq="h", periods=5)
|
| 429 |
+
i = CategoricalIndex(Categorical(idx, ordered=True))
|
| 430 |
+
exp = """CategoricalIndex(['2011-01-01 09:00:00', '2011-01-01 10:00:00',
|
| 431 |
+
'2011-01-01 11:00:00', '2011-01-01 12:00:00',
|
| 432 |
+
'2011-01-01 13:00:00'],
|
| 433 |
+
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
|
| 434 |
+
|
| 435 |
+
assert repr(i) == exp
|
| 436 |
+
|
| 437 |
+
idx = date_range("2011-01-01 09:00", freq="h", periods=5, tz="US/Eastern")
|
| 438 |
+
i = CategoricalIndex(Categorical(idx, ordered=True))
|
| 439 |
+
exp = """CategoricalIndex(['2011-01-01 09:00:00-05:00', '2011-01-01 10:00:00-05:00',
|
| 440 |
+
'2011-01-01 11:00:00-05:00', '2011-01-01 12:00:00-05:00',
|
| 441 |
+
'2011-01-01 13:00:00-05:00'],
|
| 442 |
+
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
|
| 443 |
+
|
| 444 |
+
assert repr(i) == exp
|
| 445 |
+
|
| 446 |
+
i = CategoricalIndex(Categorical(idx.append(idx), ordered=True))
|
| 447 |
+
exp = """CategoricalIndex(['2011-01-01 09:00:00-05:00', '2011-01-01 10:00:00-05:00',
|
| 448 |
+
'2011-01-01 11:00:00-05:00', '2011-01-01 12:00:00-05:00',
|
| 449 |
+
'2011-01-01 13:00:00-05:00', '2011-01-01 09:00:00-05:00',
|
| 450 |
+
'2011-01-01 10:00:00-05:00', '2011-01-01 11:00:00-05:00',
|
| 451 |
+
'2011-01-01 12:00:00-05:00', '2011-01-01 13:00:00-05:00'],
|
| 452 |
+
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
|
| 453 |
+
|
| 454 |
+
assert repr(i) == exp
|
| 455 |
+
|
| 456 |
+
def test_categorical_index_repr_period(self):
|
| 457 |
+
# test all length
|
| 458 |
+
idx = period_range("2011-01-01 09:00", freq="h", periods=1)
|
| 459 |
+
i = CategoricalIndex(Categorical(idx))
|
| 460 |
+
exp = """CategoricalIndex(['2011-01-01 09:00'], categories=[2011-01-01 09:00], ordered=False, dtype='category')""" # noqa: E501
|
| 461 |
+
assert repr(i) == exp
|
| 462 |
+
|
| 463 |
+
idx = period_range("2011-01-01 09:00", freq="h", periods=2)
|
| 464 |
+
i = CategoricalIndex(Categorical(idx))
|
| 465 |
+
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
|
| 466 |
+
assert repr(i) == exp
|
| 467 |
+
|
| 468 |
+
idx = period_range("2011-01-01 09:00", freq="h", periods=3)
|
| 469 |
+
i = CategoricalIndex(Categorical(idx))
|
| 470 |
+
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
|
| 471 |
+
assert repr(i) == exp
|
| 472 |
+
|
| 473 |
+
idx = period_range("2011-01-01 09:00", freq="h", periods=5)
|
| 474 |
+
i = CategoricalIndex(Categorical(idx))
|
| 475 |
+
exp = """CategoricalIndex(['2011-01-01 09:00', '2011-01-01 10:00', '2011-01-01 11:00',
|
| 476 |
+
'2011-01-01 12:00', '2011-01-01 13:00'],
|
| 477 |
+
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
|
| 478 |
+
|
| 479 |
+
assert repr(i) == exp
|
| 480 |
+
|
| 481 |
+
i = CategoricalIndex(Categorical(idx.append(idx)))
|
| 482 |
+
exp = """CategoricalIndex(['2011-01-01 09:00', '2011-01-01 10:00', '2011-01-01 11:00',
|
| 483 |
+
'2011-01-01 12:00', '2011-01-01 13:00', '2011-01-01 09:00',
|
| 484 |
+
'2011-01-01 10:00', '2011-01-01 11:00', '2011-01-01 12:00',
|
| 485 |
+
'2011-01-01 13:00'],
|
| 486 |
+
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
|
| 487 |
+
|
| 488 |
+
assert repr(i) == exp
|
| 489 |
+
|
| 490 |
+
idx = period_range("2011-01", freq="M", periods=5)
|
| 491 |
+
i = CategoricalIndex(Categorical(idx))
|
| 492 |
+
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
|
| 493 |
+
assert repr(i) == exp
|
| 494 |
+
|
| 495 |
+
def test_categorical_index_repr_period_ordered(self):
|
| 496 |
+
idx = period_range("2011-01-01 09:00", freq="h", periods=5)
|
| 497 |
+
i = CategoricalIndex(Categorical(idx, ordered=True))
|
| 498 |
+
exp = """CategoricalIndex(['2011-01-01 09:00', '2011-01-01 10:00', '2011-01-01 11:00',
|
| 499 |
+
'2011-01-01 12:00', '2011-01-01 13:00'],
|
| 500 |
+
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
|
| 501 |
+
|
| 502 |
+
assert repr(i) == exp
|
| 503 |
+
|
| 504 |
+
idx = period_range("2011-01", freq="M", periods=5)
|
| 505 |
+
i = CategoricalIndex(Categorical(idx, ordered=True))
|
| 506 |
+
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
|
| 507 |
+
assert repr(i) == exp
|
| 508 |
+
|
| 509 |
+
def test_categorical_index_repr_timedelta(self):
|
| 510 |
+
idx = timedelta_range("1 days", periods=5)
|
| 511 |
+
i = CategoricalIndex(Categorical(idx))
|
| 512 |
+
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
|
| 513 |
+
assert repr(i) == exp
|
| 514 |
+
|
| 515 |
+
idx = timedelta_range("1 hours", periods=10)
|
| 516 |
+
i = CategoricalIndex(Categorical(idx))
|
| 517 |
+
exp = """CategoricalIndex(['0 days 01:00:00', '1 days 01:00:00', '2 days 01:00:00',
|
| 518 |
+
'3 days 01:00:00', '4 days 01:00:00', '5 days 01:00:00',
|
| 519 |
+
'6 days 01:00:00', '7 days 01:00:00', '8 days 01:00:00',
|
| 520 |
+
'9 days 01:00:00'],
|
| 521 |
+
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
|
| 522 |
+
|
| 523 |
+
assert repr(i) == exp
|
| 524 |
+
|
| 525 |
+
def test_categorical_index_repr_timedelta_ordered(self):
|
| 526 |
+
idx = timedelta_range("1 days", periods=5)
|
| 527 |
+
i = CategoricalIndex(Categorical(idx, ordered=True))
|
| 528 |
+
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
|
| 529 |
+
assert repr(i) == exp
|
| 530 |
+
|
| 531 |
+
idx = timedelta_range("1 hours", periods=10)
|
| 532 |
+
i = CategoricalIndex(Categorical(idx, ordered=True))
|
| 533 |
+
exp = """CategoricalIndex(['0 days 01:00:00', '1 days 01:00:00', '2 days 01:00:00',
|
| 534 |
+
'3 days 01:00:00', '4 days 01:00:00', '5 days 01:00:00',
|
| 535 |
+
'6 days 01:00:00', '7 days 01:00:00', '8 days 01:00:00',
|
| 536 |
+
'9 days 01:00:00'],
|
| 537 |
+
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
|
| 538 |
+
|
| 539 |
+
assert repr(i) == exp
|
| 540 |
+
|
| 541 |
+
def test_categorical_str_repr(self):
|
| 542 |
+
# GH 33676
|
| 543 |
+
result = repr(Categorical([1, "2", 3, 4]))
|
| 544 |
+
expected = "[1, '2', 3, 4]\nCategories (4, object): [1, 3, 4, '2']"
|
| 545 |
+
assert result == expected
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/categorical/test_sorting.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from pandas import (
|
| 5 |
+
Categorical,
|
| 6 |
+
Index,
|
| 7 |
+
)
|
| 8 |
+
import pandas._testing as tm
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class TestCategoricalSort:
|
| 12 |
+
def test_argsort(self):
|
| 13 |
+
c = Categorical([5, 3, 1, 4, 2], ordered=True)
|
| 14 |
+
|
| 15 |
+
expected = np.array([2, 4, 1, 3, 0])
|
| 16 |
+
tm.assert_numpy_array_equal(
|
| 17 |
+
c.argsort(ascending=True), expected, check_dtype=False
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
expected = expected[::-1]
|
| 21 |
+
tm.assert_numpy_array_equal(
|
| 22 |
+
c.argsort(ascending=False), expected, check_dtype=False
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
def test_numpy_argsort(self):
|
| 26 |
+
c = Categorical([5, 3, 1, 4, 2], ordered=True)
|
| 27 |
+
|
| 28 |
+
expected = np.array([2, 4, 1, 3, 0])
|
| 29 |
+
tm.assert_numpy_array_equal(np.argsort(c), expected, check_dtype=False)
|
| 30 |
+
|
| 31 |
+
tm.assert_numpy_array_equal(
|
| 32 |
+
np.argsort(c, kind="mergesort"), expected, check_dtype=False
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
msg = "the 'axis' parameter is not supported"
|
| 36 |
+
with pytest.raises(ValueError, match=msg):
|
| 37 |
+
np.argsort(c, axis=0)
|
| 38 |
+
|
| 39 |
+
msg = "the 'order' parameter is not supported"
|
| 40 |
+
with pytest.raises(ValueError, match=msg):
|
| 41 |
+
np.argsort(c, order="C")
|
| 42 |
+
|
| 43 |
+
def test_sort_values(self):
|
| 44 |
+
# unordered cats are sortable
|
| 45 |
+
cat = Categorical(["a", "b", "b", "a"], ordered=False)
|
| 46 |
+
cat.sort_values()
|
| 47 |
+
|
| 48 |
+
cat = Categorical(["a", "c", "b", "d"], ordered=True)
|
| 49 |
+
|
| 50 |
+
# sort_values
|
| 51 |
+
res = cat.sort_values()
|
| 52 |
+
exp = np.array(["a", "b", "c", "d"], dtype=object)
|
| 53 |
+
tm.assert_numpy_array_equal(res.__array__(), exp)
|
| 54 |
+
tm.assert_index_equal(res.categories, cat.categories)
|
| 55 |
+
|
| 56 |
+
cat = Categorical(
|
| 57 |
+
["a", "c", "b", "d"], categories=["a", "b", "c", "d"], ordered=True
|
| 58 |
+
)
|
| 59 |
+
res = cat.sort_values()
|
| 60 |
+
exp = np.array(["a", "b", "c", "d"], dtype=object)
|
| 61 |
+
tm.assert_numpy_array_equal(res.__array__(), exp)
|
| 62 |
+
tm.assert_index_equal(res.categories, cat.categories)
|
| 63 |
+
|
| 64 |
+
res = cat.sort_values(ascending=False)
|
| 65 |
+
exp = np.array(["d", "c", "b", "a"], dtype=object)
|
| 66 |
+
tm.assert_numpy_array_equal(res.__array__(), exp)
|
| 67 |
+
tm.assert_index_equal(res.categories, cat.categories)
|
| 68 |
+
|
| 69 |
+
# sort (inplace order)
|
| 70 |
+
cat1 = cat.copy()
|
| 71 |
+
orig_codes = cat1._codes
|
| 72 |
+
cat1.sort_values(inplace=True)
|
| 73 |
+
assert cat1._codes is orig_codes
|
| 74 |
+
exp = np.array(["a", "b", "c", "d"], dtype=object)
|
| 75 |
+
tm.assert_numpy_array_equal(cat1.__array__(), exp)
|
| 76 |
+
tm.assert_index_equal(res.categories, cat.categories)
|
| 77 |
+
|
| 78 |
+
# reverse
|
| 79 |
+
cat = Categorical(["a", "c", "c", "b", "d"], ordered=True)
|
| 80 |
+
res = cat.sort_values(ascending=False)
|
| 81 |
+
exp_val = np.array(["d", "c", "c", "b", "a"], dtype=object)
|
| 82 |
+
exp_categories = Index(["a", "b", "c", "d"])
|
| 83 |
+
tm.assert_numpy_array_equal(res.__array__(), exp_val)
|
| 84 |
+
tm.assert_index_equal(res.categories, exp_categories)
|
| 85 |
+
|
| 86 |
+
def test_sort_values_na_position(self):
|
| 87 |
+
# see gh-12882
|
| 88 |
+
cat = Categorical([5, 2, np.nan, 2, np.nan], ordered=True)
|
| 89 |
+
exp_categories = Index([2, 5])
|
| 90 |
+
|
| 91 |
+
exp = np.array([2.0, 2.0, 5.0, np.nan, np.nan])
|
| 92 |
+
res = cat.sort_values() # default arguments
|
| 93 |
+
tm.assert_numpy_array_equal(res.__array__(), exp)
|
| 94 |
+
tm.assert_index_equal(res.categories, exp_categories)
|
| 95 |
+
|
| 96 |
+
exp = np.array([np.nan, np.nan, 2.0, 2.0, 5.0])
|
| 97 |
+
res = cat.sort_values(ascending=True, na_position="first")
|
| 98 |
+
tm.assert_numpy_array_equal(res.__array__(), exp)
|
| 99 |
+
tm.assert_index_equal(res.categories, exp_categories)
|
| 100 |
+
|
| 101 |
+
exp = np.array([np.nan, np.nan, 5.0, 2.0, 2.0])
|
| 102 |
+
res = cat.sort_values(ascending=False, na_position="first")
|
| 103 |
+
tm.assert_numpy_array_equal(res.__array__(), exp)
|
| 104 |
+
tm.assert_index_equal(res.categories, exp_categories)
|
| 105 |
+
|
| 106 |
+
exp = np.array([2.0, 2.0, 5.0, np.nan, np.nan])
|
| 107 |
+
res = cat.sort_values(ascending=True, na_position="last")
|
| 108 |
+
tm.assert_numpy_array_equal(res.__array__(), exp)
|
| 109 |
+
tm.assert_index_equal(res.categories, exp_categories)
|
| 110 |
+
|
| 111 |
+
exp = np.array([5.0, 2.0, 2.0, np.nan, np.nan])
|
| 112 |
+
res = cat.sort_values(ascending=False, na_position="last")
|
| 113 |
+
tm.assert_numpy_array_equal(res.__array__(), exp)
|
| 114 |
+
tm.assert_index_equal(res.categories, exp_categories)
|
| 115 |
+
|
| 116 |
+
cat = Categorical(["a", "c", "b", "d", np.nan], ordered=True)
|
| 117 |
+
res = cat.sort_values(ascending=False, na_position="last")
|
| 118 |
+
exp_val = np.array(["d", "c", "b", "a", np.nan], dtype=object)
|
| 119 |
+
exp_categories = Index(["a", "b", "c", "d"])
|
| 120 |
+
tm.assert_numpy_array_equal(res.__array__(), exp_val)
|
| 121 |
+
tm.assert_index_equal(res.categories, exp_categories)
|
| 122 |
+
|
| 123 |
+
cat = Categorical(["a", "c", "b", "d", np.nan], ordered=True)
|
| 124 |
+
res = cat.sort_values(ascending=False, na_position="first")
|
| 125 |
+
exp_val = np.array([np.nan, "d", "c", "b", "a"], dtype=object)
|
| 126 |
+
exp_categories = Index(["a", "b", "c", "d"])
|
| 127 |
+
tm.assert_numpy_array_equal(res.__array__(), exp_val)
|
| 128 |
+
tm.assert_index_equal(res.categories, exp_categories)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/categorical/test_subclass.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pandas import Categorical
|
| 2 |
+
import pandas._testing as tm
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class SubclassedCategorical(Categorical):
|
| 6 |
+
pass
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class TestCategoricalSubclassing:
|
| 10 |
+
def test_constructor(self):
|
| 11 |
+
sc = SubclassedCategorical(["a", "b", "c"])
|
| 12 |
+
assert isinstance(sc, SubclassedCategorical)
|
| 13 |
+
tm.assert_categorical_equal(sc, Categorical(["a", "b", "c"]))
|
| 14 |
+
|
| 15 |
+
def test_from_codes(self):
|
| 16 |
+
sc = SubclassedCategorical.from_codes([1, 0, 2], ["a", "b", "c"])
|
| 17 |
+
assert isinstance(sc, SubclassedCategorical)
|
| 18 |
+
exp = Categorical.from_codes([1, 0, 2], ["a", "b", "c"])
|
| 19 |
+
tm.assert_categorical_equal(sc, exp)
|
| 20 |
+
|
| 21 |
+
def test_map(self):
|
| 22 |
+
sc = SubclassedCategorical(["a", "b", "c"])
|
| 23 |
+
res = sc.map(lambda x: x.upper(), na_action=None)
|
| 24 |
+
assert isinstance(res, SubclassedCategorical)
|
| 25 |
+
exp = Categorical(["A", "B", "C"])
|
| 26 |
+
tm.assert_categorical_equal(res, exp)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/categorical/test_take.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from pandas import Categorical
|
| 5 |
+
import pandas._testing as tm
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@pytest.fixture(params=[True, False])
|
| 9 |
+
def allow_fill(request):
|
| 10 |
+
"""Boolean 'allow_fill' parameter for Categorical.take"""
|
| 11 |
+
return request.param
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class TestTake:
|
| 15 |
+
# https://github.com/pandas-dev/pandas/issues/20664
|
| 16 |
+
|
| 17 |
+
def test_take_default_allow_fill(self):
|
| 18 |
+
cat = Categorical(["a", "b"])
|
| 19 |
+
with tm.assert_produces_warning(None):
|
| 20 |
+
result = cat.take([0, -1])
|
| 21 |
+
|
| 22 |
+
assert result.equals(cat)
|
| 23 |
+
|
| 24 |
+
def test_take_positive_no_warning(self):
|
| 25 |
+
cat = Categorical(["a", "b"])
|
| 26 |
+
with tm.assert_produces_warning(None):
|
| 27 |
+
cat.take([0, 0])
|
| 28 |
+
|
| 29 |
+
def test_take_bounds(self, allow_fill):
|
| 30 |
+
# https://github.com/pandas-dev/pandas/issues/20664
|
| 31 |
+
cat = Categorical(["a", "b", "a"])
|
| 32 |
+
if allow_fill:
|
| 33 |
+
msg = "indices are out-of-bounds"
|
| 34 |
+
else:
|
| 35 |
+
msg = "index 4 is out of bounds for( axis 0 with)? size 3"
|
| 36 |
+
with pytest.raises(IndexError, match=msg):
|
| 37 |
+
cat.take([4, 5], allow_fill=allow_fill)
|
| 38 |
+
|
| 39 |
+
def test_take_empty(self, allow_fill):
|
| 40 |
+
# https://github.com/pandas-dev/pandas/issues/20664
|
| 41 |
+
cat = Categorical([], categories=["a", "b"])
|
| 42 |
+
if allow_fill:
|
| 43 |
+
msg = "indices are out-of-bounds"
|
| 44 |
+
else:
|
| 45 |
+
msg = "cannot do a non-empty take from an empty axes"
|
| 46 |
+
with pytest.raises(IndexError, match=msg):
|
| 47 |
+
cat.take([0], allow_fill=allow_fill)
|
| 48 |
+
|
| 49 |
+
def test_positional_take(self, ordered):
|
| 50 |
+
cat = Categorical(["a", "a", "b", "b"], categories=["b", "a"], ordered=ordered)
|
| 51 |
+
result = cat.take([0, 1, 2], allow_fill=False)
|
| 52 |
+
expected = Categorical(
|
| 53 |
+
["a", "a", "b"], categories=cat.categories, ordered=ordered
|
| 54 |
+
)
|
| 55 |
+
tm.assert_categorical_equal(result, expected)
|
| 56 |
+
|
| 57 |
+
def test_positional_take_unobserved(self, ordered):
|
| 58 |
+
cat = Categorical(["a", "b"], categories=["a", "b", "c"], ordered=ordered)
|
| 59 |
+
result = cat.take([1, 0], allow_fill=False)
|
| 60 |
+
expected = Categorical(["b", "a"], categories=cat.categories, ordered=ordered)
|
| 61 |
+
tm.assert_categorical_equal(result, expected)
|
| 62 |
+
|
| 63 |
+
def test_take_allow_fill(self):
|
| 64 |
+
# https://github.com/pandas-dev/pandas/issues/23296
|
| 65 |
+
cat = Categorical(["a", "a", "b"])
|
| 66 |
+
result = cat.take([0, -1, -1], allow_fill=True)
|
| 67 |
+
expected = Categorical(["a", np.nan, np.nan], categories=["a", "b"])
|
| 68 |
+
tm.assert_categorical_equal(result, expected)
|
| 69 |
+
|
| 70 |
+
def test_take_fill_with_negative_one(self):
|
| 71 |
+
# -1 was a category
|
| 72 |
+
cat = Categorical([-1, 0, 1])
|
| 73 |
+
result = cat.take([0, -1, 1], allow_fill=True, fill_value=-1)
|
| 74 |
+
expected = Categorical([-1, -1, 0], categories=[-1, 0, 1])
|
| 75 |
+
tm.assert_categorical_equal(result, expected)
|
| 76 |
+
|
| 77 |
+
def test_take_fill_value(self):
|
| 78 |
+
# https://github.com/pandas-dev/pandas/issues/23296
|
| 79 |
+
cat = Categorical(["a", "b", "c"])
|
| 80 |
+
result = cat.take([0, 1, -1], fill_value="a", allow_fill=True)
|
| 81 |
+
expected = Categorical(["a", "b", "a"], categories=["a", "b", "c"])
|
| 82 |
+
tm.assert_categorical_equal(result, expected)
|
| 83 |
+
|
| 84 |
+
def test_take_fill_value_new_raises(self):
|
| 85 |
+
# https://github.com/pandas-dev/pandas/issues/23296
|
| 86 |
+
cat = Categorical(["a", "b", "c"])
|
| 87 |
+
xpr = r"Cannot setitem on a Categorical with a new category \(d\)"
|
| 88 |
+
with pytest.raises(TypeError, match=xpr):
|
| 89 |
+
cat.take([0, 1, -1], fill_value="d", allow_fill=True)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/categorical/test_warnings.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
import pandas._testing as tm
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TestCategoricalWarnings:
|
| 7 |
+
def test_tab_complete_warning(self, ip):
|
| 8 |
+
# https://github.com/pandas-dev/pandas/issues/16409
|
| 9 |
+
pytest.importorskip("IPython", minversion="6.0.0")
|
| 10 |
+
from IPython.core.completer import provisionalcompleter
|
| 11 |
+
|
| 12 |
+
code = "import pandas as pd; c = pd.Categorical([])"
|
| 13 |
+
ip.run_cell(code)
|
| 14 |
+
|
| 15 |
+
# GH 31324 newer jedi version raises Deprecation warning;
|
| 16 |
+
# appears resolved 2021-02-02
|
| 17 |
+
with tm.assert_produces_warning(None, raise_on_extra_warnings=False):
|
| 18 |
+
with provisionalcompleter("ignore"):
|
| 19 |
+
list(ip.Completer.completions("c.", 1))
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/datetimes/__init__.py
ADDED
|
File without changes
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/datetimes/test_constructors.py
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from pandas._libs import iNaT
|
| 5 |
+
|
| 6 |
+
from pandas.core.dtypes.dtypes import DatetimeTZDtype
|
| 7 |
+
|
| 8 |
+
import pandas as pd
|
| 9 |
+
import pandas._testing as tm
|
| 10 |
+
from pandas.core.arrays import DatetimeArray
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class TestDatetimeArrayConstructor:
|
| 14 |
+
def test_from_sequence_invalid_type(self):
|
| 15 |
+
mi = pd.MultiIndex.from_product([np.arange(5), np.arange(5)])
|
| 16 |
+
with pytest.raises(TypeError, match="Cannot create a DatetimeArray"):
|
| 17 |
+
DatetimeArray._from_sequence(mi, dtype="M8[ns]")
|
| 18 |
+
|
| 19 |
+
def test_only_1dim_accepted(self):
|
| 20 |
+
arr = np.array([0, 1, 2, 3], dtype="M8[h]").astype("M8[ns]")
|
| 21 |
+
|
| 22 |
+
depr_msg = "DatetimeArray.__init__ is deprecated"
|
| 23 |
+
with tm.assert_produces_warning(FutureWarning, match=depr_msg):
|
| 24 |
+
with pytest.raises(ValueError, match="Only 1-dimensional"):
|
| 25 |
+
# 3-dim, we allow 2D to sneak in for ops purposes GH#29853
|
| 26 |
+
DatetimeArray(arr.reshape(2, 2, 1))
|
| 27 |
+
|
| 28 |
+
with tm.assert_produces_warning(FutureWarning, match=depr_msg):
|
| 29 |
+
with pytest.raises(ValueError, match="Only 1-dimensional"):
|
| 30 |
+
# 0-dim
|
| 31 |
+
DatetimeArray(arr[[0]].squeeze())
|
| 32 |
+
|
| 33 |
+
def test_freq_validation(self):
|
| 34 |
+
# GH#24623 check that invalid instances cannot be created with the
|
| 35 |
+
# public constructor
|
| 36 |
+
arr = np.arange(5, dtype=np.int64) * 3600 * 10**9
|
| 37 |
+
|
| 38 |
+
msg = (
|
| 39 |
+
"Inferred frequency h from passed values does not "
|
| 40 |
+
"conform to passed frequency W-SUN"
|
| 41 |
+
)
|
| 42 |
+
depr_msg = "DatetimeArray.__init__ is deprecated"
|
| 43 |
+
with tm.assert_produces_warning(FutureWarning, match=depr_msg):
|
| 44 |
+
with pytest.raises(ValueError, match=msg):
|
| 45 |
+
DatetimeArray(arr, freq="W")
|
| 46 |
+
|
| 47 |
+
@pytest.mark.parametrize(
|
| 48 |
+
"meth",
|
| 49 |
+
[
|
| 50 |
+
DatetimeArray._from_sequence,
|
| 51 |
+
pd.to_datetime,
|
| 52 |
+
pd.DatetimeIndex,
|
| 53 |
+
],
|
| 54 |
+
)
|
| 55 |
+
def test_mixing_naive_tzaware_raises(self, meth):
|
| 56 |
+
# GH#24569
|
| 57 |
+
arr = np.array([pd.Timestamp("2000"), pd.Timestamp("2000", tz="CET")])
|
| 58 |
+
|
| 59 |
+
msg = (
|
| 60 |
+
"Cannot mix tz-aware with tz-naive values|"
|
| 61 |
+
"Tz-aware datetime.datetime cannot be converted "
|
| 62 |
+
"to datetime64 unless utc=True"
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
for obj in [arr, arr[::-1]]:
|
| 66 |
+
# check that we raise regardless of whether naive is found
|
| 67 |
+
# before aware or vice-versa
|
| 68 |
+
with pytest.raises(ValueError, match=msg):
|
| 69 |
+
meth(obj)
|
| 70 |
+
|
| 71 |
+
def test_from_pandas_array(self):
|
| 72 |
+
arr = pd.array(np.arange(5, dtype=np.int64)) * 3600 * 10**9
|
| 73 |
+
|
| 74 |
+
result = DatetimeArray._from_sequence(arr, dtype="M8[ns]")._with_freq("infer")
|
| 75 |
+
|
| 76 |
+
expected = pd.date_range("1970-01-01", periods=5, freq="h")._data
|
| 77 |
+
tm.assert_datetime_array_equal(result, expected)
|
| 78 |
+
|
| 79 |
+
def test_mismatched_timezone_raises(self):
|
| 80 |
+
depr_msg = "DatetimeArray.__init__ is deprecated"
|
| 81 |
+
with tm.assert_produces_warning(FutureWarning, match=depr_msg):
|
| 82 |
+
arr = DatetimeArray(
|
| 83 |
+
np.array(["2000-01-01T06:00:00"], dtype="M8[ns]"),
|
| 84 |
+
dtype=DatetimeTZDtype(tz="US/Central"),
|
| 85 |
+
)
|
| 86 |
+
dtype = DatetimeTZDtype(tz="US/Eastern")
|
| 87 |
+
msg = r"dtype=datetime64\[ns.*\] does not match data dtype datetime64\[ns.*\]"
|
| 88 |
+
with tm.assert_produces_warning(FutureWarning, match=depr_msg):
|
| 89 |
+
with pytest.raises(TypeError, match=msg):
|
| 90 |
+
DatetimeArray(arr, dtype=dtype)
|
| 91 |
+
|
| 92 |
+
# also with mismatched tzawareness
|
| 93 |
+
with tm.assert_produces_warning(FutureWarning, match=depr_msg):
|
| 94 |
+
with pytest.raises(TypeError, match=msg):
|
| 95 |
+
DatetimeArray(arr, dtype=np.dtype("M8[ns]"))
|
| 96 |
+
with tm.assert_produces_warning(FutureWarning, match=depr_msg):
|
| 97 |
+
with pytest.raises(TypeError, match=msg):
|
| 98 |
+
DatetimeArray(arr.tz_localize(None), dtype=arr.dtype)
|
| 99 |
+
|
| 100 |
+
def test_non_array_raises(self):
|
| 101 |
+
depr_msg = "DatetimeArray.__init__ is deprecated"
|
| 102 |
+
with tm.assert_produces_warning(FutureWarning, match=depr_msg):
|
| 103 |
+
with pytest.raises(ValueError, match="list"):
|
| 104 |
+
DatetimeArray([1, 2, 3])
|
| 105 |
+
|
| 106 |
+
def test_bool_dtype_raises(self):
|
| 107 |
+
arr = np.array([1, 2, 3], dtype="bool")
|
| 108 |
+
|
| 109 |
+
depr_msg = "DatetimeArray.__init__ is deprecated"
|
| 110 |
+
msg = "Unexpected value for 'dtype': 'bool'. Must be"
|
| 111 |
+
with tm.assert_produces_warning(FutureWarning, match=depr_msg):
|
| 112 |
+
with pytest.raises(ValueError, match=msg):
|
| 113 |
+
DatetimeArray(arr)
|
| 114 |
+
|
| 115 |
+
msg = r"dtype bool cannot be converted to datetime64\[ns\]"
|
| 116 |
+
with pytest.raises(TypeError, match=msg):
|
| 117 |
+
DatetimeArray._from_sequence(arr, dtype="M8[ns]")
|
| 118 |
+
|
| 119 |
+
with pytest.raises(TypeError, match=msg):
|
| 120 |
+
pd.DatetimeIndex(arr)
|
| 121 |
+
|
| 122 |
+
with pytest.raises(TypeError, match=msg):
|
| 123 |
+
pd.to_datetime(arr)
|
| 124 |
+
|
| 125 |
+
def test_incorrect_dtype_raises(self):
|
| 126 |
+
depr_msg = "DatetimeArray.__init__ is deprecated"
|
| 127 |
+
with tm.assert_produces_warning(FutureWarning, match=depr_msg):
|
| 128 |
+
with pytest.raises(ValueError, match="Unexpected value for 'dtype'."):
|
| 129 |
+
DatetimeArray(np.array([1, 2, 3], dtype="i8"), dtype="category")
|
| 130 |
+
|
| 131 |
+
with tm.assert_produces_warning(FutureWarning, match=depr_msg):
|
| 132 |
+
with pytest.raises(ValueError, match="Unexpected value for 'dtype'."):
|
| 133 |
+
DatetimeArray(np.array([1, 2, 3], dtype="i8"), dtype="m8[s]")
|
| 134 |
+
|
| 135 |
+
with tm.assert_produces_warning(FutureWarning, match=depr_msg):
|
| 136 |
+
with pytest.raises(ValueError, match="Unexpected value for 'dtype'."):
|
| 137 |
+
DatetimeArray(np.array([1, 2, 3], dtype="i8"), dtype="M8[D]")
|
| 138 |
+
|
| 139 |
+
def test_mismatched_values_dtype_units(self):
|
| 140 |
+
arr = np.array([1, 2, 3], dtype="M8[s]")
|
| 141 |
+
dtype = np.dtype("M8[ns]")
|
| 142 |
+
msg = "Values resolution does not match dtype."
|
| 143 |
+
depr_msg = "DatetimeArray.__init__ is deprecated"
|
| 144 |
+
|
| 145 |
+
with tm.assert_produces_warning(FutureWarning, match=depr_msg):
|
| 146 |
+
with pytest.raises(ValueError, match=msg):
|
| 147 |
+
DatetimeArray(arr, dtype=dtype)
|
| 148 |
+
|
| 149 |
+
dtype2 = DatetimeTZDtype(tz="UTC", unit="ns")
|
| 150 |
+
with tm.assert_produces_warning(FutureWarning, match=depr_msg):
|
| 151 |
+
with pytest.raises(ValueError, match=msg):
|
| 152 |
+
DatetimeArray(arr, dtype=dtype2)
|
| 153 |
+
|
| 154 |
+
def test_freq_infer_raises(self):
|
| 155 |
+
depr_msg = "DatetimeArray.__init__ is deprecated"
|
| 156 |
+
with tm.assert_produces_warning(FutureWarning, match=depr_msg):
|
| 157 |
+
with pytest.raises(ValueError, match="Frequency inference"):
|
| 158 |
+
DatetimeArray(np.array([1, 2, 3], dtype="i8"), freq="infer")
|
| 159 |
+
|
| 160 |
+
def test_copy(self):
|
| 161 |
+
data = np.array([1, 2, 3], dtype="M8[ns]")
|
| 162 |
+
arr = DatetimeArray._from_sequence(data, copy=False)
|
| 163 |
+
assert arr._ndarray is data
|
| 164 |
+
|
| 165 |
+
arr = DatetimeArray._from_sequence(data, copy=True)
|
| 166 |
+
assert arr._ndarray is not data
|
| 167 |
+
|
| 168 |
+
@pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"])
|
| 169 |
+
def test_numpy_datetime_unit(self, unit):
|
| 170 |
+
data = np.array([1, 2, 3], dtype=f"M8[{unit}]")
|
| 171 |
+
arr = DatetimeArray._from_sequence(data)
|
| 172 |
+
assert arr.unit == unit
|
| 173 |
+
assert arr[0].unit == unit
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class TestSequenceToDT64NS:
|
| 177 |
+
def test_tz_dtype_mismatch_raises(self):
|
| 178 |
+
arr = DatetimeArray._from_sequence(
|
| 179 |
+
["2000"], dtype=DatetimeTZDtype(tz="US/Central")
|
| 180 |
+
)
|
| 181 |
+
with pytest.raises(TypeError, match="data is already tz-aware"):
|
| 182 |
+
DatetimeArray._from_sequence(arr, dtype=DatetimeTZDtype(tz="UTC"))
|
| 183 |
+
|
| 184 |
+
def test_tz_dtype_matches(self):
|
| 185 |
+
dtype = DatetimeTZDtype(tz="US/Central")
|
| 186 |
+
arr = DatetimeArray._from_sequence(["2000"], dtype=dtype)
|
| 187 |
+
result = DatetimeArray._from_sequence(arr, dtype=dtype)
|
| 188 |
+
tm.assert_equal(arr, result)
|
| 189 |
+
|
| 190 |
+
@pytest.mark.parametrize("order", ["F", "C"])
|
| 191 |
+
def test_2d(self, order):
|
| 192 |
+
dti = pd.date_range("2016-01-01", periods=6, tz="US/Pacific")
|
| 193 |
+
arr = np.array(dti, dtype=object).reshape(3, 2)
|
| 194 |
+
if order == "F":
|
| 195 |
+
arr = arr.T
|
| 196 |
+
|
| 197 |
+
res = DatetimeArray._from_sequence(arr, dtype=dti.dtype)
|
| 198 |
+
expected = DatetimeArray._from_sequence(arr.ravel(), dtype=dti.dtype).reshape(
|
| 199 |
+
arr.shape
|
| 200 |
+
)
|
| 201 |
+
tm.assert_datetime_array_equal(res, expected)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
# ----------------------------------------------------------------------------
|
| 205 |
+
# Arrow interaction
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
EXTREME_VALUES = [0, 123456789, None, iNaT, 2**63 - 1, -(2**63) + 1]
|
| 209 |
+
FINE_TO_COARSE_SAFE = [123_000_000_000, None, -123_000_000_000]
|
| 210 |
+
COARSE_TO_FINE_SAFE = [123, None, -123]
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
@pytest.mark.parametrize(
|
| 214 |
+
("pa_unit", "pd_unit", "pa_tz", "pd_tz", "data"),
|
| 215 |
+
[
|
| 216 |
+
("s", "s", "UTC", "UTC", EXTREME_VALUES),
|
| 217 |
+
("ms", "ms", "UTC", "Europe/Berlin", EXTREME_VALUES),
|
| 218 |
+
("us", "us", "US/Eastern", "UTC", EXTREME_VALUES),
|
| 219 |
+
("ns", "ns", "US/Central", "Asia/Kolkata", EXTREME_VALUES),
|
| 220 |
+
("ns", "s", "UTC", "UTC", FINE_TO_COARSE_SAFE),
|
| 221 |
+
("us", "ms", "UTC", "Europe/Berlin", FINE_TO_COARSE_SAFE),
|
| 222 |
+
("ms", "us", "US/Eastern", "UTC", COARSE_TO_FINE_SAFE),
|
| 223 |
+
("s", "ns", "US/Central", "Asia/Kolkata", COARSE_TO_FINE_SAFE),
|
| 224 |
+
],
|
| 225 |
+
)
|
| 226 |
+
def test_from_arrow_with_different_units_and_timezones_with(
|
| 227 |
+
pa_unit, pd_unit, pa_tz, pd_tz, data
|
| 228 |
+
):
|
| 229 |
+
pa = pytest.importorskip("pyarrow")
|
| 230 |
+
|
| 231 |
+
pa_type = pa.timestamp(pa_unit, tz=pa_tz)
|
| 232 |
+
arr = pa.array(data, type=pa_type)
|
| 233 |
+
dtype = DatetimeTZDtype(unit=pd_unit, tz=pd_tz)
|
| 234 |
+
|
| 235 |
+
result = dtype.__from_arrow__(arr)
|
| 236 |
+
expected = DatetimeArray._from_sequence(data, dtype=f"M8[{pa_unit}, UTC]").astype(
|
| 237 |
+
dtype, copy=False
|
| 238 |
+
)
|
| 239 |
+
tm.assert_extension_array_equal(result, expected)
|
| 240 |
+
|
| 241 |
+
result = dtype.__from_arrow__(pa.chunked_array([arr]))
|
| 242 |
+
tm.assert_extension_array_equal(result, expected)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
@pytest.mark.parametrize(
|
| 246 |
+
("unit", "tz"),
|
| 247 |
+
[
|
| 248 |
+
("s", "UTC"),
|
| 249 |
+
("ms", "Europe/Berlin"),
|
| 250 |
+
("us", "US/Eastern"),
|
| 251 |
+
("ns", "Asia/Kolkata"),
|
| 252 |
+
("ns", "UTC"),
|
| 253 |
+
],
|
| 254 |
+
)
|
| 255 |
+
def test_from_arrow_from_empty(unit, tz):
|
| 256 |
+
pa = pytest.importorskip("pyarrow")
|
| 257 |
+
|
| 258 |
+
data = []
|
| 259 |
+
arr = pa.array(data)
|
| 260 |
+
dtype = DatetimeTZDtype(unit=unit, tz=tz)
|
| 261 |
+
|
| 262 |
+
result = dtype.__from_arrow__(arr)
|
| 263 |
+
expected = DatetimeArray._from_sequence(np.array(data, dtype=f"datetime64[{unit}]"))
|
| 264 |
+
expected = expected.tz_localize(tz=tz)
|
| 265 |
+
tm.assert_extension_array_equal(result, expected)
|
| 266 |
+
|
| 267 |
+
result = dtype.__from_arrow__(pa.chunked_array([arr]))
|
| 268 |
+
tm.assert_extension_array_equal(result, expected)
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def test_from_arrow_from_integers():
|
| 272 |
+
pa = pytest.importorskip("pyarrow")
|
| 273 |
+
|
| 274 |
+
data = [0, 123456789, None, 2**63 - 1, iNaT, -123456789]
|
| 275 |
+
arr = pa.array(data)
|
| 276 |
+
dtype = DatetimeTZDtype(unit="ns", tz="UTC")
|
| 277 |
+
|
| 278 |
+
result = dtype.__from_arrow__(arr)
|
| 279 |
+
expected = DatetimeArray._from_sequence(np.array(data, dtype="datetime64[ns]"))
|
| 280 |
+
expected = expected.tz_localize("UTC")
|
| 281 |
+
tm.assert_extension_array_equal(result, expected)
|
| 282 |
+
|
| 283 |
+
result = dtype.__from_arrow__(pa.chunked_array([arr]))
|
| 284 |
+
tm.assert_extension_array_equal(result, expected)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/datetimes/test_cumulative.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
import pandas._testing as tm
|
| 4 |
+
from pandas.core.arrays import DatetimeArray
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class TestAccumulator:
|
| 8 |
+
def test_accumulators_freq(self):
|
| 9 |
+
# GH#50297
|
| 10 |
+
arr = DatetimeArray._from_sequence(
|
| 11 |
+
[
|
| 12 |
+
"2000-01-01",
|
| 13 |
+
"2000-01-02",
|
| 14 |
+
"2000-01-03",
|
| 15 |
+
],
|
| 16 |
+
dtype="M8[ns]",
|
| 17 |
+
)._with_freq("infer")
|
| 18 |
+
result = arr._accumulate("cummin")
|
| 19 |
+
expected = DatetimeArray._from_sequence(["2000-01-01"] * 3, dtype="M8[ns]")
|
| 20 |
+
tm.assert_datetime_array_equal(result, expected)
|
| 21 |
+
|
| 22 |
+
result = arr._accumulate("cummax")
|
| 23 |
+
expected = DatetimeArray._from_sequence(
|
| 24 |
+
[
|
| 25 |
+
"2000-01-01",
|
| 26 |
+
"2000-01-02",
|
| 27 |
+
"2000-01-03",
|
| 28 |
+
],
|
| 29 |
+
dtype="M8[ns]",
|
| 30 |
+
)
|
| 31 |
+
tm.assert_datetime_array_equal(result, expected)
|
| 32 |
+
|
| 33 |
+
@pytest.mark.parametrize("func", ["cumsum", "cumprod"])
|
| 34 |
+
def test_accumulators_disallowed(self, func):
|
| 35 |
+
# GH#50297
|
| 36 |
+
arr = DatetimeArray._from_sequence(
|
| 37 |
+
[
|
| 38 |
+
"2000-01-01",
|
| 39 |
+
"2000-01-02",
|
| 40 |
+
],
|
| 41 |
+
dtype="M8[ns]",
|
| 42 |
+
)._with_freq("infer")
|
| 43 |
+
with pytest.raises(TypeError, match=f"Accumulation {func}"):
|
| 44 |
+
arr._accumulate(func)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/datetimes/test_reductions.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from pandas.core.dtypes.dtypes import DatetimeTZDtype
|
| 5 |
+
|
| 6 |
+
import pandas as pd
|
| 7 |
+
from pandas import NaT
|
| 8 |
+
import pandas._testing as tm
|
| 9 |
+
from pandas.core.arrays import DatetimeArray
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class TestReductions:
|
| 13 |
+
@pytest.fixture(params=["s", "ms", "us", "ns"])
|
| 14 |
+
def unit(self, request):
|
| 15 |
+
return request.param
|
| 16 |
+
|
| 17 |
+
@pytest.fixture
|
| 18 |
+
def arr1d(self, tz_naive_fixture):
|
| 19 |
+
"""Fixture returning DatetimeArray with parametrized timezones"""
|
| 20 |
+
tz = tz_naive_fixture
|
| 21 |
+
dtype = DatetimeTZDtype(tz=tz) if tz is not None else np.dtype("M8[ns]")
|
| 22 |
+
arr = DatetimeArray._from_sequence(
|
| 23 |
+
[
|
| 24 |
+
"2000-01-03",
|
| 25 |
+
"2000-01-03",
|
| 26 |
+
"NaT",
|
| 27 |
+
"2000-01-02",
|
| 28 |
+
"2000-01-05",
|
| 29 |
+
"2000-01-04",
|
| 30 |
+
],
|
| 31 |
+
dtype=dtype,
|
| 32 |
+
)
|
| 33 |
+
return arr
|
| 34 |
+
|
| 35 |
+
def test_min_max(self, arr1d, unit):
|
| 36 |
+
arr = arr1d
|
| 37 |
+
arr = arr.as_unit(unit)
|
| 38 |
+
tz = arr.tz
|
| 39 |
+
|
| 40 |
+
result = arr.min()
|
| 41 |
+
expected = pd.Timestamp("2000-01-02", tz=tz).as_unit(unit)
|
| 42 |
+
assert result == expected
|
| 43 |
+
assert result.unit == expected.unit
|
| 44 |
+
|
| 45 |
+
result = arr.max()
|
| 46 |
+
expected = pd.Timestamp("2000-01-05", tz=tz).as_unit(unit)
|
| 47 |
+
assert result == expected
|
| 48 |
+
assert result.unit == expected.unit
|
| 49 |
+
|
| 50 |
+
result = arr.min(skipna=False)
|
| 51 |
+
assert result is NaT
|
| 52 |
+
|
| 53 |
+
result = arr.max(skipna=False)
|
| 54 |
+
assert result is NaT
|
| 55 |
+
|
| 56 |
+
@pytest.mark.parametrize("tz", [None, "US/Central"])
|
| 57 |
+
@pytest.mark.parametrize("skipna", [True, False])
|
| 58 |
+
def test_min_max_empty(self, skipna, tz):
|
| 59 |
+
dtype = DatetimeTZDtype(tz=tz) if tz is not None else np.dtype("M8[ns]")
|
| 60 |
+
arr = DatetimeArray._from_sequence([], dtype=dtype)
|
| 61 |
+
result = arr.min(skipna=skipna)
|
| 62 |
+
assert result is NaT
|
| 63 |
+
|
| 64 |
+
result = arr.max(skipna=skipna)
|
| 65 |
+
assert result is NaT
|
| 66 |
+
|
| 67 |
+
@pytest.mark.parametrize("tz", [None, "US/Central"])
|
| 68 |
+
@pytest.mark.parametrize("skipna", [True, False])
|
| 69 |
+
def test_median_empty(self, skipna, tz):
|
| 70 |
+
dtype = DatetimeTZDtype(tz=tz) if tz is not None else np.dtype("M8[ns]")
|
| 71 |
+
arr = DatetimeArray._from_sequence([], dtype=dtype)
|
| 72 |
+
result = arr.median(skipna=skipna)
|
| 73 |
+
assert result is NaT
|
| 74 |
+
|
| 75 |
+
arr = arr.reshape(0, 3)
|
| 76 |
+
result = arr.median(axis=0, skipna=skipna)
|
| 77 |
+
expected = type(arr)._from_sequence([NaT, NaT, NaT], dtype=arr.dtype)
|
| 78 |
+
tm.assert_equal(result, expected)
|
| 79 |
+
|
| 80 |
+
result = arr.median(axis=1, skipna=skipna)
|
| 81 |
+
expected = type(arr)._from_sequence([], dtype=arr.dtype)
|
| 82 |
+
tm.assert_equal(result, expected)
|
| 83 |
+
|
| 84 |
+
def test_median(self, arr1d):
|
| 85 |
+
arr = arr1d
|
| 86 |
+
|
| 87 |
+
result = arr.median()
|
| 88 |
+
assert result == arr[0]
|
| 89 |
+
result = arr.median(skipna=False)
|
| 90 |
+
assert result is NaT
|
| 91 |
+
|
| 92 |
+
result = arr.dropna().median(skipna=False)
|
| 93 |
+
assert result == arr[0]
|
| 94 |
+
|
| 95 |
+
result = arr.median(axis=0)
|
| 96 |
+
assert result == arr[0]
|
| 97 |
+
|
| 98 |
+
def test_median_axis(self, arr1d):
|
| 99 |
+
arr = arr1d
|
| 100 |
+
assert arr.median(axis=0) == arr.median()
|
| 101 |
+
assert arr.median(axis=0, skipna=False) is NaT
|
| 102 |
+
|
| 103 |
+
msg = r"abs\(axis\) must be less than ndim"
|
| 104 |
+
with pytest.raises(ValueError, match=msg):
|
| 105 |
+
arr.median(axis=1)
|
| 106 |
+
|
| 107 |
+
@pytest.mark.filterwarnings("ignore:All-NaN slice encountered:RuntimeWarning")
|
| 108 |
+
def test_median_2d(self, arr1d):
|
| 109 |
+
arr = arr1d.reshape(1, -1)
|
| 110 |
+
|
| 111 |
+
# axis = None
|
| 112 |
+
assert arr.median() == arr1d.median()
|
| 113 |
+
assert arr.median(skipna=False) is NaT
|
| 114 |
+
|
| 115 |
+
# axis = 0
|
| 116 |
+
result = arr.median(axis=0)
|
| 117 |
+
expected = arr1d
|
| 118 |
+
tm.assert_equal(result, expected)
|
| 119 |
+
|
| 120 |
+
# Since column 3 is all-NaT, we get NaT there with or without skipna
|
| 121 |
+
result = arr.median(axis=0, skipna=False)
|
| 122 |
+
expected = arr1d
|
| 123 |
+
tm.assert_equal(result, expected)
|
| 124 |
+
|
| 125 |
+
# axis = 1
|
| 126 |
+
result = arr.median(axis=1)
|
| 127 |
+
expected = type(arr)._from_sequence([arr1d.median()], dtype=arr.dtype)
|
| 128 |
+
tm.assert_equal(result, expected)
|
| 129 |
+
|
| 130 |
+
result = arr.median(axis=1, skipna=False)
|
| 131 |
+
expected = type(arr)._from_sequence([NaT], dtype=arr.dtype)
|
| 132 |
+
tm.assert_equal(result, expected)
|
| 133 |
+
|
| 134 |
+
def test_mean(self, arr1d):
|
| 135 |
+
arr = arr1d
|
| 136 |
+
|
| 137 |
+
# manually verified result
|
| 138 |
+
expected = arr[0] + 0.4 * pd.Timedelta(days=1)
|
| 139 |
+
|
| 140 |
+
result = arr.mean()
|
| 141 |
+
assert result == expected
|
| 142 |
+
result = arr.mean(skipna=False)
|
| 143 |
+
assert result is NaT
|
| 144 |
+
|
| 145 |
+
result = arr.dropna().mean(skipna=False)
|
| 146 |
+
assert result == expected
|
| 147 |
+
|
| 148 |
+
result = arr.mean(axis=0)
|
| 149 |
+
assert result == expected
|
| 150 |
+
|
| 151 |
+
def test_mean_2d(self):
|
| 152 |
+
dti = pd.date_range("2016-01-01", periods=6, tz="US/Pacific")
|
| 153 |
+
dta = dti._data.reshape(3, 2)
|
| 154 |
+
|
| 155 |
+
result = dta.mean(axis=0)
|
| 156 |
+
expected = dta[1]
|
| 157 |
+
tm.assert_datetime_array_equal(result, expected)
|
| 158 |
+
|
| 159 |
+
result = dta.mean(axis=1)
|
| 160 |
+
expected = dta[:, 0] + pd.Timedelta(hours=12)
|
| 161 |
+
tm.assert_datetime_array_equal(result, expected)
|
| 162 |
+
|
| 163 |
+
result = dta.mean(axis=None)
|
| 164 |
+
expected = dti.mean()
|
| 165 |
+
assert result == expected
|
| 166 |
+
|
| 167 |
+
@pytest.mark.parametrize("skipna", [True, False])
|
| 168 |
+
def test_mean_empty(self, arr1d, skipna):
|
| 169 |
+
arr = arr1d[:0]
|
| 170 |
+
|
| 171 |
+
assert arr.mean(skipna=skipna) is NaT
|
| 172 |
+
|
| 173 |
+
arr2d = arr.reshape(0, 3)
|
| 174 |
+
result = arr2d.mean(axis=0, skipna=skipna)
|
| 175 |
+
expected = DatetimeArray._from_sequence([NaT, NaT, NaT], dtype=arr.dtype)
|
| 176 |
+
tm.assert_datetime_array_equal(result, expected)
|
| 177 |
+
|
| 178 |
+
result = arr2d.mean(axis=1, skipna=skipna)
|
| 179 |
+
expected = arr # i.e. 1D, empty
|
| 180 |
+
tm.assert_datetime_array_equal(result, expected)
|
| 181 |
+
|
| 182 |
+
result = arr2d.mean(axis=None, skipna=skipna)
|
| 183 |
+
assert result is NaT
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/floating/__init__.py
ADDED
|
File without changes
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/floating/conftest.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from pandas.core.arrays.floating import (
|
| 6 |
+
Float32Dtype,
|
| 7 |
+
Float64Dtype,
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@pytest.fixture(params=[Float32Dtype, Float64Dtype])
|
| 12 |
+
def dtype(request):
|
| 13 |
+
"""Parametrized fixture returning a float 'dtype'"""
|
| 14 |
+
return request.param()
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@pytest.fixture
|
| 18 |
+
def data(dtype):
|
| 19 |
+
"""Fixture returning 'data' array according to parametrized float 'dtype'"""
|
| 20 |
+
return pd.array(
|
| 21 |
+
list(np.arange(0.1, 0.9, 0.1))
|
| 22 |
+
+ [pd.NA]
|
| 23 |
+
+ list(np.arange(1, 9.8, 0.1))
|
| 24 |
+
+ [pd.NA]
|
| 25 |
+
+ [9.9, 10.0],
|
| 26 |
+
dtype=dtype,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@pytest.fixture
|
| 31 |
+
def data_missing(dtype):
|
| 32 |
+
"""
|
| 33 |
+
Fixture returning array with missing data according to parametrized float
|
| 34 |
+
'dtype'.
|
| 35 |
+
"""
|
| 36 |
+
return pd.array([np.nan, 0.1], dtype=dtype)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@pytest.fixture(params=["data", "data_missing"])
|
| 40 |
+
def all_data(request, data, data_missing):
|
| 41 |
+
"""Parametrized fixture returning 'data' or 'data_missing' float arrays.
|
| 42 |
+
|
| 43 |
+
Used to test dtype conversion with and without missing values.
|
| 44 |
+
"""
|
| 45 |
+
if request.param == "data":
|
| 46 |
+
return data
|
| 47 |
+
elif request.param == "data_missing":
|
| 48 |
+
return data_missing
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/floating/test_arithmetic.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import operator
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import pandas._testing as tm
|
| 8 |
+
from pandas.core.arrays import FloatingArray
|
| 9 |
+
|
| 10 |
+
# Basic test for the arithmetic array ops
|
| 11 |
+
# -----------------------------------------------------------------------------
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@pytest.mark.parametrize(
|
| 15 |
+
"opname, exp",
|
| 16 |
+
[
|
| 17 |
+
("add", [1.1, 2.2, None, None, 5.5]),
|
| 18 |
+
("mul", [0.1, 0.4, None, None, 2.5]),
|
| 19 |
+
("sub", [0.9, 1.8, None, None, 4.5]),
|
| 20 |
+
("truediv", [10.0, 10.0, None, None, 10.0]),
|
| 21 |
+
("floordiv", [9.0, 9.0, None, None, 10.0]),
|
| 22 |
+
("mod", [0.1, 0.2, None, None, 0.0]),
|
| 23 |
+
],
|
| 24 |
+
ids=["add", "mul", "sub", "div", "floordiv", "mod"],
|
| 25 |
+
)
|
| 26 |
+
def test_array_op(dtype, opname, exp):
|
| 27 |
+
a = pd.array([1.0, 2.0, None, 4.0, 5.0], dtype=dtype)
|
| 28 |
+
b = pd.array([0.1, 0.2, 0.3, None, 0.5], dtype=dtype)
|
| 29 |
+
|
| 30 |
+
op = getattr(operator, opname)
|
| 31 |
+
|
| 32 |
+
result = op(a, b)
|
| 33 |
+
expected = pd.array(exp, dtype=dtype)
|
| 34 |
+
tm.assert_extension_array_equal(result, expected)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@pytest.mark.parametrize("zero, negative", [(0, False), (0.0, False), (-0.0, True)])
|
| 38 |
+
def test_divide_by_zero(dtype, zero, negative):
|
| 39 |
+
# TODO pending NA/NaN discussion
|
| 40 |
+
# https://github.com/pandas-dev/pandas/issues/32265/
|
| 41 |
+
a = pd.array([0, 1, -1, None], dtype=dtype)
|
| 42 |
+
result = a / zero
|
| 43 |
+
expected = FloatingArray(
|
| 44 |
+
np.array([np.nan, np.inf, -np.inf, np.nan], dtype=dtype.numpy_dtype),
|
| 45 |
+
np.array([False, False, False, True]),
|
| 46 |
+
)
|
| 47 |
+
if negative:
|
| 48 |
+
expected *= -1
|
| 49 |
+
tm.assert_extension_array_equal(result, expected)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def test_pow_scalar(dtype):
|
| 53 |
+
a = pd.array([-1, 0, 1, None, 2], dtype=dtype)
|
| 54 |
+
result = a**0
|
| 55 |
+
expected = pd.array([1, 1, 1, 1, 1], dtype=dtype)
|
| 56 |
+
tm.assert_extension_array_equal(result, expected)
|
| 57 |
+
|
| 58 |
+
result = a**1
|
| 59 |
+
expected = pd.array([-1, 0, 1, None, 2], dtype=dtype)
|
| 60 |
+
tm.assert_extension_array_equal(result, expected)
|
| 61 |
+
|
| 62 |
+
result = a**pd.NA
|
| 63 |
+
expected = pd.array([None, None, 1, None, None], dtype=dtype)
|
| 64 |
+
tm.assert_extension_array_equal(result, expected)
|
| 65 |
+
|
| 66 |
+
result = a**np.nan
|
| 67 |
+
# TODO np.nan should be converted to pd.NA / missing before operation?
|
| 68 |
+
expected = FloatingArray(
|
| 69 |
+
np.array([np.nan, np.nan, 1, np.nan, np.nan], dtype=dtype.numpy_dtype),
|
| 70 |
+
mask=a._mask,
|
| 71 |
+
)
|
| 72 |
+
tm.assert_extension_array_equal(result, expected)
|
| 73 |
+
|
| 74 |
+
# reversed
|
| 75 |
+
a = a[1:] # Can't raise integers to negative powers.
|
| 76 |
+
|
| 77 |
+
result = 0**a
|
| 78 |
+
expected = pd.array([1, 0, None, 0], dtype=dtype)
|
| 79 |
+
tm.assert_extension_array_equal(result, expected)
|
| 80 |
+
|
| 81 |
+
result = 1**a
|
| 82 |
+
expected = pd.array([1, 1, 1, 1], dtype=dtype)
|
| 83 |
+
tm.assert_extension_array_equal(result, expected)
|
| 84 |
+
|
| 85 |
+
result = pd.NA**a
|
| 86 |
+
expected = pd.array([1, None, None, None], dtype=dtype)
|
| 87 |
+
tm.assert_extension_array_equal(result, expected)
|
| 88 |
+
|
| 89 |
+
result = np.nan**a
|
| 90 |
+
expected = FloatingArray(
|
| 91 |
+
np.array([1, np.nan, np.nan, np.nan], dtype=dtype.numpy_dtype), mask=a._mask
|
| 92 |
+
)
|
| 93 |
+
tm.assert_extension_array_equal(result, expected)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def test_pow_array(dtype):
|
| 97 |
+
a = pd.array([0, 0, 0, 1, 1, 1, None, None, None], dtype=dtype)
|
| 98 |
+
b = pd.array([0, 1, None, 0, 1, None, 0, 1, None], dtype=dtype)
|
| 99 |
+
result = a**b
|
| 100 |
+
expected = pd.array([1, 0, None, 1, 1, 1, 1, None, None], dtype=dtype)
|
| 101 |
+
tm.assert_extension_array_equal(result, expected)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def test_rpow_one_to_na():
|
| 105 |
+
# https://github.com/pandas-dev/pandas/issues/22022
|
| 106 |
+
# https://github.com/pandas-dev/pandas/issues/29997
|
| 107 |
+
arr = pd.array([np.nan, np.nan], dtype="Float64")
|
| 108 |
+
result = np.array([1.0, 2.0]) ** arr
|
| 109 |
+
expected = pd.array([1.0, np.nan], dtype="Float64")
|
| 110 |
+
tm.assert_extension_array_equal(result, expected)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
@pytest.mark.parametrize("other", [0, 0.5])
|
| 114 |
+
def test_arith_zero_dim_ndarray(other):
|
| 115 |
+
arr = pd.array([1, None, 2], dtype="Float64")
|
| 116 |
+
result = arr + np.array(other)
|
| 117 |
+
expected = arr + other
|
| 118 |
+
tm.assert_equal(result, expected)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
# Test generic characteristics / errors
|
| 122 |
+
# -----------------------------------------------------------------------------
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def test_error_invalid_values(data, all_arithmetic_operators):
|
| 126 |
+
op = all_arithmetic_operators
|
| 127 |
+
s = pd.Series(data)
|
| 128 |
+
ops = getattr(s, op)
|
| 129 |
+
|
| 130 |
+
# invalid scalars
|
| 131 |
+
msg = "|".join(
|
| 132 |
+
[
|
| 133 |
+
r"can only perform ops with numeric values",
|
| 134 |
+
r"FloatingArray cannot perform the operation mod",
|
| 135 |
+
"unsupported operand type",
|
| 136 |
+
"not all arguments converted during string formatting",
|
| 137 |
+
"can't multiply sequence by non-int of type 'float'",
|
| 138 |
+
"ufunc 'subtract' cannot use operands with types dtype",
|
| 139 |
+
r"can only concatenate str \(not \"float\"\) to str",
|
| 140 |
+
"ufunc '.*' not supported for the input types, and the inputs could not",
|
| 141 |
+
"ufunc '.*' did not contain a loop with signature matching types",
|
| 142 |
+
"Concatenation operation is not implemented for NumPy arrays",
|
| 143 |
+
"has no kernel",
|
| 144 |
+
"not implemented",
|
| 145 |
+
"not supported for dtype",
|
| 146 |
+
"Can only string multiply by an integer",
|
| 147 |
+
]
|
| 148 |
+
)
|
| 149 |
+
with pytest.raises(TypeError, match=msg):
|
| 150 |
+
ops("foo")
|
| 151 |
+
with pytest.raises(TypeError, match=msg):
|
| 152 |
+
ops(pd.Timestamp("20180101"))
|
| 153 |
+
|
| 154 |
+
# invalid array-likes
|
| 155 |
+
with pytest.raises(TypeError, match=msg):
|
| 156 |
+
ops(pd.Series("foo", index=s.index))
|
| 157 |
+
|
| 158 |
+
msg = "|".join(
|
| 159 |
+
[
|
| 160 |
+
"can only perform ops with numeric values",
|
| 161 |
+
"cannot perform .* with this index type: DatetimeArray",
|
| 162 |
+
"Addition/subtraction of integers and integer-arrays "
|
| 163 |
+
"with DatetimeArray is no longer supported. *",
|
| 164 |
+
"unsupported operand type",
|
| 165 |
+
"not all arguments converted during string formatting",
|
| 166 |
+
"can't multiply sequence by non-int of type 'float'",
|
| 167 |
+
"ufunc 'subtract' cannot use operands with types dtype",
|
| 168 |
+
(
|
| 169 |
+
"ufunc 'add' cannot use operands with types "
|
| 170 |
+
rf"dtype\('{tm.ENDIAN}M8\[ns\]'\)"
|
| 171 |
+
),
|
| 172 |
+
r"ufunc 'add' cannot use operands with types dtype\('float\d{2}'\)",
|
| 173 |
+
"cannot subtract DatetimeArray from ndarray",
|
| 174 |
+
"has no kernel",
|
| 175 |
+
"not implemented",
|
| 176 |
+
"not supported for dtype",
|
| 177 |
+
]
|
| 178 |
+
)
|
| 179 |
+
with pytest.raises(TypeError, match=msg):
|
| 180 |
+
ops(pd.Series(pd.date_range("20180101", periods=len(s))))
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
# Various
|
| 184 |
+
# -----------------------------------------------------------------------------
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def test_cross_type_arithmetic():
|
| 188 |
+
df = pd.DataFrame(
|
| 189 |
+
{
|
| 190 |
+
"A": pd.array([1, 2, np.nan], dtype="Float64"),
|
| 191 |
+
"B": pd.array([1, np.nan, 3], dtype="Float32"),
|
| 192 |
+
"C": np.array([1, 2, 3], dtype="float64"),
|
| 193 |
+
}
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
result = df.A + df.C
|
| 197 |
+
expected = pd.Series([2, 4, np.nan], dtype="Float64")
|
| 198 |
+
tm.assert_series_equal(result, expected)
|
| 199 |
+
|
| 200 |
+
result = (df.A + df.C) * 3 == 12
|
| 201 |
+
expected = pd.Series([False, True, None], dtype="boolean")
|
| 202 |
+
tm.assert_series_equal(result, expected)
|
| 203 |
+
|
| 204 |
+
result = df.A + df.B
|
| 205 |
+
expected = pd.Series([2, np.nan, np.nan], dtype="Float64")
|
| 206 |
+
tm.assert_series_equal(result, expected)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
@pytest.mark.parametrize(
|
| 210 |
+
"source, neg_target, abs_target",
|
| 211 |
+
[
|
| 212 |
+
([1.1, 2.2, 3.3], [-1.1, -2.2, -3.3], [1.1, 2.2, 3.3]),
|
| 213 |
+
([1.1, 2.2, None], [-1.1, -2.2, None], [1.1, 2.2, None]),
|
| 214 |
+
([-1.1, 0.0, 1.1], [1.1, 0.0, -1.1], [1.1, 0.0, 1.1]),
|
| 215 |
+
],
|
| 216 |
+
)
|
| 217 |
+
def test_unary_float_operators(float_ea_dtype, source, neg_target, abs_target):
|
| 218 |
+
# GH38794
|
| 219 |
+
dtype = float_ea_dtype
|
| 220 |
+
arr = pd.array(source, dtype=dtype)
|
| 221 |
+
neg_result, pos_result, abs_result = -arr, +arr, abs(arr)
|
| 222 |
+
neg_target = pd.array(neg_target, dtype=dtype)
|
| 223 |
+
abs_target = pd.array(abs_target, dtype=dtype)
|
| 224 |
+
|
| 225 |
+
tm.assert_extension_array_equal(neg_result, neg_target)
|
| 226 |
+
tm.assert_extension_array_equal(pos_result, arr)
|
| 227 |
+
assert not tm.shares_memory(pos_result, arr)
|
| 228 |
+
tm.assert_extension_array_equal(abs_result, abs_target)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def test_bitwise(dtype):
|
| 232 |
+
left = pd.array([1, None, 3, 4], dtype=dtype)
|
| 233 |
+
right = pd.array([None, 3, 5, 4], dtype=dtype)
|
| 234 |
+
|
| 235 |
+
with pytest.raises(TypeError, match="unsupported operand type"):
|
| 236 |
+
left | right
|
| 237 |
+
with pytest.raises(TypeError, match="unsupported operand type"):
|
| 238 |
+
left & right
|
| 239 |
+
with pytest.raises(TypeError, match="unsupported operand type"):
|
| 240 |
+
left ^ right
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/floating/test_astype.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import pandas._testing as tm
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_astype():
|
| 9 |
+
# with missing values
|
| 10 |
+
arr = pd.array([0.1, 0.2, None], dtype="Float64")
|
| 11 |
+
|
| 12 |
+
with pytest.raises(ValueError, match="cannot convert NA to integer"):
|
| 13 |
+
arr.astype("int64")
|
| 14 |
+
|
| 15 |
+
with pytest.raises(ValueError, match="cannot convert float NaN to bool"):
|
| 16 |
+
arr.astype("bool")
|
| 17 |
+
|
| 18 |
+
result = arr.astype("float64")
|
| 19 |
+
expected = np.array([0.1, 0.2, np.nan], dtype="float64")
|
| 20 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 21 |
+
|
| 22 |
+
# no missing values
|
| 23 |
+
arr = pd.array([0.0, 1.0, 0.5], dtype="Float64")
|
| 24 |
+
result = arr.astype("int64")
|
| 25 |
+
expected = np.array([0, 1, 0], dtype="int64")
|
| 26 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 27 |
+
|
| 28 |
+
result = arr.astype("bool")
|
| 29 |
+
expected = np.array([False, True, True], dtype="bool")
|
| 30 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def test_astype_to_floating_array():
|
| 34 |
+
# astype to FloatingArray
|
| 35 |
+
arr = pd.array([0.0, 1.0, None], dtype="Float64")
|
| 36 |
+
|
| 37 |
+
result = arr.astype("Float64")
|
| 38 |
+
tm.assert_extension_array_equal(result, arr)
|
| 39 |
+
result = arr.astype(pd.Float64Dtype())
|
| 40 |
+
tm.assert_extension_array_equal(result, arr)
|
| 41 |
+
result = arr.astype("Float32")
|
| 42 |
+
expected = pd.array([0.0, 1.0, None], dtype="Float32")
|
| 43 |
+
tm.assert_extension_array_equal(result, expected)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def test_astype_to_boolean_array():
|
| 47 |
+
# astype to BooleanArray
|
| 48 |
+
arr = pd.array([0.0, 1.0, None], dtype="Float64")
|
| 49 |
+
|
| 50 |
+
result = arr.astype("boolean")
|
| 51 |
+
expected = pd.array([False, True, None], dtype="boolean")
|
| 52 |
+
tm.assert_extension_array_equal(result, expected)
|
| 53 |
+
result = arr.astype(pd.BooleanDtype())
|
| 54 |
+
tm.assert_extension_array_equal(result, expected)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def test_astype_to_integer_array():
|
| 58 |
+
# astype to IntegerArray
|
| 59 |
+
arr = pd.array([0.0, 1.5, None], dtype="Float64")
|
| 60 |
+
|
| 61 |
+
result = arr.astype("Int64")
|
| 62 |
+
expected = pd.array([0, 1, None], dtype="Int64")
|
| 63 |
+
tm.assert_extension_array_equal(result, expected)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def test_astype_str(using_infer_string):
|
| 67 |
+
a = pd.array([0.1, 0.2, None], dtype="Float64")
|
| 68 |
+
|
| 69 |
+
if using_infer_string:
|
| 70 |
+
expected = pd.array(["0.1", "0.2", None], dtype=pd.StringDtype(na_value=np.nan))
|
| 71 |
+
|
| 72 |
+
tm.assert_extension_array_equal(a.astype(str), expected)
|
| 73 |
+
tm.assert_extension_array_equal(a.astype("str"), expected)
|
| 74 |
+
else:
|
| 75 |
+
expected = np.array(["0.1", "0.2", "<NA>"], dtype="U32")
|
| 76 |
+
|
| 77 |
+
tm.assert_numpy_array_equal(a.astype(str), expected)
|
| 78 |
+
tm.assert_numpy_array_equal(a.astype("str"), expected)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def test_astype_copy():
|
| 82 |
+
arr = pd.array([0.1, 0.2, None], dtype="Float64")
|
| 83 |
+
orig = pd.array([0.1, 0.2, None], dtype="Float64")
|
| 84 |
+
|
| 85 |
+
# copy=True -> ensure both data and mask are actual copies
|
| 86 |
+
result = arr.astype("Float64", copy=True)
|
| 87 |
+
assert result is not arr
|
| 88 |
+
assert not tm.shares_memory(result, arr)
|
| 89 |
+
result[0] = 10
|
| 90 |
+
tm.assert_extension_array_equal(arr, orig)
|
| 91 |
+
result[0] = pd.NA
|
| 92 |
+
tm.assert_extension_array_equal(arr, orig)
|
| 93 |
+
|
| 94 |
+
# copy=False
|
| 95 |
+
result = arr.astype("Float64", copy=False)
|
| 96 |
+
assert result is arr
|
| 97 |
+
assert np.shares_memory(result._data, arr._data)
|
| 98 |
+
assert np.shares_memory(result._mask, arr._mask)
|
| 99 |
+
result[0] = 10
|
| 100 |
+
assert arr[0] == 10
|
| 101 |
+
result[0] = pd.NA
|
| 102 |
+
assert arr[0] is pd.NA
|
| 103 |
+
|
| 104 |
+
# astype to different dtype -> always needs a copy -> even with copy=False
|
| 105 |
+
# we need to ensure that also the mask is actually copied
|
| 106 |
+
arr = pd.array([0.1, 0.2, None], dtype="Float64")
|
| 107 |
+
orig = pd.array([0.1, 0.2, None], dtype="Float64")
|
| 108 |
+
|
| 109 |
+
result = arr.astype("Float32", copy=False)
|
| 110 |
+
assert not tm.shares_memory(result, arr)
|
| 111 |
+
result[0] = 10
|
| 112 |
+
tm.assert_extension_array_equal(arr, orig)
|
| 113 |
+
result[0] = pd.NA
|
| 114 |
+
tm.assert_extension_array_equal(arr, orig)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def test_astype_object(dtype):
|
| 118 |
+
arr = pd.array([1.0, pd.NA], dtype=dtype)
|
| 119 |
+
|
| 120 |
+
result = arr.astype(object)
|
| 121 |
+
expected = np.array([1.0, pd.NA], dtype=object)
|
| 122 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 123 |
+
# check exact element types
|
| 124 |
+
assert isinstance(result[0], float)
|
| 125 |
+
assert result[1] is pd.NA
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def test_Float64_conversion():
|
| 129 |
+
# GH#40729
|
| 130 |
+
testseries = pd.Series(["1", "2", "3", "4"], dtype="object")
|
| 131 |
+
result = testseries.astype(pd.Float64Dtype())
|
| 132 |
+
|
| 133 |
+
expected = pd.Series([1.0, 2.0, 3.0, 4.0], dtype=pd.Float64Dtype())
|
| 134 |
+
|
| 135 |
+
tm.assert_series_equal(result, expected)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/floating/test_comparison.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import pandas._testing as tm
|
| 6 |
+
from pandas.core.arrays import FloatingArray
|
| 7 |
+
from pandas.tests.arrays.masked_shared import (
|
| 8 |
+
ComparisonOps,
|
| 9 |
+
NumericOps,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class TestComparisonOps(NumericOps, ComparisonOps):
|
| 14 |
+
@pytest.mark.parametrize("other", [True, False, pd.NA, -1.0, 0.0, 1])
|
| 15 |
+
def test_scalar(self, other, comparison_op, dtype):
|
| 16 |
+
ComparisonOps.test_scalar(self, other, comparison_op, dtype)
|
| 17 |
+
|
| 18 |
+
def test_compare_with_integerarray(self, comparison_op):
|
| 19 |
+
op = comparison_op
|
| 20 |
+
a = pd.array([0, 1, None] * 3, dtype="Int64")
|
| 21 |
+
b = pd.array([0] * 3 + [1] * 3 + [None] * 3, dtype="Float64")
|
| 22 |
+
other = b.astype("Int64")
|
| 23 |
+
expected = op(a, other)
|
| 24 |
+
result = op(a, b)
|
| 25 |
+
tm.assert_extension_array_equal(result, expected)
|
| 26 |
+
expected = op(other, a)
|
| 27 |
+
result = op(b, a)
|
| 28 |
+
tm.assert_extension_array_equal(result, expected)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def test_equals():
|
| 32 |
+
# GH-30652
|
| 33 |
+
# equals is generally tested in /tests/extension/base/methods, but this
|
| 34 |
+
# specifically tests that two arrays of the same class but different dtype
|
| 35 |
+
# do not evaluate equal
|
| 36 |
+
a1 = pd.array([1, 2, None], dtype="Float64")
|
| 37 |
+
a2 = pd.array([1, 2, None], dtype="Float32")
|
| 38 |
+
assert a1.equals(a2) is False
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def test_equals_nan_vs_na():
|
| 42 |
+
# GH#44382
|
| 43 |
+
|
| 44 |
+
mask = np.zeros(3, dtype=bool)
|
| 45 |
+
data = np.array([1.0, np.nan, 3.0], dtype=np.float64)
|
| 46 |
+
|
| 47 |
+
left = FloatingArray(data, mask)
|
| 48 |
+
assert left.equals(left)
|
| 49 |
+
tm.assert_extension_array_equal(left, left)
|
| 50 |
+
|
| 51 |
+
assert left.equals(left.copy())
|
| 52 |
+
assert left.equals(FloatingArray(data.copy(), mask.copy()))
|
| 53 |
+
|
| 54 |
+
mask2 = np.array([False, True, False], dtype=bool)
|
| 55 |
+
data2 = np.array([1.0, 2.0, 3.0], dtype=np.float64)
|
| 56 |
+
right = FloatingArray(data2, mask2)
|
| 57 |
+
assert right.equals(right)
|
| 58 |
+
tm.assert_extension_array_equal(right, right)
|
| 59 |
+
|
| 60 |
+
assert not left.equals(right)
|
| 61 |
+
|
| 62 |
+
# with mask[1] = True, the only difference is data[1], which should
|
| 63 |
+
# not matter for equals
|
| 64 |
+
mask[1] = True
|
| 65 |
+
assert left.equals(right)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/floating/test_concat.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import pandas._testing as tm
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
@pytest.mark.parametrize(
|
| 8 |
+
"to_concat_dtypes, result_dtype",
|
| 9 |
+
[
|
| 10 |
+
(["Float64", "Float64"], "Float64"),
|
| 11 |
+
(["Float32", "Float64"], "Float64"),
|
| 12 |
+
(["Float32", "Float32"], "Float32"),
|
| 13 |
+
],
|
| 14 |
+
)
|
| 15 |
+
def test_concat_series(to_concat_dtypes, result_dtype):
|
| 16 |
+
result = pd.concat([pd.Series([1, 2, pd.NA], dtype=t) for t in to_concat_dtypes])
|
| 17 |
+
expected = pd.concat([pd.Series([1, 2, pd.NA], dtype=object)] * 2).astype(
|
| 18 |
+
result_dtype
|
| 19 |
+
)
|
| 20 |
+
tm.assert_series_equal(result, expected)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/floating/test_construction.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import pandas._testing as tm
|
| 6 |
+
from pandas.core.arrays import FloatingArray
|
| 7 |
+
from pandas.core.arrays.floating import (
|
| 8 |
+
Float32Dtype,
|
| 9 |
+
Float64Dtype,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def test_uses_pandas_na():
|
| 14 |
+
a = pd.array([1, None], dtype=Float64Dtype())
|
| 15 |
+
assert a[1] is pd.NA
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_floating_array_constructor():
|
| 19 |
+
values = np.array([1, 2, 3, 4], dtype="float64")
|
| 20 |
+
mask = np.array([False, False, False, True], dtype="bool")
|
| 21 |
+
|
| 22 |
+
result = FloatingArray(values, mask)
|
| 23 |
+
expected = pd.array([1, 2, 3, np.nan], dtype="Float64")
|
| 24 |
+
tm.assert_extension_array_equal(result, expected)
|
| 25 |
+
tm.assert_numpy_array_equal(result._data, values)
|
| 26 |
+
tm.assert_numpy_array_equal(result._mask, mask)
|
| 27 |
+
|
| 28 |
+
msg = r".* should be .* numpy array. Use the 'pd.array' function instead"
|
| 29 |
+
with pytest.raises(TypeError, match=msg):
|
| 30 |
+
FloatingArray(values.tolist(), mask)
|
| 31 |
+
|
| 32 |
+
with pytest.raises(TypeError, match=msg):
|
| 33 |
+
FloatingArray(values, mask.tolist())
|
| 34 |
+
|
| 35 |
+
with pytest.raises(TypeError, match=msg):
|
| 36 |
+
FloatingArray(values.astype(int), mask)
|
| 37 |
+
|
| 38 |
+
msg = r"__init__\(\) missing 1 required positional argument: 'mask'"
|
| 39 |
+
with pytest.raises(TypeError, match=msg):
|
| 40 |
+
FloatingArray(values)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_floating_array_disallows_float16():
|
| 44 |
+
# GH#44715
|
| 45 |
+
arr = np.array([1, 2], dtype=np.float16)
|
| 46 |
+
mask = np.array([False, False])
|
| 47 |
+
|
| 48 |
+
msg = "FloatingArray does not support np.float16 dtype"
|
| 49 |
+
with pytest.raises(TypeError, match=msg):
|
| 50 |
+
FloatingArray(arr, mask)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def test_floating_array_disallows_Float16_dtype(request):
|
| 54 |
+
# GH#44715
|
| 55 |
+
with pytest.raises(TypeError, match="data type 'Float16' not understood"):
|
| 56 |
+
pd.array([1.0, 2.0], dtype="Float16")
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def test_floating_array_constructor_copy():
|
| 60 |
+
values = np.array([1, 2, 3, 4], dtype="float64")
|
| 61 |
+
mask = np.array([False, False, False, True], dtype="bool")
|
| 62 |
+
|
| 63 |
+
result = FloatingArray(values, mask)
|
| 64 |
+
assert result._data is values
|
| 65 |
+
assert result._mask is mask
|
| 66 |
+
|
| 67 |
+
result = FloatingArray(values, mask, copy=True)
|
| 68 |
+
assert result._data is not values
|
| 69 |
+
assert result._mask is not mask
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def test_to_array():
|
| 73 |
+
result = pd.array([0.1, 0.2, 0.3, 0.4])
|
| 74 |
+
expected = pd.array([0.1, 0.2, 0.3, 0.4], dtype="Float64")
|
| 75 |
+
tm.assert_extension_array_equal(result, expected)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@pytest.mark.parametrize(
|
| 79 |
+
"a, b",
|
| 80 |
+
[
|
| 81 |
+
([1, None], [1, pd.NA]),
|
| 82 |
+
([None], [pd.NA]),
|
| 83 |
+
([None, np.nan], [pd.NA, pd.NA]),
|
| 84 |
+
([1, np.nan], [1, pd.NA]),
|
| 85 |
+
([np.nan], [pd.NA]),
|
| 86 |
+
],
|
| 87 |
+
)
|
| 88 |
+
def test_to_array_none_is_nan(a, b):
|
| 89 |
+
result = pd.array(a, dtype="Float64")
|
| 90 |
+
expected = pd.array(b, dtype="Float64")
|
| 91 |
+
tm.assert_extension_array_equal(result, expected)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def test_to_array_mixed_integer_float():
|
| 95 |
+
result = pd.array([1, 2.0])
|
| 96 |
+
expected = pd.array([1.0, 2.0], dtype="Float64")
|
| 97 |
+
tm.assert_extension_array_equal(result, expected)
|
| 98 |
+
|
| 99 |
+
result = pd.array([1, None, 2.0])
|
| 100 |
+
expected = pd.array([1.0, None, 2.0], dtype="Float64")
|
| 101 |
+
tm.assert_extension_array_equal(result, expected)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
@pytest.mark.parametrize(
|
| 105 |
+
"values",
|
| 106 |
+
[
|
| 107 |
+
["foo", "bar"],
|
| 108 |
+
"foo",
|
| 109 |
+
1,
|
| 110 |
+
1.0,
|
| 111 |
+
pd.date_range("20130101", periods=2),
|
| 112 |
+
np.array(["foo"]),
|
| 113 |
+
[[1, 2], [3, 4]],
|
| 114 |
+
[np.nan, {"a": 1}],
|
| 115 |
+
# GH#44514 all-NA case used to get quietly swapped out before checking ndim
|
| 116 |
+
np.array([pd.NA] * 6, dtype=object).reshape(3, 2),
|
| 117 |
+
],
|
| 118 |
+
)
|
| 119 |
+
def test_to_array_error(values):
|
| 120 |
+
# error in converting existing arrays to FloatingArray
|
| 121 |
+
msg = "|".join(
|
| 122 |
+
[
|
| 123 |
+
"cannot be converted to FloatingDtype",
|
| 124 |
+
"values must be a 1D list-like",
|
| 125 |
+
"Cannot pass scalar",
|
| 126 |
+
r"float\(\) argument must be a string or a (real )?number, not 'dict'",
|
| 127 |
+
"could not convert string to float: 'foo'",
|
| 128 |
+
r"could not convert string to float: np\.str_\('foo'\)",
|
| 129 |
+
]
|
| 130 |
+
)
|
| 131 |
+
with pytest.raises((TypeError, ValueError), match=msg):
|
| 132 |
+
pd.array(values, dtype="Float64")
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
@pytest.mark.parametrize("values", [["1", "2", None], ["1.5", "2", None]])
|
| 136 |
+
def test_construct_from_float_strings(values):
|
| 137 |
+
# see also test_to_integer_array_str
|
| 138 |
+
expected = pd.array([float(values[0]), 2, None], dtype="Float64")
|
| 139 |
+
|
| 140 |
+
res = pd.array(values, dtype="Float64")
|
| 141 |
+
tm.assert_extension_array_equal(res, expected)
|
| 142 |
+
|
| 143 |
+
res = FloatingArray._from_sequence(values)
|
| 144 |
+
tm.assert_extension_array_equal(res, expected)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def test_to_array_inferred_dtype():
|
| 148 |
+
# if values has dtype -> respect it
|
| 149 |
+
result = pd.array(np.array([1, 2], dtype="float32"))
|
| 150 |
+
assert result.dtype == Float32Dtype()
|
| 151 |
+
|
| 152 |
+
# if values have no dtype -> always float64
|
| 153 |
+
result = pd.array([1.0, 2.0])
|
| 154 |
+
assert result.dtype == Float64Dtype()
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def test_to_array_dtype_keyword():
|
| 158 |
+
result = pd.array([1, 2], dtype="Float32")
|
| 159 |
+
assert result.dtype == Float32Dtype()
|
| 160 |
+
|
| 161 |
+
# if values has dtype -> override it
|
| 162 |
+
result = pd.array(np.array([1, 2], dtype="float32"), dtype="Float64")
|
| 163 |
+
assert result.dtype == Float64Dtype()
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def test_to_array_integer():
|
| 167 |
+
result = pd.array([1, 2], dtype="Float64")
|
| 168 |
+
expected = pd.array([1.0, 2.0], dtype="Float64")
|
| 169 |
+
tm.assert_extension_array_equal(result, expected)
|
| 170 |
+
|
| 171 |
+
# for integer dtypes, the itemsize is not preserved
|
| 172 |
+
# TODO can we specify "floating" in general?
|
| 173 |
+
result = pd.array(np.array([1, 2], dtype="int32"), dtype="Float64")
|
| 174 |
+
assert result.dtype == Float64Dtype()
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
@pytest.mark.parametrize(
|
| 178 |
+
"bool_values, values, target_dtype, expected_dtype",
|
| 179 |
+
[
|
| 180 |
+
([False, True], [0, 1], Float64Dtype(), Float64Dtype()),
|
| 181 |
+
([False, True], [0, 1], "Float64", Float64Dtype()),
|
| 182 |
+
([False, True, np.nan], [0, 1, np.nan], Float64Dtype(), Float64Dtype()),
|
| 183 |
+
],
|
| 184 |
+
)
|
| 185 |
+
def test_to_array_bool(bool_values, values, target_dtype, expected_dtype):
|
| 186 |
+
result = pd.array(bool_values, dtype=target_dtype)
|
| 187 |
+
assert result.dtype == expected_dtype
|
| 188 |
+
expected = pd.array(values, dtype=target_dtype)
|
| 189 |
+
tm.assert_extension_array_equal(result, expected)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def test_series_from_float(data):
|
| 193 |
+
# construct from our dtype & string dtype
|
| 194 |
+
dtype = data.dtype
|
| 195 |
+
|
| 196 |
+
# from float
|
| 197 |
+
expected = pd.Series(data)
|
| 198 |
+
result = pd.Series(data.to_numpy(na_value=np.nan, dtype="float"), dtype=str(dtype))
|
| 199 |
+
tm.assert_series_equal(result, expected)
|
| 200 |
+
|
| 201 |
+
# from list
|
| 202 |
+
expected = pd.Series(data)
|
| 203 |
+
result = pd.Series(np.array(data).tolist(), dtype=str(dtype))
|
| 204 |
+
tm.assert_series_equal(result, expected)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/floating/test_contains.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
import pandas as pd
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def test_contains_nan():
|
| 7 |
+
# GH#52840
|
| 8 |
+
arr = pd.array(range(5)) / 0
|
| 9 |
+
|
| 10 |
+
assert np.isnan(arr._data[0])
|
| 11 |
+
assert not arr.isna()[0]
|
| 12 |
+
assert np.nan in arr
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/floating/test_function.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
# np.sign emits a warning with nans, <https://github.com/numpy/numpy/issues/15127>
|
| 12 |
+
@pytest.mark.filterwarnings("ignore:invalid value encountered in sign:RuntimeWarning")
|
| 13 |
+
def test_ufuncs_single(ufunc):
|
| 14 |
+
a = pd.array([1, 2, -3, np.nan], dtype="Float64")
|
| 15 |
+
result = ufunc(a)
|
| 16 |
+
expected = pd.array(ufunc(a.astype(float)), dtype="Float64")
|
| 17 |
+
tm.assert_extension_array_equal(result, expected)
|
| 18 |
+
|
| 19 |
+
s = pd.Series(a)
|
| 20 |
+
result = ufunc(s)
|
| 21 |
+
expected = pd.Series(expected)
|
| 22 |
+
tm.assert_series_equal(result, expected)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@pytest.mark.parametrize("ufunc", [np.log, np.exp, np.sin, np.cos, np.sqrt])
|
| 26 |
+
def test_ufuncs_single_float(ufunc):
|
| 27 |
+
a = pd.array([1.0, 0.2, 3.0, np.nan], dtype="Float64")
|
| 28 |
+
with np.errstate(invalid="ignore"):
|
| 29 |
+
result = ufunc(a)
|
| 30 |
+
expected = pd.array(ufunc(a.astype(float)), dtype="Float64")
|
| 31 |
+
tm.assert_extension_array_equal(result, expected)
|
| 32 |
+
|
| 33 |
+
s = pd.Series(a)
|
| 34 |
+
with np.errstate(invalid="ignore"):
|
| 35 |
+
result = ufunc(s)
|
| 36 |
+
expected = pd.Series(ufunc(s.astype(float)), dtype="Float64")
|
| 37 |
+
tm.assert_series_equal(result, expected)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@pytest.mark.parametrize("ufunc", [np.add, np.subtract])
|
| 41 |
+
def test_ufuncs_binary_float(ufunc):
|
| 42 |
+
# two FloatingArrays
|
| 43 |
+
a = pd.array([1, 0.2, -3, np.nan], dtype="Float64")
|
| 44 |
+
result = ufunc(a, a)
|
| 45 |
+
expected = pd.array(ufunc(a.astype(float), a.astype(float)), dtype="Float64")
|
| 46 |
+
tm.assert_extension_array_equal(result, expected)
|
| 47 |
+
|
| 48 |
+
# FloatingArray with numpy array
|
| 49 |
+
arr = np.array([1, 2, 3, 4])
|
| 50 |
+
result = ufunc(a, arr)
|
| 51 |
+
expected = pd.array(ufunc(a.astype(float), arr), dtype="Float64")
|
| 52 |
+
tm.assert_extension_array_equal(result, expected)
|
| 53 |
+
|
| 54 |
+
result = ufunc(arr, a)
|
| 55 |
+
expected = pd.array(ufunc(arr, a.astype(float)), dtype="Float64")
|
| 56 |
+
tm.assert_extension_array_equal(result, expected)
|
| 57 |
+
|
| 58 |
+
# FloatingArray with scalar
|
| 59 |
+
result = ufunc(a, 1)
|
| 60 |
+
expected = pd.array(ufunc(a.astype(float), 1), dtype="Float64")
|
| 61 |
+
tm.assert_extension_array_equal(result, expected)
|
| 62 |
+
|
| 63 |
+
result = ufunc(1, a)
|
| 64 |
+
expected = pd.array(ufunc(1, a.astype(float)), dtype="Float64")
|
| 65 |
+
tm.assert_extension_array_equal(result, expected)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@pytest.mark.parametrize("values", [[0, 1], [0, None]])
|
| 69 |
+
def test_ufunc_reduce_raises(values):
|
| 70 |
+
arr = pd.array(values, dtype="Float64")
|
| 71 |
+
|
| 72 |
+
res = np.add.reduce(arr)
|
| 73 |
+
expected = arr.sum(skipna=False)
|
| 74 |
+
tm.assert_almost_equal(res, expected)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@pytest.mark.skipif(not IS64, reason="GH 36579: fail on 32-bit system")
|
| 78 |
+
@pytest.mark.parametrize(
|
| 79 |
+
"pandasmethname, kwargs",
|
| 80 |
+
[
|
| 81 |
+
("var", {"ddof": 0}),
|
| 82 |
+
("var", {"ddof": 1}),
|
| 83 |
+
("std", {"ddof": 0}),
|
| 84 |
+
("std", {"ddof": 1}),
|
| 85 |
+
("kurtosis", {}),
|
| 86 |
+
("skew", {}),
|
| 87 |
+
("sem", {}),
|
| 88 |
+
],
|
| 89 |
+
)
|
| 90 |
+
def test_stat_method(pandasmethname, kwargs):
|
| 91 |
+
s = pd.Series(data=[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, np.nan, np.nan], dtype="Float64")
|
| 92 |
+
pandasmeth = getattr(s, pandasmethname)
|
| 93 |
+
result = pandasmeth(**kwargs)
|
| 94 |
+
s2 = pd.Series(data=[0.1, 0.2, 0.3, 0.4, 0.5, 0.6], dtype="float64")
|
| 95 |
+
pandasmeth = getattr(s2, pandasmethname)
|
| 96 |
+
expected = pandasmeth(**kwargs)
|
| 97 |
+
assert expected == result
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def test_value_counts_na():
|
| 101 |
+
arr = pd.array([0.1, 0.2, 0.1, pd.NA], dtype="Float64")
|
| 102 |
+
result = arr.value_counts(dropna=False)
|
| 103 |
+
idx = pd.Index([0.1, 0.2, pd.NA], dtype=arr.dtype)
|
| 104 |
+
assert idx.dtype == arr.dtype
|
| 105 |
+
expected = pd.Series([2, 1, 1], index=idx, dtype="Int64", name="count")
|
| 106 |
+
tm.assert_series_equal(result, expected)
|
| 107 |
+
|
| 108 |
+
result = arr.value_counts(dropna=True)
|
| 109 |
+
expected = pd.Series([2, 1], index=idx[:-1], dtype="Int64", name="count")
|
| 110 |
+
tm.assert_series_equal(result, expected)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def test_value_counts_empty():
|
| 114 |
+
ser = pd.Series([], dtype="Float64")
|
| 115 |
+
result = ser.value_counts()
|
| 116 |
+
idx = pd.Index([], dtype="Float64")
|
| 117 |
+
assert idx.dtype == "Float64"
|
| 118 |
+
expected = pd.Series([], index=idx, dtype="Int64", name="count")
|
| 119 |
+
tm.assert_series_equal(result, expected)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def test_value_counts_with_normalize():
|
| 123 |
+
ser = pd.Series([0.1, 0.2, 0.1, pd.NA], dtype="Float64")
|
| 124 |
+
result = ser.value_counts(normalize=True)
|
| 125 |
+
expected = pd.Series([2, 1], index=ser[:2], dtype="Float64", name="proportion") / 3
|
| 126 |
+
assert expected.index.dtype == ser.dtype
|
| 127 |
+
tm.assert_series_equal(result, expected)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
@pytest.mark.parametrize("skipna", [True, False])
|
| 131 |
+
@pytest.mark.parametrize("min_count", [0, 4])
|
| 132 |
+
def test_floating_array_sum(skipna, min_count, dtype):
|
| 133 |
+
arr = pd.array([1, 2, 3, None], dtype=dtype)
|
| 134 |
+
result = arr.sum(skipna=skipna, min_count=min_count)
|
| 135 |
+
if skipna and min_count == 0:
|
| 136 |
+
assert result == 6.0
|
| 137 |
+
else:
|
| 138 |
+
assert result is pd.NA
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
@pytest.mark.parametrize(
|
| 142 |
+
"values, expected", [([1, 2, 3], 6.0), ([1, 2, 3, None], 6.0), ([None], 0.0)]
|
| 143 |
+
)
|
| 144 |
+
def test_floating_array_numpy_sum(values, expected):
|
| 145 |
+
arr = pd.array(values, dtype="Float64")
|
| 146 |
+
result = np.sum(arr)
|
| 147 |
+
assert result == expected
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
@pytest.mark.parametrize("op", ["sum", "min", "max", "prod"])
|
| 151 |
+
def test_preserve_dtypes(op):
|
| 152 |
+
df = pd.DataFrame(
|
| 153 |
+
{
|
| 154 |
+
"A": ["a", "b", "b"],
|
| 155 |
+
"B": [1, None, 3],
|
| 156 |
+
"C": pd.array([0.1, None, 3.0], dtype="Float64"),
|
| 157 |
+
}
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
# op
|
| 161 |
+
result = getattr(df.C, op)()
|
| 162 |
+
assert isinstance(result, np.float64)
|
| 163 |
+
|
| 164 |
+
# groupby
|
| 165 |
+
result = getattr(df.groupby("A"), op)()
|
| 166 |
+
|
| 167 |
+
expected = pd.DataFrame(
|
| 168 |
+
{"B": np.array([1.0, 3.0]), "C": pd.array([0.1, 3], dtype="Float64")},
|
| 169 |
+
index=pd.Index(["a", "b"], name="A"),
|
| 170 |
+
)
|
| 171 |
+
tm.assert_frame_equal(result, expected)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
@pytest.mark.parametrize("skipna", [True, False])
|
| 175 |
+
@pytest.mark.parametrize("method", ["min", "max"])
|
| 176 |
+
def test_floating_array_min_max(skipna, method, dtype):
|
| 177 |
+
arr = pd.array([0.0, 1.0, None], dtype=dtype)
|
| 178 |
+
func = getattr(arr, method)
|
| 179 |
+
result = func(skipna=skipna)
|
| 180 |
+
if skipna:
|
| 181 |
+
assert result == (0 if method == "min" else 1)
|
| 182 |
+
else:
|
| 183 |
+
assert result is pd.NA
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
@pytest.mark.parametrize("skipna", [True, False])
|
| 187 |
+
@pytest.mark.parametrize("min_count", [0, 9])
|
| 188 |
+
def test_floating_array_prod(skipna, min_count, dtype):
|
| 189 |
+
arr = pd.array([1.0, 2.0, None], dtype=dtype)
|
| 190 |
+
result = arr.prod(skipna=skipna, min_count=min_count)
|
| 191 |
+
if skipna and min_count == 0:
|
| 192 |
+
assert result == 2
|
| 193 |
+
else:
|
| 194 |
+
assert result is pd.NA
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/floating/test_repr.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from pandas.core.arrays.floating import (
|
| 6 |
+
Float32Dtype,
|
| 7 |
+
Float64Dtype,
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def test_dtypes(dtype):
|
| 12 |
+
# smoke tests on auto dtype construction
|
| 13 |
+
|
| 14 |
+
np.dtype(dtype.type).kind == "f"
|
| 15 |
+
assert dtype.name is not None
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@pytest.mark.parametrize(
|
| 19 |
+
"dtype, expected",
|
| 20 |
+
[(Float32Dtype(), "Float32Dtype()"), (Float64Dtype(), "Float64Dtype()")],
|
| 21 |
+
)
|
| 22 |
+
def test_repr_dtype(dtype, expected):
|
| 23 |
+
assert repr(dtype) == expected
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def test_repr_array():
|
| 27 |
+
result = repr(pd.array([1.0, None, 3.0]))
|
| 28 |
+
expected = "<FloatingArray>\n[1.0, <NA>, 3.0]\nLength: 3, dtype: Float64"
|
| 29 |
+
assert result == expected
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def test_repr_array_long():
|
| 33 |
+
data = pd.array([1.0, 2.0, None] * 1000)
|
| 34 |
+
expected = """<FloatingArray>
|
| 35 |
+
[ 1.0, 2.0, <NA>, 1.0, 2.0, <NA>, 1.0, 2.0, <NA>, 1.0,
|
| 36 |
+
...
|
| 37 |
+
<NA>, 1.0, 2.0, <NA>, 1.0, 2.0, <NA>, 1.0, 2.0, <NA>]
|
| 38 |
+
Length: 3000, dtype: Float64"""
|
| 39 |
+
result = repr(data)
|
| 40 |
+
assert result == expected
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_frame_repr(data_missing):
|
| 44 |
+
df = pd.DataFrame({"A": data_missing})
|
| 45 |
+
result = repr(df)
|
| 46 |
+
expected = " A\n0 <NA>\n1 0.1"
|
| 47 |
+
assert result == expected
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/floating/test_to_numpy.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import pandas._testing as tm
|
| 6 |
+
from pandas.core.arrays import FloatingArray
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@pytest.mark.parametrize("box", [True, False], ids=["series", "array"])
|
| 10 |
+
def test_to_numpy(box):
|
| 11 |
+
con = pd.Series if box else pd.array
|
| 12 |
+
|
| 13 |
+
# default (with or without missing values) -> object dtype
|
| 14 |
+
arr = con([0.1, 0.2, 0.3], dtype="Float64")
|
| 15 |
+
result = arr.to_numpy()
|
| 16 |
+
expected = np.array([0.1, 0.2, 0.3], dtype="float64")
|
| 17 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 18 |
+
|
| 19 |
+
arr = con([0.1, 0.2, None], dtype="Float64")
|
| 20 |
+
result = arr.to_numpy()
|
| 21 |
+
expected = np.array([0.1, 0.2, np.nan], dtype="float64")
|
| 22 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@pytest.mark.parametrize("box", [True, False], ids=["series", "array"])
|
| 26 |
+
def test_to_numpy_float(box):
|
| 27 |
+
con = pd.Series if box else pd.array
|
| 28 |
+
|
| 29 |
+
# no missing values -> can convert to float, otherwise raises
|
| 30 |
+
arr = con([0.1, 0.2, 0.3], dtype="Float64")
|
| 31 |
+
result = arr.to_numpy(dtype="float64")
|
| 32 |
+
expected = np.array([0.1, 0.2, 0.3], dtype="float64")
|
| 33 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 34 |
+
|
| 35 |
+
arr = con([0.1, 0.2, None], dtype="Float64")
|
| 36 |
+
result = arr.to_numpy(dtype="float64")
|
| 37 |
+
expected = np.array([0.1, 0.2, np.nan], dtype="float64")
|
| 38 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 39 |
+
|
| 40 |
+
result = arr.to_numpy(dtype="float64", na_value=np.nan)
|
| 41 |
+
expected = np.array([0.1, 0.2, np.nan], dtype="float64")
|
| 42 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@pytest.mark.parametrize("box", [True, False], ids=["series", "array"])
|
| 46 |
+
def test_to_numpy_int(box):
|
| 47 |
+
con = pd.Series if box else pd.array
|
| 48 |
+
|
| 49 |
+
# no missing values -> can convert to int, otherwise raises
|
| 50 |
+
arr = con([1.0, 2.0, 3.0], dtype="Float64")
|
| 51 |
+
result = arr.to_numpy(dtype="int64")
|
| 52 |
+
expected = np.array([1, 2, 3], dtype="int64")
|
| 53 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 54 |
+
|
| 55 |
+
arr = con([1.0, 2.0, None], dtype="Float64")
|
| 56 |
+
with pytest.raises(ValueError, match="cannot convert to 'int64'-dtype"):
|
| 57 |
+
result = arr.to_numpy(dtype="int64")
|
| 58 |
+
|
| 59 |
+
# automatic casting (floors the values)
|
| 60 |
+
arr = con([0.1, 0.9, 1.1], dtype="Float64")
|
| 61 |
+
result = arr.to_numpy(dtype="int64")
|
| 62 |
+
expected = np.array([0, 0, 1], dtype="int64")
|
| 63 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@pytest.mark.parametrize("box", [True, False], ids=["series", "array"])
|
| 67 |
+
def test_to_numpy_na_value(box):
|
| 68 |
+
con = pd.Series if box else pd.array
|
| 69 |
+
|
| 70 |
+
arr = con([0.0, 1.0, None], dtype="Float64")
|
| 71 |
+
result = arr.to_numpy(dtype=object, na_value=None)
|
| 72 |
+
expected = np.array([0.0, 1.0, None], dtype="object")
|
| 73 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 74 |
+
|
| 75 |
+
result = arr.to_numpy(dtype=bool, na_value=False)
|
| 76 |
+
expected = np.array([False, True, False], dtype="bool")
|
| 77 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 78 |
+
|
| 79 |
+
result = arr.to_numpy(dtype="int64", na_value=-99)
|
| 80 |
+
expected = np.array([0, 1, -99], dtype="int64")
|
| 81 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def test_to_numpy_na_value_with_nan():
|
| 85 |
+
# array with both NaN and NA -> only fill NA with `na_value`
|
| 86 |
+
arr = FloatingArray(np.array([0.0, np.nan, 0.0]), np.array([False, False, True]))
|
| 87 |
+
result = arr.to_numpy(dtype="float64", na_value=-1)
|
| 88 |
+
expected = np.array([0.0, np.nan, -1.0], dtype="float64")
|
| 89 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@pytest.mark.parametrize("dtype", ["float64", "float32", "int32", "int64", "bool"])
|
| 93 |
+
@pytest.mark.parametrize("box", [True, False], ids=["series", "array"])
|
| 94 |
+
def test_to_numpy_dtype(box, dtype):
|
| 95 |
+
con = pd.Series if box else pd.array
|
| 96 |
+
arr = con([0.0, 1.0], dtype="Float64")
|
| 97 |
+
|
| 98 |
+
result = arr.to_numpy(dtype=dtype)
|
| 99 |
+
expected = np.array([0, 1], dtype=dtype)
|
| 100 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@pytest.mark.parametrize("dtype", ["int32", "int64", "bool"])
|
| 104 |
+
@pytest.mark.parametrize("box", [True, False], ids=["series", "array"])
|
| 105 |
+
def test_to_numpy_na_raises(box, dtype):
|
| 106 |
+
con = pd.Series if box else pd.array
|
| 107 |
+
arr = con([0.0, 1.0, None], dtype="Float64")
|
| 108 |
+
with pytest.raises(ValueError, match=dtype):
|
| 109 |
+
arr.to_numpy(dtype=dtype)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@pytest.mark.parametrize("box", [True, False], ids=["series", "array"])
|
| 113 |
+
def test_to_numpy_string(box, dtype):
|
| 114 |
+
con = pd.Series if box else pd.array
|
| 115 |
+
arr = con([0.0, 1.0, None], dtype="Float64")
|
| 116 |
+
|
| 117 |
+
result = arr.to_numpy(dtype="str")
|
| 118 |
+
expected = np.array([0.0, 1.0, pd.NA], dtype=f"{tm.ENDIAN}U32")
|
| 119 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def test_to_numpy_copy():
|
| 123 |
+
# to_numpy can be zero-copy if no missing values
|
| 124 |
+
arr = pd.array([0.1, 0.2, 0.3], dtype="Float64")
|
| 125 |
+
result = arr.to_numpy(dtype="float64")
|
| 126 |
+
result[0] = 10
|
| 127 |
+
tm.assert_extension_array_equal(arr, pd.array([10, 0.2, 0.3], dtype="Float64"))
|
| 128 |
+
|
| 129 |
+
arr = pd.array([0.1, 0.2, 0.3], dtype="Float64")
|
| 130 |
+
result = arr.to_numpy(dtype="float64", copy=True)
|
| 131 |
+
result[0] = 10
|
| 132 |
+
tm.assert_extension_array_equal(arr, pd.array([0.1, 0.2, 0.3], dtype="Float64"))
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/integer/__init__.py
ADDED
|
File without changes
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/integer/conftest.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from pandas.core.arrays.integer import (
|
| 6 |
+
Int8Dtype,
|
| 7 |
+
Int16Dtype,
|
| 8 |
+
Int32Dtype,
|
| 9 |
+
Int64Dtype,
|
| 10 |
+
UInt8Dtype,
|
| 11 |
+
UInt16Dtype,
|
| 12 |
+
UInt32Dtype,
|
| 13 |
+
UInt64Dtype,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@pytest.fixture(
|
| 18 |
+
params=[
|
| 19 |
+
Int8Dtype,
|
| 20 |
+
Int16Dtype,
|
| 21 |
+
Int32Dtype,
|
| 22 |
+
Int64Dtype,
|
| 23 |
+
UInt8Dtype,
|
| 24 |
+
UInt16Dtype,
|
| 25 |
+
UInt32Dtype,
|
| 26 |
+
UInt64Dtype,
|
| 27 |
+
]
|
| 28 |
+
)
|
| 29 |
+
def dtype(request):
|
| 30 |
+
"""Parametrized fixture returning integer 'dtype'"""
|
| 31 |
+
return request.param()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@pytest.fixture
|
| 35 |
+
def data(dtype):
|
| 36 |
+
"""
|
| 37 |
+
Fixture returning 'data' array with valid and missing values according to
|
| 38 |
+
parametrized integer 'dtype'.
|
| 39 |
+
|
| 40 |
+
Used to test dtype conversion with and without missing values.
|
| 41 |
+
"""
|
| 42 |
+
return pd.array(
|
| 43 |
+
list(range(8)) + [np.nan] + list(range(10, 98)) + [np.nan] + [99, 100],
|
| 44 |
+
dtype=dtype,
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@pytest.fixture
|
| 49 |
+
def data_missing(dtype):
|
| 50 |
+
"""
|
| 51 |
+
Fixture returning array with exactly one NaN and one valid integer,
|
| 52 |
+
according to parametrized integer 'dtype'.
|
| 53 |
+
|
| 54 |
+
Used to test dtype conversion with and without missing values.
|
| 55 |
+
"""
|
| 56 |
+
return pd.array([np.nan, 1], dtype=dtype)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@pytest.fixture(params=["data", "data_missing"])
|
| 60 |
+
def all_data(request, data, data_missing):
|
| 61 |
+
"""Parametrized fixture returning 'data' or 'data_missing' integer arrays.
|
| 62 |
+
|
| 63 |
+
Used to test dtype conversion with and without missing values.
|
| 64 |
+
"""
|
| 65 |
+
if request.param == "data":
|
| 66 |
+
return data
|
| 67 |
+
elif request.param == "data_missing":
|
| 68 |
+
return data_miss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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import operator
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import pandas._testing as tm
|
| 8 |
+
from pandas.core import ops
|
| 9 |
+
from pandas.core.arrays import FloatingArray
|
| 10 |
+
|
| 11 |
+
# Basic test for the arithmetic array ops
|
| 12 |
+
# -----------------------------------------------------------------------------
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@pytest.mark.parametrize(
|
| 16 |
+
"opname, exp",
|
| 17 |
+
[("add", [1, 3, None, None, 9]), ("mul", [0, 2, None, None, 20])],
|
| 18 |
+
ids=["add", "mul"],
|
| 19 |
+
)
|
| 20 |
+
def test_add_mul(dtype, opname, exp):
|
| 21 |
+
a = pd.array([0, 1, None, 3, 4], dtype=dtype)
|
| 22 |
+
b = pd.array([1, 2, 3, None, 5], dtype=dtype)
|
| 23 |
+
|
| 24 |
+
# array / array
|
| 25 |
+
expected = pd.array(exp, dtype=dtype)
|
| 26 |
+
|
| 27 |
+
op = getattr(operator, opname)
|
| 28 |
+
result = op(a, b)
|
| 29 |
+
tm.assert_extension_array_equal(result, expected)
|
| 30 |
+
|
| 31 |
+
op = getattr(ops, "r" + opname)
|
| 32 |
+
result = op(a, b)
|
| 33 |
+
tm.assert_extension_array_equal(result, expected)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def test_sub(dtype):
|
| 37 |
+
a = pd.array([1, 2, 3, None, 5], dtype=dtype)
|
| 38 |
+
b = pd.array([0, 1, None, 3, 4], dtype=dtype)
|
| 39 |
+
|
| 40 |
+
result = a - b
|
| 41 |
+
expected = pd.array([1, 1, None, None, 1], dtype=dtype)
|
| 42 |
+
tm.assert_extension_array_equal(result, expected)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def test_div(dtype):
|
| 46 |
+
a = pd.array([1, 2, 3, None, 5], dtype=dtype)
|
| 47 |
+
b = pd.array([0, 1, None, 3, 4], dtype=dtype)
|
| 48 |
+
|
| 49 |
+
result = a / b
|
| 50 |
+
expected = pd.array([np.inf, 2, None, None, 1.25], dtype="Float64")
|
| 51 |
+
tm.assert_extension_array_equal(result, expected)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@pytest.mark.parametrize("zero, negative", [(0, False), (0.0, False), (-0.0, True)])
|
| 55 |
+
def test_divide_by_zero(zero, negative):
|
| 56 |
+
# https://github.com/pandas-dev/pandas/issues/27398, GH#22793
|
| 57 |
+
a = pd.array([0, 1, -1, None], dtype="Int64")
|
| 58 |
+
result = a / zero
|
| 59 |
+
expected = FloatingArray(
|
| 60 |
+
np.array([np.nan, np.inf, -np.inf, 1], dtype="float64"),
|
| 61 |
+
np.array([False, False, False, True]),
|
| 62 |
+
)
|
| 63 |
+
if negative:
|
| 64 |
+
expected *= -1
|
| 65 |
+
tm.assert_extension_array_equal(result, expected)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def test_floordiv(dtype):
|
| 69 |
+
a = pd.array([1, 2, 3, None, 5], dtype=dtype)
|
| 70 |
+
b = pd.array([0, 1, None, 3, 4], dtype=dtype)
|
| 71 |
+
|
| 72 |
+
result = a // b
|
| 73 |
+
# Series op sets 1//0 to np.inf, which IntegerArray does not do (yet)
|
| 74 |
+
expected = pd.array([0, 2, None, None, 1], dtype=dtype)
|
| 75 |
+
tm.assert_extension_array_equal(result, expected)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def test_floordiv_by_int_zero_no_mask(any_int_ea_dtype):
|
| 79 |
+
# GH 48223: Aligns with non-masked floordiv
|
| 80 |
+
# but differs from numpy
|
| 81 |
+
# https://github.com/pandas-dev/pandas/issues/30188#issuecomment-564452740
|
| 82 |
+
ser = pd.Series([0, 1], dtype=any_int_ea_dtype)
|
| 83 |
+
result = 1 // ser
|
| 84 |
+
expected = pd.Series([np.inf, 1.0], dtype="Float64")
|
| 85 |
+
tm.assert_series_equal(result, expected)
|
| 86 |
+
|
| 87 |
+
ser_non_nullable = ser.astype(ser.dtype.numpy_dtype)
|
| 88 |
+
result = 1 // ser_non_nullable
|
| 89 |
+
expected = expected.astype(np.float64)
|
| 90 |
+
tm.assert_series_equal(result, expected)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def test_mod(dtype):
|
| 94 |
+
a = pd.array([1, 2, 3, None, 5], dtype=dtype)
|
| 95 |
+
b = pd.array([0, 1, None, 3, 4], dtype=dtype)
|
| 96 |
+
|
| 97 |
+
result = a % b
|
| 98 |
+
expected = pd.array([0, 0, None, None, 1], dtype=dtype)
|
| 99 |
+
tm.assert_extension_array_equal(result, expected)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def test_pow_scalar():
|
| 103 |
+
a = pd.array([-1, 0, 1, None, 2], dtype="Int64")
|
| 104 |
+
result = a**0
|
| 105 |
+
expected = pd.array([1, 1, 1, 1, 1], dtype="Int64")
|
| 106 |
+
tm.assert_extension_array_equal(result, expected)
|
| 107 |
+
|
| 108 |
+
result = a**1
|
| 109 |
+
expected = pd.array([-1, 0, 1, None, 2], dtype="Int64")
|
| 110 |
+
tm.assert_extension_array_equal(result, expected)
|
| 111 |
+
|
| 112 |
+
result = a**pd.NA
|
| 113 |
+
expected = pd.array([None, None, 1, None, None], dtype="Int64")
|
| 114 |
+
tm.assert_extension_array_equal(result, expected)
|
| 115 |
+
|
| 116 |
+
result = a**np.nan
|
| 117 |
+
expected = FloatingArray(
|
| 118 |
+
np.array([np.nan, np.nan, 1, np.nan, np.nan], dtype="float64"),
|
| 119 |
+
np.array([False, False, False, True, False]),
|
| 120 |
+
)
|
| 121 |
+
tm.assert_extension_array_equal(result, expected)
|
| 122 |
+
|
| 123 |
+
# reversed
|
| 124 |
+
a = a[1:] # Can't raise integers to negative powers.
|
| 125 |
+
|
| 126 |
+
result = 0**a
|
| 127 |
+
expected = pd.array([1, 0, None, 0], dtype="Int64")
|
| 128 |
+
tm.assert_extension_array_equal(result, expected)
|
| 129 |
+
|
| 130 |
+
result = 1**a
|
| 131 |
+
expected = pd.array([1, 1, 1, 1], dtype="Int64")
|
| 132 |
+
tm.assert_extension_array_equal(result, expected)
|
| 133 |
+
|
| 134 |
+
result = pd.NA**a
|
| 135 |
+
expected = pd.array([1, None, None, None], dtype="Int64")
|
| 136 |
+
tm.assert_extension_array_equal(result, expected)
|
| 137 |
+
|
| 138 |
+
result = np.nan**a
|
| 139 |
+
expected = FloatingArray(
|
| 140 |
+
np.array([1, np.nan, np.nan, np.nan], dtype="float64"),
|
| 141 |
+
np.array([False, False, True, False]),
|
| 142 |
+
)
|
| 143 |
+
tm.assert_extension_array_equal(result, expected)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def test_pow_array():
|
| 147 |
+
a = pd.array([0, 0, 0, 1, 1, 1, None, None, None])
|
| 148 |
+
b = pd.array([0, 1, None, 0, 1, None, 0, 1, None])
|
| 149 |
+
result = a**b
|
| 150 |
+
expected = pd.array([1, 0, None, 1, 1, 1, 1, None, None])
|
| 151 |
+
tm.assert_extension_array_equal(result, expected)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def test_rpow_one_to_na():
|
| 155 |
+
# https://github.com/pandas-dev/pandas/issues/22022
|
| 156 |
+
# https://github.com/pandas-dev/pandas/issues/29997
|
| 157 |
+
arr = pd.array([np.nan, np.nan], dtype="Int64")
|
| 158 |
+
result = np.array([1.0, 2.0]) ** arr
|
| 159 |
+
expected = pd.array([1.0, np.nan], dtype="Float64")
|
| 160 |
+
tm.assert_extension_array_equal(result, expected)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
@pytest.mark.parametrize("other", [0, 0.5])
|
| 164 |
+
def test_numpy_zero_dim_ndarray(other):
|
| 165 |
+
arr = pd.array([1, None, 2])
|
| 166 |
+
result = arr + np.array(other)
|
| 167 |
+
expected = arr + other
|
| 168 |
+
tm.assert_equal(result, expected)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
# Test generic characteristics / errors
|
| 172 |
+
# -----------------------------------------------------------------------------
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def test_error_invalid_values(data, all_arithmetic_operators):
|
| 176 |
+
op = all_arithmetic_operators
|
| 177 |
+
s = pd.Series(data)
|
| 178 |
+
ops = getattr(s, op)
|
| 179 |
+
|
| 180 |
+
# invalid scalars
|
| 181 |
+
with tm.external_error_raised(TypeError):
|
| 182 |
+
ops("foo")
|
| 183 |
+
with tm.external_error_raised(TypeError):
|
| 184 |
+
ops(pd.Timestamp("20180101"))
|
| 185 |
+
|
| 186 |
+
# invalid array-likes
|
| 187 |
+
str_ser = pd.Series("foo", index=s.index)
|
| 188 |
+
# with pytest.raises(TypeError, match=msg):
|
| 189 |
+
if all_arithmetic_operators in [
|
| 190 |
+
"__mul__",
|
| 191 |
+
"__rmul__",
|
| 192 |
+
]: # (data[~data.isna()] >= 0).all():
|
| 193 |
+
res = ops(str_ser)
|
| 194 |
+
expected = pd.Series(["foo" * x for x in data], index=s.index)
|
| 195 |
+
expected = expected.fillna(np.nan)
|
| 196 |
+
# TODO: doing this fillna to keep tests passing as we make
|
| 197 |
+
# assert_almost_equal stricter, but the expected with pd.NA seems
|
| 198 |
+
# more-correct than np.nan here.
|
| 199 |
+
tm.assert_series_equal(res, expected)
|
| 200 |
+
else:
|
| 201 |
+
with tm.external_error_raised(TypeError):
|
| 202 |
+
ops(str_ser)
|
| 203 |
+
|
| 204 |
+
with tm.external_error_raised(TypeError):
|
| 205 |
+
ops(pd.Series(pd.date_range("20180101", periods=len(s))))
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
# Various
|
| 209 |
+
# -----------------------------------------------------------------------------
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
# TODO test unsigned overflow
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def test_arith_coerce_scalar(data, all_arithmetic_operators):
|
| 216 |
+
op = tm.get_op_from_name(all_arithmetic_operators)
|
| 217 |
+
s = pd.Series(data)
|
| 218 |
+
other = 0.01
|
| 219 |
+
|
| 220 |
+
result = op(s, other)
|
| 221 |
+
expected = op(s.astype(float), other)
|
| 222 |
+
expected = expected.astype("Float64")
|
| 223 |
+
|
| 224 |
+
# rmod results in NaN that wasn't NA in original nullable Series -> unmask it
|
| 225 |
+
if all_arithmetic_operators == "__rmod__":
|
| 226 |
+
mask = (s == 0).fillna(False).to_numpy(bool)
|
| 227 |
+
expected.array._mask[mask] = False
|
| 228 |
+
|
| 229 |
+
tm.assert_series_equal(result, expected)
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
@pytest.mark.parametrize("other", [1.0, np.array(1.0)])
|
| 233 |
+
def test_arithmetic_conversion(all_arithmetic_operators, other):
|
| 234 |
+
# if we have a float operand we should have a float result
|
| 235 |
+
# if that is equal to an integer
|
| 236 |
+
op = tm.get_op_from_name(all_arithmetic_operators)
|
| 237 |
+
|
| 238 |
+
s = pd.Series([1, 2, 3], dtype="Int64")
|
| 239 |
+
result = op(s, other)
|
| 240 |
+
assert result.dtype == "Float64"
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def test_cross_type_arithmetic():
|
| 244 |
+
df = pd.DataFrame(
|
| 245 |
+
{
|
| 246 |
+
"A": pd.Series([1, 2, np.nan], dtype="Int64"),
|
| 247 |
+
"B": pd.Series([1, np.nan, 3], dtype="UInt8"),
|
| 248 |
+
"C": [1, 2, 3],
|
| 249 |
+
}
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
result = df.A + df.C
|
| 253 |
+
expected = pd.Series([2, 4, np.nan], dtype="Int64")
|
| 254 |
+
tm.assert_series_equal(result, expected)
|
| 255 |
+
|
| 256 |
+
result = (df.A + df.C) * 3 == 12
|
| 257 |
+
expected = pd.Series([False, True, None], dtype="boolean")
|
| 258 |
+
tm.assert_series_equal(result, expected)
|
| 259 |
+
|
| 260 |
+
result = df.A + df.B
|
| 261 |
+
expected = pd.Series([2, np.nan, np.nan], dtype="Int64")
|
| 262 |
+
tm.assert_series_equal(result, expected)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
@pytest.mark.parametrize("op", ["mean"])
|
| 266 |
+
def test_reduce_to_float(op):
|
| 267 |
+
# some reduce ops always return float, even if the result
|
| 268 |
+
# is a rounded number
|
| 269 |
+
df = pd.DataFrame(
|
| 270 |
+
{
|
| 271 |
+
"A": ["a", "b", "b"],
|
| 272 |
+
"B": [1, None, 3],
|
| 273 |
+
"C": pd.array([1, None, 3], dtype="Int64"),
|
| 274 |
+
}
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
# op
|
| 278 |
+
result = getattr(df.C, op)()
|
| 279 |
+
assert isinstance(result, float)
|
| 280 |
+
|
| 281 |
+
# groupby
|
| 282 |
+
result = getattr(df.groupby("A"), op)()
|
| 283 |
+
|
| 284 |
+
expected = pd.DataFrame(
|
| 285 |
+
{"B": np.array([1.0, 3.0]), "C": pd.array([1, 3], dtype="Float64")},
|
| 286 |
+
index=pd.Index(["a", "b"], name="A"),
|
| 287 |
+
)
|
| 288 |
+
tm.assert_frame_equal(result, expected)
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
@pytest.mark.parametrize(
|
| 292 |
+
"source, neg_target, abs_target",
|
| 293 |
+
[
|
| 294 |
+
([1, 2, 3], [-1, -2, -3], [1, 2, 3]),
|
| 295 |
+
([1, 2, None], [-1, -2, None], [1, 2, None]),
|
| 296 |
+
([-1, 0, 1], [1, 0, -1], [1, 0, 1]),
|
| 297 |
+
],
|
| 298 |
+
)
|
| 299 |
+
def test_unary_int_operators(any_signed_int_ea_dtype, source, neg_target, abs_target):
|
| 300 |
+
dtype = any_signed_int_ea_dtype
|
| 301 |
+
arr = pd.array(source, dtype=dtype)
|
| 302 |
+
neg_result, pos_result, abs_result = -arr, +arr, abs(arr)
|
| 303 |
+
neg_target = pd.array(neg_target, dtype=dtype)
|
| 304 |
+
abs_target = pd.array(abs_target, dtype=dtype)
|
| 305 |
+
|
| 306 |
+
tm.assert_extension_array_equal(neg_result, neg_target)
|
| 307 |
+
tm.assert_extension_array_equal(pos_result, arr)
|
| 308 |
+
assert not tm.shares_memory(pos_result, arr)
|
| 309 |
+
tm.assert_extension_array_equal(abs_result, abs_target)
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def test_values_multiplying_large_series_by_NA():
|
| 313 |
+
# GH#33701
|
| 314 |
+
|
| 315 |
+
result = pd.NA * pd.Series(np.zeros(10001))
|
| 316 |
+
expected = pd.Series([pd.NA] * 10001)
|
| 317 |
+
|
| 318 |
+
tm.assert_series_equal(result, expected)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def test_bitwise(dtype):
|
| 322 |
+
left = pd.array([1, None, 3, 4], dtype=dtype)
|
| 323 |
+
right = pd.array([None, 3, 5, 4], dtype=dtype)
|
| 324 |
+
|
| 325 |
+
result = left | right
|
| 326 |
+
expected = pd.array([None, None, 3 | 5, 4 | 4], dtype=dtype)
|
| 327 |
+
tm.assert_extension_array_equal(result, expected)
|
| 328 |
+
|
| 329 |
+
result = left & right
|
| 330 |
+
expected = pd.array([None, None, 3 & 5, 4 & 4], dtype=dtype)
|
| 331 |
+
tm.assert_extension_array_equal(result, expected)
|
| 332 |
+
|
| 333 |
+
result = left ^ right
|
| 334 |
+
expected = pd.array([None, None, 3 ^ 5, 4 ^ 4], dtype=dtype)
|
| 335 |
+
tm.assert_extension_array_equal(result, expected)
|
| 336 |
+
|
| 337 |
+
# TODO: desired behavior when operating with boolean? defer?
|
| 338 |
+
|
| 339 |
+
floats = right.astype("Float64")
|
| 340 |
+
with pytest.raises(TypeError, match="unsupported operand type"):
|
| 341 |
+
left | floats
|
| 342 |
+
with pytest.raises(TypeError, match="unsupported operand type"):
|
| 343 |
+
left & floats
|
| 344 |
+
with pytest.raises(TypeError, match="unsupported operand type"):
|
| 345 |
+
left ^ floats
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/integer/test_comparison.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import pandas._testing as tm
|
| 5 |
+
from pandas.tests.arrays.masked_shared import (
|
| 6 |
+
ComparisonOps,
|
| 7 |
+
NumericOps,
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class TestComparisonOps(NumericOps, ComparisonOps):
|
| 12 |
+
@pytest.mark.parametrize("other", [True, False, pd.NA, -1, 0, 1])
|
| 13 |
+
def test_scalar(self, other, comparison_op, dtype):
|
| 14 |
+
ComparisonOps.test_scalar(self, other, comparison_op, dtype)
|
| 15 |
+
|
| 16 |
+
def test_compare_to_int(self, dtype, comparison_op):
|
| 17 |
+
# GH 28930
|
| 18 |
+
op_name = f"__{comparison_op.__name__}__"
|
| 19 |
+
s1 = pd.Series([1, None, 3], dtype=dtype)
|
| 20 |
+
s2 = pd.Series([1, None, 3], dtype="float")
|
| 21 |
+
|
| 22 |
+
method = getattr(s1, op_name)
|
| 23 |
+
result = method(2)
|
| 24 |
+
|
| 25 |
+
method = getattr(s2, op_name)
|
| 26 |
+
expected = method(2).astype("boolean")
|
| 27 |
+
expected[s2.isna()] = pd.NA
|
| 28 |
+
|
| 29 |
+
tm.assert_series_equal(result, expected)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def test_equals():
|
| 33 |
+
# GH-30652
|
| 34 |
+
# equals is generally tested in /tests/extension/base/methods, but this
|
| 35 |
+
# specifically tests that two arrays of the same class but different dtype
|
| 36 |
+
# do not evaluate equal
|
| 37 |
+
a1 = pd.array([1, 2, None], dtype="Int64")
|
| 38 |
+
a2 = pd.array([1, 2, None], dtype="Int32")
|
| 39 |
+
assert a1.equals(a2) is False
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/integer/test_concat.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import pandas._testing as tm
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@pytest.mark.parametrize(
|
| 9 |
+
"to_concat_dtypes, result_dtype",
|
| 10 |
+
[
|
| 11 |
+
(["Int64", "Int64"], "Int64"),
|
| 12 |
+
(["UInt64", "UInt64"], "UInt64"),
|
| 13 |
+
(["Int8", "Int8"], "Int8"),
|
| 14 |
+
(["Int8", "Int16"], "Int16"),
|
| 15 |
+
(["UInt8", "Int8"], "Int16"),
|
| 16 |
+
(["Int32", "UInt32"], "Int64"),
|
| 17 |
+
(["Int64", "UInt64"], "Float64"),
|
| 18 |
+
(["Int64", "boolean"], "object"),
|
| 19 |
+
(["UInt8", "boolean"], "object"),
|
| 20 |
+
],
|
| 21 |
+
)
|
| 22 |
+
def test_concat_series(to_concat_dtypes, result_dtype):
|
| 23 |
+
# we expect the same dtypes as we would get with non-masked inputs,
|
| 24 |
+
# just masked where available.
|
| 25 |
+
|
| 26 |
+
result = pd.concat([pd.Series([0, 1, pd.NA], dtype=t) for t in to_concat_dtypes])
|
| 27 |
+
expected = pd.concat([pd.Series([0, 1, pd.NA], dtype=object)] * 2).astype(
|
| 28 |
+
result_dtype
|
| 29 |
+
)
|
| 30 |
+
tm.assert_series_equal(result, expected)
|
| 31 |
+
|
| 32 |
+
# order doesn't matter for result
|
| 33 |
+
result = pd.concat(
|
| 34 |
+
[pd.Series([0, 1, pd.NA], dtype=t) for t in to_concat_dtypes[::-1]]
|
| 35 |
+
)
|
| 36 |
+
expected = pd.concat([pd.Series([0, 1, pd.NA], dtype=object)] * 2).astype(
|
| 37 |
+
result_dtype
|
| 38 |
+
)
|
| 39 |
+
tm.assert_series_equal(result, expected)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@pytest.mark.parametrize(
|
| 43 |
+
"to_concat_dtypes, result_dtype",
|
| 44 |
+
[
|
| 45 |
+
(["Int64", "int64"], "Int64"),
|
| 46 |
+
(["UInt64", "uint64"], "UInt64"),
|
| 47 |
+
(["Int8", "int8"], "Int8"),
|
| 48 |
+
(["Int8", "int16"], "Int16"),
|
| 49 |
+
(["UInt8", "int8"], "Int16"),
|
| 50 |
+
(["Int32", "uint32"], "Int64"),
|
| 51 |
+
(["Int64", "uint64"], "Float64"),
|
| 52 |
+
(["Int64", "bool"], "object"),
|
| 53 |
+
(["UInt8", "bool"], "object"),
|
| 54 |
+
],
|
| 55 |
+
)
|
| 56 |
+
def test_concat_series_with_numpy(to_concat_dtypes, result_dtype):
|
| 57 |
+
# we expect the same dtypes as we would get with non-masked inputs,
|
| 58 |
+
# just masked where available.
|
| 59 |
+
|
| 60 |
+
s1 = pd.Series([0, 1, pd.NA], dtype=to_concat_dtypes[0])
|
| 61 |
+
s2 = pd.Series(np.array([0, 1], dtype=to_concat_dtypes[1]))
|
| 62 |
+
result = pd.concat([s1, s2], ignore_index=True)
|
| 63 |
+
expected = pd.Series([0, 1, pd.NA, 0, 1], dtype=object).astype(result_dtype)
|
| 64 |
+
tm.assert_series_equal(result, expected)
|
| 65 |
+
|
| 66 |
+
# order doesn't matter for result
|
| 67 |
+
result = pd.concat([s2, s1], ignore_index=True)
|
| 68 |
+
expected = pd.Series([0, 1, 0, 1, pd.NA], dtype=object).astype(result_dtype)
|
| 69 |
+
tm.assert_series_equal(result, expected)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/integer/test_construction.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import pandas._testing as tm
|
| 6 |
+
from pandas.api.types import is_integer
|
| 7 |
+
from pandas.core.arrays import IntegerArray
|
| 8 |
+
from pandas.core.arrays.integer import (
|
| 9 |
+
Int8Dtype,
|
| 10 |
+
Int32Dtype,
|
| 11 |
+
Int64Dtype,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@pytest.fixture(params=[pd.array, IntegerArray._from_sequence])
|
| 16 |
+
def constructor(request):
|
| 17 |
+
"""Fixture returning parametrized IntegerArray from given sequence.
|
| 18 |
+
|
| 19 |
+
Used to test dtype conversions.
|
| 20 |
+
"""
|
| 21 |
+
return request.param
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def test_uses_pandas_na():
|
| 25 |
+
a = pd.array([1, None], dtype=Int64Dtype())
|
| 26 |
+
assert a[1] is pd.NA
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def test_from_dtype_from_float(data):
|
| 30 |
+
# construct from our dtype & string dtype
|
| 31 |
+
dtype = data.dtype
|
| 32 |
+
|
| 33 |
+
# from float
|
| 34 |
+
expected = pd.Series(data)
|
| 35 |
+
result = pd.Series(data.to_numpy(na_value=np.nan, dtype="float"), dtype=str(dtype))
|
| 36 |
+
tm.assert_series_equal(result, expected)
|
| 37 |
+
|
| 38 |
+
# from int / list
|
| 39 |
+
expected = pd.Series(data)
|
| 40 |
+
result = pd.Series(np.array(data).tolist(), dtype=str(dtype))
|
| 41 |
+
tm.assert_series_equal(result, expected)
|
| 42 |
+
|
| 43 |
+
# from int / array
|
| 44 |
+
expected = pd.Series(data).dropna().reset_index(drop=True)
|
| 45 |
+
dropped = np.array(data.dropna()).astype(np.dtype(dtype.type))
|
| 46 |
+
result = pd.Series(dropped, dtype=str(dtype))
|
| 47 |
+
tm.assert_series_equal(result, expected)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def test_conversions(data_missing):
|
| 51 |
+
# astype to object series
|
| 52 |
+
df = pd.DataFrame({"A": data_missing})
|
| 53 |
+
result = df["A"].astype("object")
|
| 54 |
+
expected = pd.Series(np.array([pd.NA, 1], dtype=object), name="A")
|
| 55 |
+
tm.assert_series_equal(result, expected)
|
| 56 |
+
|
| 57 |
+
# convert to object ndarray
|
| 58 |
+
# we assert that we are exactly equal
|
| 59 |
+
# including type conversions of scalars
|
| 60 |
+
result = df["A"].astype("object").values
|
| 61 |
+
expected = np.array([pd.NA, 1], dtype=object)
|
| 62 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 63 |
+
|
| 64 |
+
for r, e in zip(result, expected):
|
| 65 |
+
if pd.isnull(r):
|
| 66 |
+
assert pd.isnull(e)
|
| 67 |
+
elif is_integer(r):
|
| 68 |
+
assert r == e
|
| 69 |
+
assert is_integer(e)
|
| 70 |
+
else:
|
| 71 |
+
assert r == e
|
| 72 |
+
assert type(r) == type(e)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_integer_array_constructor():
|
| 76 |
+
values = np.array([1, 2, 3, 4], dtype="int64")
|
| 77 |
+
mask = np.array([False, False, False, True], dtype="bool")
|
| 78 |
+
|
| 79 |
+
result = IntegerArray(values, mask)
|
| 80 |
+
expected = pd.array([1, 2, 3, np.nan], dtype="Int64")
|
| 81 |
+
tm.assert_extension_array_equal(result, expected)
|
| 82 |
+
|
| 83 |
+
msg = r".* should be .* numpy array. Use the 'pd.array' function instead"
|
| 84 |
+
with pytest.raises(TypeError, match=msg):
|
| 85 |
+
IntegerArray(values.tolist(), mask)
|
| 86 |
+
|
| 87 |
+
with pytest.raises(TypeError, match=msg):
|
| 88 |
+
IntegerArray(values, mask.tolist())
|
| 89 |
+
|
| 90 |
+
with pytest.raises(TypeError, match=msg):
|
| 91 |
+
IntegerArray(values.astype(float), mask)
|
| 92 |
+
msg = r"__init__\(\) missing 1 required positional argument: 'mask'"
|
| 93 |
+
with pytest.raises(TypeError, match=msg):
|
| 94 |
+
IntegerArray(values)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def test_integer_array_constructor_copy():
|
| 98 |
+
values = np.array([1, 2, 3, 4], dtype="int64")
|
| 99 |
+
mask = np.array([False, False, False, True], dtype="bool")
|
| 100 |
+
|
| 101 |
+
result = IntegerArray(values, mask)
|
| 102 |
+
assert result._data is values
|
| 103 |
+
assert result._mask is mask
|
| 104 |
+
|
| 105 |
+
result = IntegerArray(values, mask, copy=True)
|
| 106 |
+
assert result._data is not values
|
| 107 |
+
assert result._mask is not mask
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@pytest.mark.parametrize(
|
| 111 |
+
"a, b",
|
| 112 |
+
[
|
| 113 |
+
([1, None], [1, np.nan]),
|
| 114 |
+
([None], [np.nan]),
|
| 115 |
+
([None, np.nan], [np.nan, np.nan]),
|
| 116 |
+
([np.nan, np.nan], [np.nan, np.nan]),
|
| 117 |
+
],
|
| 118 |
+
)
|
| 119 |
+
def test_to_integer_array_none_is_nan(a, b):
|
| 120 |
+
result = pd.array(a, dtype="Int64")
|
| 121 |
+
expected = pd.array(b, dtype="Int64")
|
| 122 |
+
tm.assert_extension_array_equal(result, expected)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
@pytest.mark.parametrize(
|
| 126 |
+
"values",
|
| 127 |
+
[
|
| 128 |
+
["foo", "bar"],
|
| 129 |
+
"foo",
|
| 130 |
+
1,
|
| 131 |
+
1.0,
|
| 132 |
+
pd.date_range("20130101", periods=2),
|
| 133 |
+
np.array(["foo"]),
|
| 134 |
+
[[1, 2], [3, 4]],
|
| 135 |
+
[np.nan, {"a": 1}],
|
| 136 |
+
],
|
| 137 |
+
)
|
| 138 |
+
def test_to_integer_array_error(values):
|
| 139 |
+
# error in converting existing arrays to IntegerArrays
|
| 140 |
+
msg = "|".join(
|
| 141 |
+
[
|
| 142 |
+
r"cannot be converted to IntegerDtype",
|
| 143 |
+
r"invalid literal for int\(\) with base 10:",
|
| 144 |
+
r"values must be a 1D list-like",
|
| 145 |
+
r"Cannot pass scalar",
|
| 146 |
+
r"int\(\) argument must be a string",
|
| 147 |
+
]
|
| 148 |
+
)
|
| 149 |
+
with pytest.raises((ValueError, TypeError), match=msg):
|
| 150 |
+
pd.array(values, dtype="Int64")
|
| 151 |
+
|
| 152 |
+
with pytest.raises((ValueError, TypeError), match=msg):
|
| 153 |
+
IntegerArray._from_sequence(values)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def test_to_integer_array_inferred_dtype(constructor):
|
| 157 |
+
# if values has dtype -> respect it
|
| 158 |
+
result = constructor(np.array([1, 2], dtype="int8"))
|
| 159 |
+
assert result.dtype == Int8Dtype()
|
| 160 |
+
result = constructor(np.array([1, 2], dtype="int32"))
|
| 161 |
+
assert result.dtype == Int32Dtype()
|
| 162 |
+
|
| 163 |
+
# if values have no dtype -> always int64
|
| 164 |
+
result = constructor([1, 2])
|
| 165 |
+
assert result.dtype == Int64Dtype()
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def test_to_integer_array_dtype_keyword(constructor):
|
| 169 |
+
result = constructor([1, 2], dtype="Int8")
|
| 170 |
+
assert result.dtype == Int8Dtype()
|
| 171 |
+
|
| 172 |
+
# if values has dtype -> override it
|
| 173 |
+
result = constructor(np.array([1, 2], dtype="int8"), dtype="Int32")
|
| 174 |
+
assert result.dtype == Int32Dtype()
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def test_to_integer_array_float():
|
| 178 |
+
result = IntegerArray._from_sequence([1.0, 2.0], dtype="Int64")
|
| 179 |
+
expected = pd.array([1, 2], dtype="Int64")
|
| 180 |
+
tm.assert_extension_array_equal(result, expected)
|
| 181 |
+
|
| 182 |
+
with pytest.raises(TypeError, match="cannot safely cast non-equivalent"):
|
| 183 |
+
IntegerArray._from_sequence([1.5, 2.0], dtype="Int64")
|
| 184 |
+
|
| 185 |
+
# for float dtypes, the itemsize is not preserved
|
| 186 |
+
result = IntegerArray._from_sequence(
|
| 187 |
+
np.array([1.0, 2.0], dtype="float32"), dtype="Int64"
|
| 188 |
+
)
|
| 189 |
+
assert result.dtype == Int64Dtype()
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def test_to_integer_array_str():
|
| 193 |
+
result = IntegerArray._from_sequence(["1", "2", None], dtype="Int64")
|
| 194 |
+
expected = pd.array([1, 2, np.nan], dtype="Int64")
|
| 195 |
+
tm.assert_extension_array_equal(result, expected)
|
| 196 |
+
|
| 197 |
+
with pytest.raises(
|
| 198 |
+
ValueError, match=r"invalid literal for int\(\) with base 10: .*"
|
| 199 |
+
):
|
| 200 |
+
IntegerArray._from_sequence(["1", "2", ""], dtype="Int64")
|
| 201 |
+
|
| 202 |
+
with pytest.raises(
|
| 203 |
+
ValueError, match=r"invalid literal for int\(\) with base 10: .*"
|
| 204 |
+
):
|
| 205 |
+
IntegerArray._from_sequence(["1.5", "2.0"], dtype="Int64")
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
@pytest.mark.parametrize(
|
| 209 |
+
"bool_values, int_values, target_dtype, expected_dtype",
|
| 210 |
+
[
|
| 211 |
+
([False, True], [0, 1], Int64Dtype(), Int64Dtype()),
|
| 212 |
+
([False, True], [0, 1], "Int64", Int64Dtype()),
|
| 213 |
+
([False, True, np.nan], [0, 1, np.nan], Int64Dtype(), Int64Dtype()),
|
| 214 |
+
],
|
| 215 |
+
)
|
| 216 |
+
def test_to_integer_array_bool(
|
| 217 |
+
constructor, bool_values, int_values, target_dtype, expected_dtype
|
| 218 |
+
):
|
| 219 |
+
result = constructor(bool_values, dtype=target_dtype)
|
| 220 |
+
assert result.dtype == expected_dtype
|
| 221 |
+
expected = pd.array(int_values, dtype=target_dtype)
|
| 222 |
+
tm.assert_extension_array_equal(result, expected)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
@pytest.mark.parametrize(
|
| 226 |
+
"values, to_dtype, result_dtype",
|
| 227 |
+
[
|
| 228 |
+
(np.array([1], dtype="int64"), None, Int64Dtype),
|
| 229 |
+
(np.array([1, np.nan]), None, Int64Dtype),
|
| 230 |
+
(np.array([1, np.nan]), "int8", Int8Dtype),
|
| 231 |
+
],
|
| 232 |
+
)
|
| 233 |
+
def test_to_integer_array(values, to_dtype, result_dtype):
|
| 234 |
+
# convert existing arrays to IntegerArrays
|
| 235 |
+
result = IntegerArray._from_sequence(values, dtype=to_dtype)
|
| 236 |
+
assert result.dtype == result_dtype()
|
| 237 |
+
expected = pd.array(values, dtype=result_dtype())
|
| 238 |
+
tm.assert_extension_array_equal(result, expected)
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def test_integer_array_from_boolean():
|
| 242 |
+
# GH31104
|
| 243 |
+
expected = pd.array(np.array([True, False]), dtype="Int64")
|
| 244 |
+
result = pd.array(np.array([True, False], dtype=object), dtype="Int64")
|
| 245 |
+
tm.assert_extension_array_equal(result, expected)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/integer/test_dtypes.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from pandas.core.dtypes.generic import ABCIndex
|
| 5 |
+
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import pandas._testing as tm
|
| 8 |
+
from pandas.core.arrays.integer import (
|
| 9 |
+
Int8Dtype,
|
| 10 |
+
UInt32Dtype,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def test_dtypes(dtype):
|
| 15 |
+
# smoke tests on auto dtype construction
|
| 16 |
+
|
| 17 |
+
if dtype.is_signed_integer:
|
| 18 |
+
assert np.dtype(dtype.type).kind == "i"
|
| 19 |
+
else:
|
| 20 |
+
assert np.dtype(dtype.type).kind == "u"
|
| 21 |
+
assert dtype.name is not None
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@pytest.mark.parametrize("op", ["sum", "min", "max", "prod"])
|
| 25 |
+
def test_preserve_dtypes(op):
|
| 26 |
+
# for ops that enable (mean would actually work here
|
| 27 |
+
# but generally it is a float return value)
|
| 28 |
+
df = pd.DataFrame(
|
| 29 |
+
{
|
| 30 |
+
"A": ["a", "b", "b"],
|
| 31 |
+
"B": [1, None, 3],
|
| 32 |
+
"C": pd.array([1, None, 3], dtype="Int64"),
|
| 33 |
+
}
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
# op
|
| 37 |
+
result = getattr(df.C, op)()
|
| 38 |
+
if op in {"sum", "prod", "min", "max"}:
|
| 39 |
+
assert isinstance(result, np.int64)
|
| 40 |
+
else:
|
| 41 |
+
assert isinstance(result, int)
|
| 42 |
+
|
| 43 |
+
# groupby
|
| 44 |
+
result = getattr(df.groupby("A"), op)()
|
| 45 |
+
|
| 46 |
+
expected = pd.DataFrame(
|
| 47 |
+
{"B": np.array([1.0, 3.0]), "C": pd.array([1, 3], dtype="Int64")},
|
| 48 |
+
index=pd.Index(["a", "b"], name="A"),
|
| 49 |
+
)
|
| 50 |
+
tm.assert_frame_equal(result, expected)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def test_astype_nansafe():
|
| 54 |
+
# see gh-22343
|
| 55 |
+
arr = pd.array([np.nan, 1, 2], dtype="Int8")
|
| 56 |
+
msg = "cannot convert NA to integer"
|
| 57 |
+
|
| 58 |
+
with pytest.raises(ValueError, match=msg):
|
| 59 |
+
arr.astype("uint32")
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@pytest.mark.parametrize("dropna", [True, False])
|
| 63 |
+
def test_construct_index(all_data, dropna):
|
| 64 |
+
# ensure that we do not coerce to different Index dtype or non-index
|
| 65 |
+
|
| 66 |
+
all_data = all_data[:10]
|
| 67 |
+
if dropna:
|
| 68 |
+
other = np.array(all_data[~all_data.isna()])
|
| 69 |
+
else:
|
| 70 |
+
other = all_data
|
| 71 |
+
|
| 72 |
+
result = pd.Index(pd.array(other, dtype=all_data.dtype))
|
| 73 |
+
expected = pd.Index(other, dtype=all_data.dtype)
|
| 74 |
+
assert all_data.dtype == expected.dtype # dont coerce to object
|
| 75 |
+
|
| 76 |
+
tm.assert_index_equal(result, expected)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
@pytest.mark.parametrize("dropna", [True, False])
|
| 80 |
+
def test_astype_index(all_data, dropna):
|
| 81 |
+
# as an int/uint index to Index
|
| 82 |
+
|
| 83 |
+
all_data = all_data[:10]
|
| 84 |
+
if dropna:
|
| 85 |
+
other = all_data[~all_data.isna()]
|
| 86 |
+
else:
|
| 87 |
+
other = all_data
|
| 88 |
+
|
| 89 |
+
dtype = all_data.dtype
|
| 90 |
+
idx = pd.Index(np.array(other))
|
| 91 |
+
assert isinstance(idx, ABCIndex)
|
| 92 |
+
|
| 93 |
+
result = idx.astype(dtype)
|
| 94 |
+
expected = idx.astype(object).astype(dtype)
|
| 95 |
+
tm.assert_index_equal(result, expected)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def test_astype(all_data):
|
| 99 |
+
all_data = all_data[:10]
|
| 100 |
+
|
| 101 |
+
ints = all_data[~all_data.isna()]
|
| 102 |
+
mixed = all_data
|
| 103 |
+
dtype = Int8Dtype()
|
| 104 |
+
|
| 105 |
+
# coerce to same type - ints
|
| 106 |
+
s = pd.Series(ints)
|
| 107 |
+
result = s.astype(all_data.dtype)
|
| 108 |
+
expected = pd.Series(ints)
|
| 109 |
+
tm.assert_series_equal(result, expected)
|
| 110 |
+
|
| 111 |
+
# coerce to same other - ints
|
| 112 |
+
s = pd.Series(ints)
|
| 113 |
+
result = s.astype(dtype)
|
| 114 |
+
expected = pd.Series(ints, dtype=dtype)
|
| 115 |
+
tm.assert_series_equal(result, expected)
|
| 116 |
+
|
| 117 |
+
# coerce to same numpy_dtype - ints
|
| 118 |
+
s = pd.Series(ints)
|
| 119 |
+
result = s.astype(all_data.dtype.numpy_dtype)
|
| 120 |
+
expected = pd.Series(ints._data.astype(all_data.dtype.numpy_dtype))
|
| 121 |
+
tm.assert_series_equal(result, expected)
|
| 122 |
+
|
| 123 |
+
# coerce to same type - mixed
|
| 124 |
+
s = pd.Series(mixed)
|
| 125 |
+
result = s.astype(all_data.dtype)
|
| 126 |
+
expected = pd.Series(mixed)
|
| 127 |
+
tm.assert_series_equal(result, expected)
|
| 128 |
+
|
| 129 |
+
# coerce to same other - mixed
|
| 130 |
+
s = pd.Series(mixed)
|
| 131 |
+
result = s.astype(dtype)
|
| 132 |
+
expected = pd.Series(mixed, dtype=dtype)
|
| 133 |
+
tm.assert_series_equal(result, expected)
|
| 134 |
+
|
| 135 |
+
# coerce to same numpy_dtype - mixed
|
| 136 |
+
s = pd.Series(mixed)
|
| 137 |
+
msg = "cannot convert NA to integer"
|
| 138 |
+
with pytest.raises(ValueError, match=msg):
|
| 139 |
+
s.astype(all_data.dtype.numpy_dtype)
|
| 140 |
+
|
| 141 |
+
# coerce to object
|
| 142 |
+
s = pd.Series(mixed)
|
| 143 |
+
result = s.astype("object")
|
| 144 |
+
expected = pd.Series(np.asarray(mixed, dtype=object))
|
| 145 |
+
tm.assert_series_equal(result, expected)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def test_astype_copy():
|
| 149 |
+
arr = pd.array([1, 2, 3, None], dtype="Int64")
|
| 150 |
+
orig = pd.array([1, 2, 3, None], dtype="Int64")
|
| 151 |
+
|
| 152 |
+
# copy=True -> ensure both data and mask are actual copies
|
| 153 |
+
result = arr.astype("Int64", copy=True)
|
| 154 |
+
assert result is not arr
|
| 155 |
+
assert not tm.shares_memory(result, arr)
|
| 156 |
+
result[0] = 10
|
| 157 |
+
tm.assert_extension_array_equal(arr, orig)
|
| 158 |
+
result[0] = pd.NA
|
| 159 |
+
tm.assert_extension_array_equal(arr, orig)
|
| 160 |
+
|
| 161 |
+
# copy=False
|
| 162 |
+
result = arr.astype("Int64", copy=False)
|
| 163 |
+
assert result is arr
|
| 164 |
+
assert np.shares_memory(result._data, arr._data)
|
| 165 |
+
assert np.shares_memory(result._mask, arr._mask)
|
| 166 |
+
result[0] = 10
|
| 167 |
+
assert arr[0] == 10
|
| 168 |
+
result[0] = pd.NA
|
| 169 |
+
assert arr[0] is pd.NA
|
| 170 |
+
|
| 171 |
+
# astype to different dtype -> always needs a copy -> even with copy=False
|
| 172 |
+
# we need to ensure that also the mask is actually copied
|
| 173 |
+
arr = pd.array([1, 2, 3, None], dtype="Int64")
|
| 174 |
+
orig = pd.array([1, 2, 3, None], dtype="Int64")
|
| 175 |
+
|
| 176 |
+
result = arr.astype("Int32", copy=False)
|
| 177 |
+
assert not tm.shares_memory(result, arr)
|
| 178 |
+
result[0] = 10
|
| 179 |
+
tm.assert_extension_array_equal(arr, orig)
|
| 180 |
+
result[0] = pd.NA
|
| 181 |
+
tm.assert_extension_array_equal(arr, orig)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def test_astype_to_larger_numpy():
|
| 185 |
+
a = pd.array([1, 2], dtype="Int32")
|
| 186 |
+
result = a.astype("int64")
|
| 187 |
+
expected = np.array([1, 2], dtype="int64")
|
| 188 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 189 |
+
|
| 190 |
+
a = pd.array([1, 2], dtype="UInt32")
|
| 191 |
+
result = a.astype("uint64")
|
| 192 |
+
expected = np.array([1, 2], dtype="uint64")
|
| 193 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
@pytest.mark.parametrize("dtype", [Int8Dtype(), "Int8", UInt32Dtype(), "UInt32"])
|
| 197 |
+
def test_astype_specific_casting(dtype):
|
| 198 |
+
s = pd.Series([1, 2, 3], dtype="Int64")
|
| 199 |
+
result = s.astype(dtype)
|
| 200 |
+
expected = pd.Series([1, 2, 3], dtype=dtype)
|
| 201 |
+
tm.assert_series_equal(result, expected)
|
| 202 |
+
|
| 203 |
+
s = pd.Series([1, 2, 3, None], dtype="Int64")
|
| 204 |
+
result = s.astype(dtype)
|
| 205 |
+
expected = pd.Series([1, 2, 3, None], dtype=dtype)
|
| 206 |
+
tm.assert_series_equal(result, expected)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def test_astype_floating():
|
| 210 |
+
arr = pd.array([1, 2, None], dtype="Int64")
|
| 211 |
+
result = arr.astype("Float64")
|
| 212 |
+
expected = pd.array([1.0, 2.0, None], dtype="Float64")
|
| 213 |
+
tm.assert_extension_array_equal(result, expected)
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def test_astype_dt64():
|
| 217 |
+
# GH#32435
|
| 218 |
+
arr = pd.array([1, 2, 3, pd.NA]) * 10**9
|
| 219 |
+
|
| 220 |
+
result = arr.astype("datetime64[ns]")
|
| 221 |
+
|
| 222 |
+
expected = np.array([1, 2, 3, "NaT"], dtype="M8[s]").astype("M8[ns]")
|
| 223 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def test_construct_cast_invalid(dtype):
|
| 227 |
+
msg = "cannot safely"
|
| 228 |
+
arr = [1.2, 2.3, 3.7]
|
| 229 |
+
with pytest.raises(TypeError, match=msg):
|
| 230 |
+
pd.array(arr, dtype=dtype)
|
| 231 |
+
|
| 232 |
+
with pytest.raises(TypeError, match=msg):
|
| 233 |
+
pd.Series(arr).astype(dtype)
|
| 234 |
+
|
| 235 |
+
arr = [1.2, 2.3, 3.7, np.nan]
|
| 236 |
+
with pytest.raises(TypeError, match=msg):
|
| 237 |
+
pd.array(arr, dtype=dtype)
|
| 238 |
+
|
| 239 |
+
with pytest.raises(TypeError, match=msg):
|
| 240 |
+
pd.Series(arr).astype(dtype)
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
@pytest.mark.parametrize("in_series", [True, False])
|
| 244 |
+
def test_to_numpy_na_nan(in_series):
|
| 245 |
+
a = pd.array([0, 1, None], dtype="Int64")
|
| 246 |
+
if in_series:
|
| 247 |
+
a = pd.Series(a)
|
| 248 |
+
|
| 249 |
+
result = a.to_numpy(dtype="float64", na_value=np.nan)
|
| 250 |
+
expected = np.array([0.0, 1.0, np.nan], dtype="float64")
|
| 251 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 252 |
+
|
| 253 |
+
result = a.to_numpy(dtype="int64", na_value=-1)
|
| 254 |
+
expected = np.array([0, 1, -1], dtype="int64")
|
| 255 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 256 |
+
|
| 257 |
+
result = a.to_numpy(dtype="bool", na_value=False)
|
| 258 |
+
expected = np.array([False, True, False], dtype="bool")
|
| 259 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
@pytest.mark.parametrize("in_series", [True, False])
|
| 263 |
+
@pytest.mark.parametrize("dtype", ["int32", "int64", "bool"])
|
| 264 |
+
def test_to_numpy_dtype(dtype, in_series):
|
| 265 |
+
a = pd.array([0, 1], dtype="Int64")
|
| 266 |
+
if in_series:
|
| 267 |
+
a = pd.Series(a)
|
| 268 |
+
|
| 269 |
+
result = a.to_numpy(dtype=dtype)
|
| 270 |
+
expected = np.array([0, 1], dtype=dtype)
|
| 271 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
@pytest.mark.parametrize("dtype", ["int64", "bool"])
|
| 275 |
+
def test_to_numpy_na_raises(dtype):
|
| 276 |
+
a = pd.array([0, 1, None], dtype="Int64")
|
| 277 |
+
with pytest.raises(ValueError, match=dtype):
|
| 278 |
+
a.to_numpy(dtype=dtype)
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def test_astype_str(using_infer_string):
|
| 282 |
+
a = pd.array([1, 2, None], dtype="Int64")
|
| 283 |
+
|
| 284 |
+
if using_infer_string:
|
| 285 |
+
expected = pd.array(["1", "2", None], dtype=pd.StringDtype(na_value=np.nan))
|
| 286 |
+
|
| 287 |
+
tm.assert_extension_array_equal(a.astype(str), expected)
|
| 288 |
+
tm.assert_extension_array_equal(a.astype("str"), expected)
|
| 289 |
+
else:
|
| 290 |
+
expected = np.array(["1", "2", "<NA>"], dtype=f"{tm.ENDIAN}U21")
|
| 291 |
+
|
| 292 |
+
tm.assert_numpy_array_equal(a.astype(str), expected)
|
| 293 |
+
tm.assert_numpy_array_equal(a.astype("str"), expected)
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def test_astype_boolean():
|
| 297 |
+
# https://github.com/pandas-dev/pandas/issues/31102
|
| 298 |
+
a = pd.array([1, 0, -1, 2, None], dtype="Int64")
|
| 299 |
+
result = a.astype("boolean")
|
| 300 |
+
expected = pd.array([True, False, True, True, None], dtype="boolean")
|
| 301 |
+
tm.assert_extension_array_equal(result, expected)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/integer/test_function.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import pandas._testing as tm
|
| 6 |
+
from pandas.core.arrays import FloatingArray
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@pytest.mark.parametrize("ufunc", [np.abs, np.sign])
|
| 10 |
+
# np.sign emits a warning with nans, <https://github.com/numpy/numpy/issues/15127>
|
| 11 |
+
@pytest.mark.filterwarnings("ignore:invalid value encountered in sign:RuntimeWarning")
|
| 12 |
+
def test_ufuncs_single_int(ufunc):
|
| 13 |
+
a = pd.array([1, 2, -3, np.nan])
|
| 14 |
+
result = ufunc(a)
|
| 15 |
+
expected = pd.array(ufunc(a.astype(float)), dtype="Int64")
|
| 16 |
+
tm.assert_extension_array_equal(result, expected)
|
| 17 |
+
|
| 18 |
+
s = pd.Series(a)
|
| 19 |
+
result = ufunc(s)
|
| 20 |
+
expected = pd.Series(pd.array(ufunc(a.astype(float)), dtype="Int64"))
|
| 21 |
+
tm.assert_series_equal(result, expected)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@pytest.mark.parametrize("ufunc", [np.log, np.exp, np.sin, np.cos, np.sqrt])
|
| 25 |
+
def test_ufuncs_single_float(ufunc):
|
| 26 |
+
a = pd.array([1, 2, -3, np.nan])
|
| 27 |
+
with np.errstate(invalid="ignore"):
|
| 28 |
+
result = ufunc(a)
|
| 29 |
+
expected = FloatingArray(ufunc(a.astype(float)), mask=a._mask)
|
| 30 |
+
tm.assert_extension_array_equal(result, expected)
|
| 31 |
+
|
| 32 |
+
s = pd.Series(a)
|
| 33 |
+
with np.errstate(invalid="ignore"):
|
| 34 |
+
result = ufunc(s)
|
| 35 |
+
expected = pd.Series(expected)
|
| 36 |
+
tm.assert_series_equal(result, expected)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@pytest.mark.parametrize("ufunc", [np.add, np.subtract])
|
| 40 |
+
def test_ufuncs_binary_int(ufunc):
|
| 41 |
+
# two IntegerArrays
|
| 42 |
+
a = pd.array([1, 2, -3, np.nan])
|
| 43 |
+
result = ufunc(a, a)
|
| 44 |
+
expected = pd.array(ufunc(a.astype(float), a.astype(float)), dtype="Int64")
|
| 45 |
+
tm.assert_extension_array_equal(result, expected)
|
| 46 |
+
|
| 47 |
+
# IntegerArray with numpy array
|
| 48 |
+
arr = np.array([1, 2, 3, 4])
|
| 49 |
+
result = ufunc(a, arr)
|
| 50 |
+
expected = pd.array(ufunc(a.astype(float), arr), dtype="Int64")
|
| 51 |
+
tm.assert_extension_array_equal(result, expected)
|
| 52 |
+
|
| 53 |
+
result = ufunc(arr, a)
|
| 54 |
+
expected = pd.array(ufunc(arr, a.astype(float)), dtype="Int64")
|
| 55 |
+
tm.assert_extension_array_equal(result, expected)
|
| 56 |
+
|
| 57 |
+
# IntegerArray with scalar
|
| 58 |
+
result = ufunc(a, 1)
|
| 59 |
+
expected = pd.array(ufunc(a.astype(float), 1), dtype="Int64")
|
| 60 |
+
tm.assert_extension_array_equal(result, expected)
|
| 61 |
+
|
| 62 |
+
result = ufunc(1, a)
|
| 63 |
+
expected = pd.array(ufunc(1, a.astype(float)), dtype="Int64")
|
| 64 |
+
tm.assert_extension_array_equal(result, expected)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def test_ufunc_binary_output():
|
| 68 |
+
a = pd.array([1, 2, np.nan])
|
| 69 |
+
result = np.modf(a)
|
| 70 |
+
expected = np.modf(a.to_numpy(na_value=np.nan, dtype="float"))
|
| 71 |
+
expected = (pd.array(expected[0]), pd.array(expected[1]))
|
| 72 |
+
|
| 73 |
+
assert isinstance(result, tuple)
|
| 74 |
+
assert len(result) == 2
|
| 75 |
+
|
| 76 |
+
for x, y in zip(result, expected):
|
| 77 |
+
tm.assert_extension_array_equal(x, y)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@pytest.mark.parametrize("values", [[0, 1], [0, None]])
|
| 81 |
+
def test_ufunc_reduce_raises(values):
|
| 82 |
+
arr = pd.array(values)
|
| 83 |
+
|
| 84 |
+
res = np.add.reduce(arr)
|
| 85 |
+
expected = arr.sum(skipna=False)
|
| 86 |
+
tm.assert_almost_equal(res, expected)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
@pytest.mark.parametrize(
|
| 90 |
+
"pandasmethname, kwargs",
|
| 91 |
+
[
|
| 92 |
+
("var", {"ddof": 0}),
|
| 93 |
+
("var", {"ddof": 1}),
|
| 94 |
+
("std", {"ddof": 0}),
|
| 95 |
+
("std", {"ddof": 1}),
|
| 96 |
+
("kurtosis", {}),
|
| 97 |
+
("skew", {}),
|
| 98 |
+
("sem", {}),
|
| 99 |
+
],
|
| 100 |
+
)
|
| 101 |
+
def test_stat_method(pandasmethname, kwargs):
|
| 102 |
+
s = pd.Series(data=[1, 2, 3, 4, 5, 6, np.nan, np.nan], dtype="Int64")
|
| 103 |
+
pandasmeth = getattr(s, pandasmethname)
|
| 104 |
+
result = pandasmeth(**kwargs)
|
| 105 |
+
s2 = pd.Series(data=[1, 2, 3, 4, 5, 6], dtype="Int64")
|
| 106 |
+
pandasmeth = getattr(s2, pandasmethname)
|
| 107 |
+
expected = pandasmeth(**kwargs)
|
| 108 |
+
assert expected == result
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def test_value_counts_na():
|
| 112 |
+
arr = pd.array([1, 2, 1, pd.NA], dtype="Int64")
|
| 113 |
+
result = arr.value_counts(dropna=False)
|
| 114 |
+
ex_index = pd.Index([1, 2, pd.NA], dtype="Int64")
|
| 115 |
+
assert ex_index.dtype == "Int64"
|
| 116 |
+
expected = pd.Series([2, 1, 1], index=ex_index, dtype="Int64", name="count")
|
| 117 |
+
tm.assert_series_equal(result, expected)
|
| 118 |
+
|
| 119 |
+
result = arr.value_counts(dropna=True)
|
| 120 |
+
expected = pd.Series([2, 1], index=arr[:2], dtype="Int64", name="count")
|
| 121 |
+
assert expected.index.dtype == arr.dtype
|
| 122 |
+
tm.assert_series_equal(result, expected)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def test_value_counts_empty():
|
| 126 |
+
# https://github.com/pandas-dev/pandas/issues/33317
|
| 127 |
+
ser = pd.Series([], dtype="Int64")
|
| 128 |
+
result = ser.value_counts()
|
| 129 |
+
idx = pd.Index([], dtype=ser.dtype)
|
| 130 |
+
assert idx.dtype == ser.dtype
|
| 131 |
+
expected = pd.Series([], index=idx, dtype="Int64", name="count")
|
| 132 |
+
tm.assert_series_equal(result, expected)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def test_value_counts_with_normalize():
|
| 136 |
+
# GH 33172
|
| 137 |
+
ser = pd.Series([1, 2, 1, pd.NA], dtype="Int64")
|
| 138 |
+
result = ser.value_counts(normalize=True)
|
| 139 |
+
expected = pd.Series([2, 1], index=ser[:2], dtype="Float64", name="proportion") / 3
|
| 140 |
+
assert expected.index.dtype == ser.dtype
|
| 141 |
+
tm.assert_series_equal(result, expected)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
@pytest.mark.parametrize("skipna", [True, False])
|
| 145 |
+
@pytest.mark.parametrize("min_count", [0, 4])
|
| 146 |
+
def test_integer_array_sum(skipna, min_count, any_int_ea_dtype):
|
| 147 |
+
dtype = any_int_ea_dtype
|
| 148 |
+
arr = pd.array([1, 2, 3, None], dtype=dtype)
|
| 149 |
+
result = arr.sum(skipna=skipna, min_count=min_count)
|
| 150 |
+
if skipna and min_count == 0:
|
| 151 |
+
assert result == 6
|
| 152 |
+
else:
|
| 153 |
+
assert result is pd.NA
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
@pytest.mark.parametrize("skipna", [True, False])
|
| 157 |
+
@pytest.mark.parametrize("method", ["min", "max"])
|
| 158 |
+
def test_integer_array_min_max(skipna, method, any_int_ea_dtype):
|
| 159 |
+
dtype = any_int_ea_dtype
|
| 160 |
+
arr = pd.array([0, 1, None], dtype=dtype)
|
| 161 |
+
func = getattr(arr, method)
|
| 162 |
+
result = func(skipna=skipna)
|
| 163 |
+
if skipna:
|
| 164 |
+
assert result == (0 if method == "min" else 1)
|
| 165 |
+
else:
|
| 166 |
+
assert result is pd.NA
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
@pytest.mark.parametrize("skipna", [True, False])
|
| 170 |
+
@pytest.mark.parametrize("min_count", [0, 9])
|
| 171 |
+
def test_integer_array_prod(skipna, min_count, any_int_ea_dtype):
|
| 172 |
+
dtype = any_int_ea_dtype
|
| 173 |
+
arr = pd.array([1, 2, None], dtype=dtype)
|
| 174 |
+
result = arr.prod(skipna=skipna, min_count=min_count)
|
| 175 |
+
if skipna and min_count == 0:
|
| 176 |
+
assert result == 2
|
| 177 |
+
else:
|
| 178 |
+
assert result is pd.NA
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
@pytest.mark.parametrize(
|
| 182 |
+
"values, expected", [([1, 2, 3], 6), ([1, 2, 3, None], 6), ([None], 0)]
|
| 183 |
+
)
|
| 184 |
+
def test_integer_array_numpy_sum(values, expected):
|
| 185 |
+
arr = pd.array(values, dtype="Int64")
|
| 186 |
+
result = np.sum(arr)
|
| 187 |
+
assert result == expected
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
@pytest.mark.parametrize("op", ["sum", "prod", "min", "max"])
|
| 191 |
+
def test_dataframe_reductions(op):
|
| 192 |
+
# https://github.com/pandas-dev/pandas/pull/32867
|
| 193 |
+
# ensure the integers are not cast to float during reductions
|
| 194 |
+
df = pd.DataFrame({"a": pd.array([1, 2], dtype="Int64")})
|
| 195 |
+
result = df.max()
|
| 196 |
+
assert isinstance(result["a"], np.int64)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
# TODO(jreback) - these need testing / are broken
|
| 200 |
+
|
| 201 |
+
# shift
|
| 202 |
+
|
| 203 |
+
# set_index (destroys type)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/integer/test_indexing.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import pandas._testing as tm
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def test_array_setitem_nullable_boolean_mask():
|
| 6 |
+
# GH 31446
|
| 7 |
+
ser = pd.Series([1, 2], dtype="Int64")
|
| 8 |
+
result = ser.where(ser > 1)
|
| 9 |
+
expected = pd.Series([pd.NA, 2], dtype="Int64")
|
| 10 |
+
tm.assert_series_equal(result, expected)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def test_array_setitem():
|
| 14 |
+
# GH 31446
|
| 15 |
+
arr = pd.Series([1, 2], dtype="Int64").array
|
| 16 |
+
arr[arr > 1] = 1
|
| 17 |
+
|
| 18 |
+
expected = pd.array([1, 1], dtype="Int64")
|
| 19 |
+
tm.assert_extension_array_equal(arr, expected)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/integer/test_reduction.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from pandas import (
|
| 6 |
+
DataFrame,
|
| 7 |
+
Series,
|
| 8 |
+
array,
|
| 9 |
+
)
|
| 10 |
+
import pandas._testing as tm
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@pytest.mark.parametrize(
|
| 14 |
+
"op, expected",
|
| 15 |
+
[
|
| 16 |
+
["sum", np.int64(3)],
|
| 17 |
+
["prod", np.int64(2)],
|
| 18 |
+
["min", np.int64(1)],
|
| 19 |
+
["max", np.int64(2)],
|
| 20 |
+
["mean", np.float64(1.5)],
|
| 21 |
+
["median", np.float64(1.5)],
|
| 22 |
+
["var", np.float64(0.5)],
|
| 23 |
+
["std", np.float64(0.5**0.5)],
|
| 24 |
+
["skew", pd.NA],
|
| 25 |
+
["kurt", pd.NA],
|
| 26 |
+
["any", True],
|
| 27 |
+
["all", True],
|
| 28 |
+
],
|
| 29 |
+
)
|
| 30 |
+
def test_series_reductions(op, expected):
|
| 31 |
+
ser = Series([1, 2], dtype="Int64")
|
| 32 |
+
result = getattr(ser, op)()
|
| 33 |
+
tm.assert_equal(result, expected)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@pytest.mark.parametrize(
|
| 37 |
+
"op, expected",
|
| 38 |
+
[
|
| 39 |
+
["sum", Series([3], index=["a"], dtype="Int64")],
|
| 40 |
+
["prod", Series([2], index=["a"], dtype="Int64")],
|
| 41 |
+
["min", Series([1], index=["a"], dtype="Int64")],
|
| 42 |
+
["max", Series([2], index=["a"], dtype="Int64")],
|
| 43 |
+
["mean", Series([1.5], index=["a"], dtype="Float64")],
|
| 44 |
+
["median", Series([1.5], index=["a"], dtype="Float64")],
|
| 45 |
+
["var", Series([0.5], index=["a"], dtype="Float64")],
|
| 46 |
+
["std", Series([0.5**0.5], index=["a"], dtype="Float64")],
|
| 47 |
+
["skew", Series([pd.NA], index=["a"], dtype="Float64")],
|
| 48 |
+
["kurt", Series([pd.NA], index=["a"], dtype="Float64")],
|
| 49 |
+
["any", Series([True], index=["a"], dtype="boolean")],
|
| 50 |
+
["all", Series([True], index=["a"], dtype="boolean")],
|
| 51 |
+
],
|
| 52 |
+
)
|
| 53 |
+
def test_dataframe_reductions(op, expected):
|
| 54 |
+
df = DataFrame({"a": array([1, 2], dtype="Int64")})
|
| 55 |
+
result = getattr(df, op)()
|
| 56 |
+
tm.assert_series_equal(result, expected)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@pytest.mark.parametrize(
|
| 60 |
+
"op, expected",
|
| 61 |
+
[
|
| 62 |
+
["sum", array([1, 3], dtype="Int64")],
|
| 63 |
+
["prod", array([1, 3], dtype="Int64")],
|
| 64 |
+
["min", array([1, 3], dtype="Int64")],
|
| 65 |
+
["max", array([1, 3], dtype="Int64")],
|
| 66 |
+
["mean", array([1, 3], dtype="Float64")],
|
| 67 |
+
["median", array([1, 3], dtype="Float64")],
|
| 68 |
+
["var", array([pd.NA], dtype="Float64")],
|
| 69 |
+
["std", array([pd.NA], dtype="Float64")],
|
| 70 |
+
["skew", array([pd.NA], dtype="Float64")],
|
| 71 |
+
["any", array([True, True], dtype="boolean")],
|
| 72 |
+
["all", array([True, True], dtype="boolean")],
|
| 73 |
+
],
|
| 74 |
+
)
|
| 75 |
+
def test_groupby_reductions(op, expected):
|
| 76 |
+
df = DataFrame(
|
| 77 |
+
{
|
| 78 |
+
"A": ["a", "b", "b"],
|
| 79 |
+
"B": array([1, None, 3], dtype="Int64"),
|
| 80 |
+
}
|
| 81 |
+
)
|
| 82 |
+
result = getattr(df.groupby("A"), op)()
|
| 83 |
+
expected = DataFrame(expected, index=pd.Index(["a", "b"], name="A"), columns=["B"])
|
| 84 |
+
|
| 85 |
+
tm.assert_frame_equal(result, expected)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
@pytest.mark.parametrize(
|
| 89 |
+
"op, expected",
|
| 90 |
+
[
|
| 91 |
+
["sum", Series([4, 4], index=["B", "C"], dtype="Float64")],
|
| 92 |
+
["prod", Series([3, 3], index=["B", "C"], dtype="Float64")],
|
| 93 |
+
["min", Series([1, 1], index=["B", "C"], dtype="Float64")],
|
| 94 |
+
["max", Series([3, 3], index=["B", "C"], dtype="Float64")],
|
| 95 |
+
["mean", Series([2, 2], index=["B", "C"], dtype="Float64")],
|
| 96 |
+
["median", Series([2, 2], index=["B", "C"], dtype="Float64")],
|
| 97 |
+
["var", Series([2, 2], index=["B", "C"], dtype="Float64")],
|
| 98 |
+
["std", Series([2**0.5, 2**0.5], index=["B", "C"], dtype="Float64")],
|
| 99 |
+
["skew", Series([pd.NA, pd.NA], index=["B", "C"], dtype="Float64")],
|
| 100 |
+
["kurt", Series([pd.NA, pd.NA], index=["B", "C"], dtype="Float64")],
|
| 101 |
+
["any", Series([True, True, True], index=["A", "B", "C"], dtype="boolean")],
|
| 102 |
+
["all", Series([True, True, True], index=["A", "B", "C"], dtype="boolean")],
|
| 103 |
+
],
|
| 104 |
+
)
|
| 105 |
+
def test_mixed_reductions(op, expected):
|
| 106 |
+
df = DataFrame(
|
| 107 |
+
{
|
| 108 |
+
"A": ["a", "b", "b"],
|
| 109 |
+
"B": [1, None, 3],
|
| 110 |
+
"C": array([1, None, 3], dtype="Int64"),
|
| 111 |
+
}
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
# series
|
| 115 |
+
result = getattr(df.C, op)()
|
| 116 |
+
tm.assert_equal(result, expected["C"])
|
| 117 |
+
|
| 118 |
+
# frame
|
| 119 |
+
if op in ["any", "all"]:
|
| 120 |
+
result = getattr(df, op)()
|
| 121 |
+
else:
|
| 122 |
+
result = getattr(df, op)(numeric_only=True)
|
| 123 |
+
tm.assert_series_equal(result, expected)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/integer/test_repr.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from pandas.core.arrays.integer import (
|
| 6 |
+
Int8Dtype,
|
| 7 |
+
Int16Dtype,
|
| 8 |
+
Int32Dtype,
|
| 9 |
+
Int64Dtype,
|
| 10 |
+
UInt8Dtype,
|
| 11 |
+
UInt16Dtype,
|
| 12 |
+
UInt32Dtype,
|
| 13 |
+
UInt64Dtype,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def test_dtypes(dtype):
|
| 18 |
+
# smoke tests on auto dtype construction
|
| 19 |
+
|
| 20 |
+
if dtype.is_signed_integer:
|
| 21 |
+
assert np.dtype(dtype.type).kind == "i"
|
| 22 |
+
else:
|
| 23 |
+
assert np.dtype(dtype.type).kind == "u"
|
| 24 |
+
assert dtype.name is not None
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@pytest.mark.parametrize(
|
| 28 |
+
"dtype, expected",
|
| 29 |
+
[
|
| 30 |
+
(Int8Dtype(), "Int8Dtype()"),
|
| 31 |
+
(Int16Dtype(), "Int16Dtype()"),
|
| 32 |
+
(Int32Dtype(), "Int32Dtype()"),
|
| 33 |
+
(Int64Dtype(), "Int64Dtype()"),
|
| 34 |
+
(UInt8Dtype(), "UInt8Dtype()"),
|
| 35 |
+
(UInt16Dtype(), "UInt16Dtype()"),
|
| 36 |
+
(UInt32Dtype(), "UInt32Dtype()"),
|
| 37 |
+
(UInt64Dtype(), "UInt64Dtype()"),
|
| 38 |
+
],
|
| 39 |
+
)
|
| 40 |
+
def test_repr_dtype(dtype, expected):
|
| 41 |
+
assert repr(dtype) == expected
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_repr_array():
|
| 45 |
+
result = repr(pd.array([1, None, 3]))
|
| 46 |
+
expected = "<IntegerArray>\n[1, <NA>, 3]\nLength: 3, dtype: Int64"
|
| 47 |
+
assert result == expected
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def test_repr_array_long():
|
| 51 |
+
data = pd.array([1, 2, None] * 1000)
|
| 52 |
+
expected = (
|
| 53 |
+
"<IntegerArray>\n"
|
| 54 |
+
"[ 1, 2, <NA>, 1, 2, <NA>, 1, 2, <NA>, 1,\n"
|
| 55 |
+
" ...\n"
|
| 56 |
+
" <NA>, 1, 2, <NA>, 1, 2, <NA>, 1, 2, <NA>]\n"
|
| 57 |
+
"Length: 3000, dtype: Int64"
|
| 58 |
+
)
|
| 59 |
+
result = repr(data)
|
| 60 |
+
assert result == expected
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def test_frame_repr(data_missing):
|
| 64 |
+
df = pd.DataFrame({"A": data_missing})
|
| 65 |
+
result = repr(df)
|
| 66 |
+
expected = " A\n0 <NA>\n1 1"
|
| 67 |
+
assert result == expected
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/interval/__init__.py
ADDED
|
File without changes
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/interval/test_astype.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
from pandas import (
|
| 4 |
+
Categorical,
|
| 5 |
+
CategoricalDtype,
|
| 6 |
+
Index,
|
| 7 |
+
IntervalIndex,
|
| 8 |
+
)
|
| 9 |
+
import pandas._testing as tm
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class TestAstype:
|
| 13 |
+
@pytest.mark.parametrize("ordered", [True, False])
|
| 14 |
+
def test_astype_categorical_retains_ordered(self, ordered):
|
| 15 |
+
index = IntervalIndex.from_breaks(range(5))
|
| 16 |
+
arr = index._data
|
| 17 |
+
|
| 18 |
+
dtype = CategoricalDtype(None, ordered=ordered)
|
| 19 |
+
|
| 20 |
+
expected = Categorical(list(arr), ordered=ordered)
|
| 21 |
+
result = arr.astype(dtype)
|
| 22 |
+
assert result.ordered is ordered
|
| 23 |
+
tm.assert_categorical_equal(result, expected)
|
| 24 |
+
|
| 25 |
+
# test IntervalIndex.astype while we're at it.
|
| 26 |
+
result = index.astype(dtype)
|
| 27 |
+
expected = Index(expected)
|
| 28 |
+
tm.assert_index_equal(result, expected)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/interval/test_formats.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pandas.core.arrays import IntervalArray
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def test_repr():
|
| 5 |
+
# GH#25022
|
| 6 |
+
arr = IntervalArray.from_tuples([(0, 1), (1, 2)])
|
| 7 |
+
result = repr(arr)
|
| 8 |
+
expected = (
|
| 9 |
+
"<IntervalArray>\n"
|
| 10 |
+
"[(0, 1], (1, 2]]\n"
|
| 11 |
+
"Length: 2, dtype: interval[int64, right]"
|
| 12 |
+
)
|
| 13 |
+
assert result == expected
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/interval/test_interval.py
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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11 |
+
date_range,
|
| 12 |
+
timedelta_range,
|
| 13 |
+
)
|
| 14 |
+
import pandas._testing as tm
|
| 15 |
+
from pandas.core.arrays import IntervalArray
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@pytest.fixture(
|
| 19 |
+
params=[
|
| 20 |
+
(Index([0, 2, 4]), Index([1, 3, 5])),
|
| 21 |
+
(Index([0.0, 1.0, 2.0]), Index([1.0, 2.0, 3.0])),
|
| 22 |
+
(timedelta_range("0 days", periods=3), timedelta_range("1 day", periods=3)),
|
| 23 |
+
(date_range("20170101", periods=3), date_range("20170102", periods=3)),
|
| 24 |
+
(
|
| 25 |
+
date_range("20170101", periods=3, tz="US/Eastern"),
|
| 26 |
+
date_range("20170102", periods=3, tz="US/Eastern"),
|
| 27 |
+
),
|
| 28 |
+
],
|
| 29 |
+
ids=lambda x: str(x[0].dtype),
|
| 30 |
+
)
|
| 31 |
+
def left_right_dtypes(request):
|
| 32 |
+
"""
|
| 33 |
+
Fixture for building an IntervalArray from various dtypes
|
| 34 |
+
"""
|
| 35 |
+
return request.param
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class TestAttributes:
|
| 39 |
+
@pytest.mark.parametrize(
|
| 40 |
+
"left, right",
|
| 41 |
+
[
|
| 42 |
+
(0, 1),
|
| 43 |
+
(Timedelta("0 days"), Timedelta("1 day")),
|
| 44 |
+
(Timestamp("2018-01-01"), Timestamp("2018-01-02")),
|
| 45 |
+
(
|
| 46 |
+
Timestamp("2018-01-01", tz="US/Eastern"),
|
| 47 |
+
Timestamp("2018-01-02", tz="US/Eastern"),
|
| 48 |
+
),
|
| 49 |
+
],
|
| 50 |
+
)
|
| 51 |
+
@pytest.mark.parametrize("constructor", [IntervalArray, IntervalIndex])
|
| 52 |
+
def test_is_empty(self, constructor, left, right, closed):
|
| 53 |
+
# GH27219
|
| 54 |
+
tuples = [(left, left), (left, right), np.nan]
|
| 55 |
+
expected = np.array([closed != "both", False, False])
|
| 56 |
+
result = constructor.from_tuples(tuples, closed=closed).is_empty
|
| 57 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class TestMethods:
|
| 61 |
+
@pytest.mark.parametrize("new_closed", ["left", "right", "both", "neither"])
|
| 62 |
+
def test_set_closed(self, closed, new_closed):
|
| 63 |
+
# GH 21670
|
| 64 |
+
array = IntervalArray.from_breaks(range(10), closed=closed)
|
| 65 |
+
result = array.set_closed(new_closed)
|
| 66 |
+
expected = IntervalArray.from_breaks(range(10), closed=new_closed)
|
| 67 |
+
tm.assert_extension_array_equal(result, expected)
|
| 68 |
+
|
| 69 |
+
@pytest.mark.parametrize(
|
| 70 |
+
"other",
|
| 71 |
+
[
|
| 72 |
+
Interval(0, 1, closed="right"),
|
| 73 |
+
IntervalArray.from_breaks([1, 2, 3, 4], closed="right"),
|
| 74 |
+
],
|
| 75 |
+
)
|
| 76 |
+
def test_where_raises(self, other):
|
| 77 |
+
# GH#45768 The IntervalArray methods raises; the Series method coerces
|
| 78 |
+
ser = pd.Series(IntervalArray.from_breaks([1, 2, 3, 4], closed="left"))
|
| 79 |
+
mask = np.array([True, False, True])
|
| 80 |
+
match = "'value.closed' is 'right', expected 'left'."
|
| 81 |
+
with pytest.raises(ValueError, match=match):
|
| 82 |
+
ser.array._where(mask, other)
|
| 83 |
+
|
| 84 |
+
res = ser.where(mask, other=other)
|
| 85 |
+
expected = ser.astype(object).where(mask, other)
|
| 86 |
+
tm.assert_series_equal(res, expected)
|
| 87 |
+
|
| 88 |
+
def test_shift(self):
|
| 89 |
+
# https://github.com/pandas-dev/pandas/issues/31495, GH#22428, GH#31502
|
| 90 |
+
a = IntervalArray.from_breaks([1, 2, 3])
|
| 91 |
+
result = a.shift()
|
| 92 |
+
# int -> float
|
| 93 |
+
expected = IntervalArray.from_tuples([(np.nan, np.nan), (1.0, 2.0)])
|
| 94 |
+
tm.assert_interval_array_equal(result, expected)
|
| 95 |
+
|
| 96 |
+
msg = "can only insert Interval objects and NA into an IntervalArray"
|
| 97 |
+
with pytest.raises(TypeError, match=msg):
|
| 98 |
+
a.shift(1, fill_value=pd.NaT)
|
| 99 |
+
|
| 100 |
+
def test_shift_datetime(self):
|
| 101 |
+
# GH#31502, GH#31504
|
| 102 |
+
a = IntervalArray.from_breaks(date_range("2000", periods=4))
|
| 103 |
+
result = a.shift(2)
|
| 104 |
+
expected = a.take([-1, -1, 0], allow_fill=True)
|
| 105 |
+
tm.assert_interval_array_equal(result, expected)
|
| 106 |
+
|
| 107 |
+
result = a.shift(-1)
|
| 108 |
+
expected = a.take([1, 2, -1], allow_fill=True)
|
| 109 |
+
tm.assert_interval_array_equal(result, expected)
|
| 110 |
+
|
| 111 |
+
msg = "can only insert Interval objects and NA into an IntervalArray"
|
| 112 |
+
with pytest.raises(TypeError, match=msg):
|
| 113 |
+
a.shift(1, fill_value=np.timedelta64("NaT", "ns"))
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class TestSetitem:
|
| 117 |
+
def test_set_na(self, left_right_dtypes):
|
| 118 |
+
left, right = left_right_dtypes
|
| 119 |
+
left = left.copy(deep=True)
|
| 120 |
+
right = right.copy(deep=True)
|
| 121 |
+
result = IntervalArray.from_arrays(left, right)
|
| 122 |
+
|
| 123 |
+
if result.dtype.subtype.kind not in ["m", "M"]:
|
| 124 |
+
msg = "'value' should be an interval type, got <.*NaTType'> instead."
|
| 125 |
+
with pytest.raises(TypeError, match=msg):
|
| 126 |
+
result[0] = pd.NaT
|
| 127 |
+
if result.dtype.subtype.kind in ["i", "u"]:
|
| 128 |
+
msg = "Cannot set float NaN to integer-backed IntervalArray"
|
| 129 |
+
# GH#45484 TypeError, not ValueError, matches what we get with
|
| 130 |
+
# non-NA un-holdable value.
|
| 131 |
+
with pytest.raises(TypeError, match=msg):
|
| 132 |
+
result[0] = np.nan
|
| 133 |
+
return
|
| 134 |
+
|
| 135 |
+
result[0] = np.nan
|
| 136 |
+
|
| 137 |
+
expected_left = Index([left._na_value] + list(left[1:]))
|
| 138 |
+
expected_right = Index([right._na_value] + list(right[1:]))
|
| 139 |
+
expected = IntervalArray.from_arrays(expected_left, expected_right)
|
| 140 |
+
|
| 141 |
+
tm.assert_extension_array_equal(result, expected)
|
| 142 |
+
|
| 143 |
+
def test_setitem_mismatched_closed(self):
|
| 144 |
+
arr = IntervalArray.from_breaks(range(4))
|
| 145 |
+
orig = arr.copy()
|
| 146 |
+
other = arr.set_closed("both")
|
| 147 |
+
|
| 148 |
+
msg = "'value.closed' is 'both', expected 'right'"
|
| 149 |
+
with pytest.raises(ValueError, match=msg):
|
| 150 |
+
arr[0] = other[0]
|
| 151 |
+
with pytest.raises(ValueError, match=msg):
|
| 152 |
+
arr[:1] = other[:1]
|
| 153 |
+
with pytest.raises(ValueError, match=msg):
|
| 154 |
+
arr[:0] = other[:0]
|
| 155 |
+
with pytest.raises(ValueError, match=msg):
|
| 156 |
+
arr[:] = other[::-1]
|
| 157 |
+
with pytest.raises(ValueError, match=msg):
|
| 158 |
+
arr[:] = list(other[::-1])
|
| 159 |
+
with pytest.raises(ValueError, match=msg):
|
| 160 |
+
arr[:] = other[::-1].astype(object)
|
| 161 |
+
with pytest.raises(ValueError, match=msg):
|
| 162 |
+
arr[:] = other[::-1].astype("category")
|
| 163 |
+
|
| 164 |
+
# empty list should be no-op
|
| 165 |
+
arr[:0] = []
|
| 166 |
+
tm.assert_interval_array_equal(arr, orig)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class TestReductions:
|
| 170 |
+
def test_min_max_invalid_axis(self, left_right_dtypes):
|
| 171 |
+
left, right = left_right_dtypes
|
| 172 |
+
left = left.copy(deep=True)
|
| 173 |
+
right = right.copy(deep=True)
|
| 174 |
+
arr = IntervalArray.from_arrays(left, right)
|
| 175 |
+
|
| 176 |
+
msg = "`axis` must be fewer than the number of dimensions"
|
| 177 |
+
for axis in [-2, 1]:
|
| 178 |
+
with pytest.raises(ValueError, match=msg):
|
| 179 |
+
arr.min(axis=axis)
|
| 180 |
+
with pytest.raises(ValueError, match=msg):
|
| 181 |
+
arr.max(axis=axis)
|
| 182 |
+
|
| 183 |
+
msg = "'>=' not supported between"
|
| 184 |
+
with pytest.raises(TypeError, match=msg):
|
| 185 |
+
arr.min(axis="foo")
|
| 186 |
+
with pytest.raises(TypeError, match=msg):
|
| 187 |
+
arr.max(axis="foo")
|
| 188 |
+
|
| 189 |
+
def test_min_max(self, left_right_dtypes, index_or_series_or_array):
|
| 190 |
+
# GH#44746
|
| 191 |
+
left, right = left_right_dtypes
|
| 192 |
+
left = left.copy(deep=True)
|
| 193 |
+
right = right.copy(deep=True)
|
| 194 |
+
arr = IntervalArray.from_arrays(left, right)
|
| 195 |
+
|
| 196 |
+
# The expected results below are only valid if monotonic
|
| 197 |
+
assert left.is_monotonic_increasing
|
| 198 |
+
assert Index(arr).is_monotonic_increasing
|
| 199 |
+
|
| 200 |
+
MIN = arr[0]
|
| 201 |
+
MAX = arr[-1]
|
| 202 |
+
|
| 203 |
+
indexer = np.arange(len(arr))
|
| 204 |
+
np.random.default_rng(2).shuffle(indexer)
|
| 205 |
+
arr = arr.take(indexer)
|
| 206 |
+
|
| 207 |
+
arr_na = arr.insert(2, np.nan)
|
| 208 |
+
|
| 209 |
+
arr = index_or_series_or_array(arr)
|
| 210 |
+
arr_na = index_or_series_or_array(arr_na)
|
| 211 |
+
|
| 212 |
+
for skipna in [True, False]:
|
| 213 |
+
res = arr.min(skipna=skipna)
|
| 214 |
+
assert res == MIN
|
| 215 |
+
assert type(res) == type(MIN)
|
| 216 |
+
|
| 217 |
+
res = arr.max(skipna=skipna)
|
| 218 |
+
assert res == MAX
|
| 219 |
+
assert type(res) == type(MAX)
|
| 220 |
+
|
| 221 |
+
res = arr_na.min(skipna=False)
|
| 222 |
+
assert np.isnan(res)
|
| 223 |
+
res = arr_na.max(skipna=False)
|
| 224 |
+
assert np.isnan(res)
|
| 225 |
+
|
| 226 |
+
res = arr_na.min(skipna=True)
|
| 227 |
+
assert res == MIN
|
| 228 |
+
assert type(res) == type(MIN)
|
| 229 |
+
res = arr_na.max(skipna=True)
|
| 230 |
+
assert res == MAX
|
| 231 |
+
assert type(res) == type(MAX)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/interval/test_interval_pyarrow.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import pandas._testing as tm
|
| 6 |
+
from pandas.core.arrays import IntervalArray
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def test_arrow_extension_type():
|
| 10 |
+
pa = pytest.importorskip("pyarrow")
|
| 11 |
+
|
| 12 |
+
from pandas.core.arrays.arrow.extension_types import ArrowIntervalType
|
| 13 |
+
|
| 14 |
+
p1 = ArrowIntervalType(pa.int64(), "left")
|
| 15 |
+
p2 = ArrowIntervalType(pa.int64(), "left")
|
| 16 |
+
p3 = ArrowIntervalType(pa.int64(), "right")
|
| 17 |
+
|
| 18 |
+
assert p1.closed == "left"
|
| 19 |
+
assert p1 == p2
|
| 20 |
+
assert p1 != p3
|
| 21 |
+
assert hash(p1) == hash(p2)
|
| 22 |
+
assert hash(p1) != hash(p3)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_arrow_array():
|
| 26 |
+
pa = pytest.importorskip("pyarrow")
|
| 27 |
+
|
| 28 |
+
from pandas.core.arrays.arrow.extension_types import ArrowIntervalType
|
| 29 |
+
|
| 30 |
+
intervals = pd.interval_range(1, 5, freq=1).array
|
| 31 |
+
|
| 32 |
+
result = pa.array(intervals)
|
| 33 |
+
assert isinstance(result.type, ArrowIntervalType)
|
| 34 |
+
assert result.type.closed == intervals.closed
|
| 35 |
+
assert result.type.subtype == pa.int64()
|
| 36 |
+
assert result.storage.field("left").equals(pa.array([1, 2, 3, 4], type="int64"))
|
| 37 |
+
assert result.storage.field("right").equals(pa.array([2, 3, 4, 5], type="int64"))
|
| 38 |
+
|
| 39 |
+
expected = pa.array([{"left": i, "right": i + 1} for i in range(1, 5)])
|
| 40 |
+
assert result.storage.equals(expected)
|
| 41 |
+
|
| 42 |
+
# convert to its storage type
|
| 43 |
+
result = pa.array(intervals, type=expected.type)
|
| 44 |
+
assert result.equals(expected)
|
| 45 |
+
|
| 46 |
+
# unsupported conversions
|
| 47 |
+
with pytest.raises(TypeError, match="Not supported to convert IntervalArray"):
|
| 48 |
+
pa.array(intervals, type="float64")
|
| 49 |
+
|
| 50 |
+
with pytest.raises(TypeError, match="Not supported to convert IntervalArray"):
|
| 51 |
+
pa.array(intervals, type=ArrowIntervalType(pa.float64(), "left"))
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def test_arrow_array_missing():
|
| 55 |
+
pa = pytest.importorskip("pyarrow")
|
| 56 |
+
|
| 57 |
+
from pandas.core.arrays.arrow.extension_types import ArrowIntervalType
|
| 58 |
+
|
| 59 |
+
arr = IntervalArray.from_breaks([0.0, 1.0, 2.0, 3.0])
|
| 60 |
+
arr[1] = None
|
| 61 |
+
|
| 62 |
+
result = pa.array(arr)
|
| 63 |
+
assert isinstance(result.type, ArrowIntervalType)
|
| 64 |
+
assert result.type.closed == arr.closed
|
| 65 |
+
assert result.type.subtype == pa.float64()
|
| 66 |
+
|
| 67 |
+
# fields have missing values (not NaN)
|
| 68 |
+
left = pa.array([0.0, None, 2.0], type="float64")
|
| 69 |
+
right = pa.array([1.0, None, 3.0], type="float64")
|
| 70 |
+
assert result.storage.field("left").equals(left)
|
| 71 |
+
assert result.storage.field("right").equals(right)
|
| 72 |
+
|
| 73 |
+
# structarray itself also has missing values on the array level
|
| 74 |
+
vals = [
|
| 75 |
+
{"left": 0.0, "right": 1.0},
|
| 76 |
+
{"left": None, "right": None},
|
| 77 |
+
{"left": 2.0, "right": 3.0},
|
| 78 |
+
]
|
| 79 |
+
expected = pa.StructArray.from_pandas(vals, mask=np.array([False, True, False]))
|
| 80 |
+
assert result.storage.equals(expected)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
@pytest.mark.filterwarnings(
|
| 84 |
+
"ignore:Passing a BlockManager to DataFrame:DeprecationWarning"
|
| 85 |
+
)
|
| 86 |
+
@pytest.mark.parametrize(
|
| 87 |
+
"breaks",
|
| 88 |
+
[[0.0, 1.0, 2.0, 3.0], pd.date_range("2017", periods=4, freq="D")],
|
| 89 |
+
ids=["float", "datetime64[ns]"],
|
| 90 |
+
)
|
| 91 |
+
def test_arrow_table_roundtrip(breaks):
|
| 92 |
+
pa = pytest.importorskip("pyarrow")
|
| 93 |
+
|
| 94 |
+
from pandas.core.arrays.arrow.extension_types import ArrowIntervalType
|
| 95 |
+
|
| 96 |
+
arr = IntervalArray.from_breaks(breaks)
|
| 97 |
+
arr[1] = None
|
| 98 |
+
df = pd.DataFrame({"a": arr})
|
| 99 |
+
|
| 100 |
+
table = pa.table(df)
|
| 101 |
+
assert isinstance(table.field("a").type, ArrowIntervalType)
|
| 102 |
+
result = table.to_pandas()
|
| 103 |
+
assert isinstance(result["a"].dtype, pd.IntervalDtype)
|
| 104 |
+
tm.assert_frame_equal(result, df)
|
| 105 |
+
|
| 106 |
+
table2 = pa.concat_tables([table, table])
|
| 107 |
+
result = table2.to_pandas()
|
| 108 |
+
expected = pd.concat([df, df], ignore_index=True)
|
| 109 |
+
tm.assert_frame_equal(result, expected)
|
| 110 |
+
|
| 111 |
+
# GH#41040
|
| 112 |
+
table = pa.table(
|
| 113 |
+
[pa.chunked_array([], type=table.column(0).type)], schema=table.schema
|
| 114 |
+
)
|
| 115 |
+
result = table.to_pandas()
|
| 116 |
+
tm.assert_frame_equal(result, expected[0:0])
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
@pytest.mark.filterwarnings(
|
| 120 |
+
"ignore:Passing a BlockManager to DataFrame:DeprecationWarning"
|
| 121 |
+
)
|
| 122 |
+
@pytest.mark.parametrize(
|
| 123 |
+
"breaks",
|
| 124 |
+
[[0.0, 1.0, 2.0, 3.0], pd.date_range("2017", periods=4, freq="D")],
|
| 125 |
+
ids=["float", "datetime64[ns]"],
|
| 126 |
+
)
|
| 127 |
+
def test_arrow_table_roundtrip_without_metadata(breaks):
|
| 128 |
+
pa = pytest.importorskip("pyarrow")
|
| 129 |
+
|
| 130 |
+
arr = IntervalArray.from_breaks(breaks)
|
| 131 |
+
arr[1] = None
|
| 132 |
+
df = pd.DataFrame({"a": arr})
|
| 133 |
+
|
| 134 |
+
table = pa.table(df)
|
| 135 |
+
# remove the metadata
|
| 136 |
+
table = table.replace_schema_metadata()
|
| 137 |
+
assert table.schema.metadata is None
|
| 138 |
+
|
| 139 |
+
result = table.to_pandas()
|
| 140 |
+
assert isinstance(result["a"].dtype, pd.IntervalDtype)
|
| 141 |
+
tm.assert_frame_equal(result, df)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def test_from_arrow_from_raw_struct_array():
|
| 145 |
+
# in case pyarrow lost the Interval extension type (eg on parquet roundtrip
|
| 146 |
+
# with datetime64[ns] subtype, see GH-45881), still allow conversion
|
| 147 |
+
# from arrow to IntervalArray
|
| 148 |
+
pa = pytest.importorskip("pyarrow")
|
| 149 |
+
|
| 150 |
+
arr = pa.array([{"left": 0, "right": 1}, {"left": 1, "right": 2}])
|
| 151 |
+
dtype = pd.IntervalDtype(np.dtype("int64"), closed="neither")
|
| 152 |
+
|
| 153 |
+
result = dtype.__from_arrow__(arr)
|
| 154 |
+
expected = IntervalArray.from_breaks(
|
| 155 |
+
np.array([0, 1, 2], dtype="int64"), closed="neither"
|
| 156 |
+
)
|
| 157 |
+
tm.assert_extension_array_equal(result, expected)
|
| 158 |
+
|
| 159 |
+
result = dtype.__from_arrow__(pa.chunked_array([arr]))
|
| 160 |
+
tm.assert_extension_array_equal(result, expected)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/interval/test_overlaps.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for Interval-Interval operations, such as overlaps, contains, etc."""
|
| 2 |
+
import numpy as np
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
from pandas import (
|
| 6 |
+
Interval,
|
| 7 |
+
IntervalIndex,
|
| 8 |
+
Timedelta,
|
| 9 |
+
Timestamp,
|
| 10 |
+
)
|
| 11 |
+
import pandas._testing as tm
|
| 12 |
+
from pandas.core.arrays import IntervalArray
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@pytest.fixture(params=[IntervalArray, IntervalIndex])
|
| 16 |
+
def constructor(request):
|
| 17 |
+
"""
|
| 18 |
+
Fixture for testing both interval container classes.
|
| 19 |
+
"""
|
| 20 |
+
return request.param
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@pytest.fixture(
|
| 24 |
+
params=[
|
| 25 |
+
(Timedelta("0 days"), Timedelta("1 day")),
|
| 26 |
+
(Timestamp("2018-01-01"), Timedelta("1 day")),
|
| 27 |
+
(0, 1),
|
| 28 |
+
],
|
| 29 |
+
ids=lambda x: type(x[0]).__name__,
|
| 30 |
+
)
|
| 31 |
+
def start_shift(request):
|
| 32 |
+
"""
|
| 33 |
+
Fixture for generating intervals of different types from a start value
|
| 34 |
+
and a shift value that can be added to start to generate an endpoint.
|
| 35 |
+
"""
|
| 36 |
+
return request.param
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class TestOverlaps:
|
| 40 |
+
def test_overlaps_interval(self, constructor, start_shift, closed, other_closed):
|
| 41 |
+
start, shift = start_shift
|
| 42 |
+
interval = Interval(start, start + 3 * shift, other_closed)
|
| 43 |
+
|
| 44 |
+
# intervals: identical, nested, spanning, partial, adjacent, disjoint
|
| 45 |
+
tuples = [
|
| 46 |
+
(start, start + 3 * shift),
|
| 47 |
+
(start + shift, start + 2 * shift),
|
| 48 |
+
(start - shift, start + 4 * shift),
|
| 49 |
+
(start + 2 * shift, start + 4 * shift),
|
| 50 |
+
(start + 3 * shift, start + 4 * shift),
|
| 51 |
+
(start + 4 * shift, start + 5 * shift),
|
| 52 |
+
]
|
| 53 |
+
interval_container = constructor.from_tuples(tuples, closed)
|
| 54 |
+
|
| 55 |
+
adjacent = interval.closed_right and interval_container.closed_left
|
| 56 |
+
expected = np.array([True, True, True, True, adjacent, False])
|
| 57 |
+
result = interval_container.overlaps(interval)
|
| 58 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 59 |
+
|
| 60 |
+
@pytest.mark.parametrize("other_constructor", [IntervalArray, IntervalIndex])
|
| 61 |
+
def test_overlaps_interval_container(self, constructor, other_constructor):
|
| 62 |
+
# TODO: modify this test when implemented
|
| 63 |
+
interval_container = constructor.from_breaks(range(5))
|
| 64 |
+
other_container = other_constructor.from_breaks(range(5))
|
| 65 |
+
with pytest.raises(NotImplementedError, match="^$"):
|
| 66 |
+
interval_container.overlaps(other_container)
|
| 67 |
+
|
| 68 |
+
def test_overlaps_na(self, constructor, start_shift):
|
| 69 |
+
"""NA values are marked as False"""
|
| 70 |
+
start, shift = start_shift
|
| 71 |
+
interval = Interval(start, start + shift)
|
| 72 |
+
|
| 73 |
+
tuples = [
|
| 74 |
+
(start, start + shift),
|
| 75 |
+
np.nan,
|
| 76 |
+
(start + 2 * shift, start + 3 * shift),
|
| 77 |
+
]
|
| 78 |
+
interval_container = constructor.from_tuples(tuples)
|
| 79 |
+
|
| 80 |
+
expected = np.array([True, False, False])
|
| 81 |
+
result = interval_container.overlaps(interval)
|
| 82 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 83 |
+
|
| 84 |
+
@pytest.mark.parametrize(
|
| 85 |
+
"other",
|
| 86 |
+
[10, True, "foo", Timedelta("1 day"), Timestamp("2018-01-01")],
|
| 87 |
+
ids=lambda x: type(x).__name__,
|
| 88 |
+
)
|
| 89 |
+
def test_overlaps_invalid_type(self, constructor, other):
|
| 90 |
+
interval_container = constructor.from_breaks(range(5))
|
| 91 |
+
msg = f"`other` must be Interval-like, got {type(other).__name__}"
|
| 92 |
+
with pytest.raises(TypeError, match=msg):
|
| 93 |
+
interval_container.overlaps(other)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/masked/__init__.py
ADDED
|
File without changes
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/masked/test_arithmetic.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Any
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
import pandas as pd
|
| 9 |
+
import pandas._testing as tm
|
| 10 |
+
|
| 11 |
+
# integer dtypes
|
| 12 |
+
arrays = [pd.array([1, 2, 3, None], dtype=dtype) for dtype in tm.ALL_INT_EA_DTYPES]
|
| 13 |
+
scalars: list[Any] = [2] * len(arrays)
|
| 14 |
+
# floating dtypes
|
| 15 |
+
arrays += [pd.array([0.1, 0.2, 0.3, None], dtype=dtype) for dtype in tm.FLOAT_EA_DTYPES]
|
| 16 |
+
scalars += [0.2, 0.2]
|
| 17 |
+
# boolean
|
| 18 |
+
arrays += [pd.array([True, False, True, None], dtype="boolean")]
|
| 19 |
+
scalars += [False]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@pytest.fixture(params=zip(arrays, scalars), ids=[a.dtype.name for a in arrays])
|
| 23 |
+
def data(request):
|
| 24 |
+
"""Fixture returning parametrized (array, scalar) tuple.
|
| 25 |
+
|
| 26 |
+
Used to test equivalence of scalars, numpy arrays with array ops, and the
|
| 27 |
+
equivalence of DataFrame and Series ops.
|
| 28 |
+
"""
|
| 29 |
+
return request.param
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def check_skip(data, op_name):
|
| 33 |
+
if isinstance(data.dtype, pd.BooleanDtype) and "sub" in op_name:
|
| 34 |
+
pytest.skip("subtract not implemented for boolean")
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def is_bool_not_implemented(data, op_name):
|
| 38 |
+
# match non-masked behavior
|
| 39 |
+
return data.dtype.kind == "b" and op_name.strip("_").lstrip("r") in [
|
| 40 |
+
"pow",
|
| 41 |
+
"truediv",
|
| 42 |
+
"floordiv",
|
| 43 |
+
]
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# Test equivalence of scalars, numpy arrays with array ops
|
| 47 |
+
# -----------------------------------------------------------------------------
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def test_array_scalar_like_equivalence(data, all_arithmetic_operators):
|
| 51 |
+
data, scalar = data
|
| 52 |
+
op = tm.get_op_from_name(all_arithmetic_operators)
|
| 53 |
+
check_skip(data, all_arithmetic_operators)
|
| 54 |
+
|
| 55 |
+
scalar_array = pd.array([scalar] * len(data), dtype=data.dtype)
|
| 56 |
+
|
| 57 |
+
# TODO also add len-1 array (np.array([scalar], dtype=data.dtype.numpy_dtype))
|
| 58 |
+
for scalar in [scalar, data.dtype.type(scalar)]:
|
| 59 |
+
if is_bool_not_implemented(data, all_arithmetic_operators):
|
| 60 |
+
msg = "operator '.*' not implemented for bool dtypes"
|
| 61 |
+
with pytest.raises(NotImplementedError, match=msg):
|
| 62 |
+
op(data, scalar)
|
| 63 |
+
with pytest.raises(NotImplementedError, match=msg):
|
| 64 |
+
op(data, scalar_array)
|
| 65 |
+
else:
|
| 66 |
+
result = op(data, scalar)
|
| 67 |
+
expected = op(data, scalar_array)
|
| 68 |
+
tm.assert_extension_array_equal(result, expected)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def test_array_NA(data, all_arithmetic_operators):
|
| 72 |
+
data, _ = data
|
| 73 |
+
op = tm.get_op_from_name(all_arithmetic_operators)
|
| 74 |
+
check_skip(data, all_arithmetic_operators)
|
| 75 |
+
|
| 76 |
+
scalar = pd.NA
|
| 77 |
+
scalar_array = pd.array([pd.NA] * len(data), dtype=data.dtype)
|
| 78 |
+
|
| 79 |
+
mask = data._mask.copy()
|
| 80 |
+
|
| 81 |
+
if is_bool_not_implemented(data, all_arithmetic_operators):
|
| 82 |
+
msg = "operator '.*' not implemented for bool dtypes"
|
| 83 |
+
with pytest.raises(NotImplementedError, match=msg):
|
| 84 |
+
op(data, scalar)
|
| 85 |
+
# GH#45421 check op doesn't alter data._mask inplace
|
| 86 |
+
tm.assert_numpy_array_equal(mask, data._mask)
|
| 87 |
+
return
|
| 88 |
+
|
| 89 |
+
result = op(data, scalar)
|
| 90 |
+
# GH#45421 check op doesn't alter data._mask inplace
|
| 91 |
+
tm.assert_numpy_array_equal(mask, data._mask)
|
| 92 |
+
|
| 93 |
+
expected = op(data, scalar_array)
|
| 94 |
+
tm.assert_numpy_array_equal(mask, data._mask)
|
| 95 |
+
|
| 96 |
+
tm.assert_extension_array_equal(result, expected)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def test_numpy_array_equivalence(data, all_arithmetic_operators):
|
| 100 |
+
data, scalar = data
|
| 101 |
+
op = tm.get_op_from_name(all_arithmetic_operators)
|
| 102 |
+
check_skip(data, all_arithmetic_operators)
|
| 103 |
+
|
| 104 |
+
numpy_array = np.array([scalar] * len(data), dtype=data.dtype.numpy_dtype)
|
| 105 |
+
pd_array = pd.array(numpy_array, dtype=data.dtype)
|
| 106 |
+
|
| 107 |
+
if is_bool_not_implemented(data, all_arithmetic_operators):
|
| 108 |
+
msg = "operator '.*' not implemented for bool dtypes"
|
| 109 |
+
with pytest.raises(NotImplementedError, match=msg):
|
| 110 |
+
op(data, numpy_array)
|
| 111 |
+
with pytest.raises(NotImplementedError, match=msg):
|
| 112 |
+
op(data, pd_array)
|
| 113 |
+
return
|
| 114 |
+
|
| 115 |
+
result = op(data, numpy_array)
|
| 116 |
+
expected = op(data, pd_array)
|
| 117 |
+
tm.assert_extension_array_equal(result, expected)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
# Test equivalence with Series and DataFrame ops
|
| 121 |
+
# -----------------------------------------------------------------------------
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def test_frame(data, all_arithmetic_operators):
|
| 125 |
+
data, scalar = data
|
| 126 |
+
op = tm.get_op_from_name(all_arithmetic_operators)
|
| 127 |
+
check_skip(data, all_arithmetic_operators)
|
| 128 |
+
|
| 129 |
+
# DataFrame with scalar
|
| 130 |
+
df = pd.DataFrame({"A": data})
|
| 131 |
+
|
| 132 |
+
if is_bool_not_implemented(data, all_arithmetic_operators):
|
| 133 |
+
msg = "operator '.*' not implemented for bool dtypes"
|
| 134 |
+
with pytest.raises(NotImplementedError, match=msg):
|
| 135 |
+
op(df, scalar)
|
| 136 |
+
with pytest.raises(NotImplementedError, match=msg):
|
| 137 |
+
op(data, scalar)
|
| 138 |
+
return
|
| 139 |
+
|
| 140 |
+
result = op(df, scalar)
|
| 141 |
+
expected = pd.DataFrame({"A": op(data, scalar)})
|
| 142 |
+
tm.assert_frame_equal(result, expected)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def test_series(data, all_arithmetic_operators):
|
| 146 |
+
data, scalar = data
|
| 147 |
+
op = tm.get_op_from_name(all_arithmetic_operators)
|
| 148 |
+
check_skip(data, all_arithmetic_operators)
|
| 149 |
+
|
| 150 |
+
ser = pd.Series(data)
|
| 151 |
+
|
| 152 |
+
others = [
|
| 153 |
+
scalar,
|
| 154 |
+
np.array([scalar] * len(data), dtype=data.dtype.numpy_dtype),
|
| 155 |
+
pd.array([scalar] * len(data), dtype=data.dtype),
|
| 156 |
+
pd.Series([scalar] * len(data), dtype=data.dtype),
|
| 157 |
+
]
|
| 158 |
+
|
| 159 |
+
for other in others:
|
| 160 |
+
if is_bool_not_implemented(data, all_arithmetic_operators):
|
| 161 |
+
msg = "operator '.*' not implemented for bool dtypes"
|
| 162 |
+
with pytest.raises(NotImplementedError, match=msg):
|
| 163 |
+
op(ser, other)
|
| 164 |
+
|
| 165 |
+
else:
|
| 166 |
+
result = op(ser, other)
|
| 167 |
+
expected = pd.Series(op(data, other))
|
| 168 |
+
tm.assert_series_equal(result, expected)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
# Test generic characteristics / errors
|
| 172 |
+
# -----------------------------------------------------------------------------
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def test_error_invalid_object(data, all_arithmetic_operators):
|
| 176 |
+
data, _ = data
|
| 177 |
+
|
| 178 |
+
op = all_arithmetic_operators
|
| 179 |
+
opa = getattr(data, op)
|
| 180 |
+
|
| 181 |
+
# 2d -> return NotImplemented
|
| 182 |
+
result = opa(pd.DataFrame({"A": data}))
|
| 183 |
+
assert result is NotImplemented
|
| 184 |
+
|
| 185 |
+
msg = r"can only perform ops with 1-d structures"
|
| 186 |
+
with pytest.raises(NotImplementedError, match=msg):
|
| 187 |
+
opa(np.arange(len(data)).reshape(-1, len(data)))
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def test_error_len_mismatch(data, all_arithmetic_operators):
|
| 191 |
+
# operating with a list-like with non-matching length raises
|
| 192 |
+
data, scalar = data
|
| 193 |
+
op = tm.get_op_from_name(all_arithmetic_operators)
|
| 194 |
+
|
| 195 |
+
other = [scalar] * (len(data) - 1)
|
| 196 |
+
|
| 197 |
+
err = ValueError
|
| 198 |
+
msg = "|".join(
|
| 199 |
+
[
|
| 200 |
+
r"operands could not be broadcast together with shapes \(3,\) \(4,\)",
|
| 201 |
+
r"operands could not be broadcast together with shapes \(4,\) \(3,\)",
|
| 202 |
+
]
|
| 203 |
+
)
|
| 204 |
+
if data.dtype.kind == "b" and all_arithmetic_operators.strip("_") in [
|
| 205 |
+
"sub",
|
| 206 |
+
"rsub",
|
| 207 |
+
]:
|
| 208 |
+
err = TypeError
|
| 209 |
+
msg = (
|
| 210 |
+
r"numpy boolean subtract, the `\-` operator, is not supported, use "
|
| 211 |
+
r"the bitwise_xor, the `\^` operator, or the logical_xor function instead"
|
| 212 |
+
)
|
| 213 |
+
elif is_bool_not_implemented(data, all_arithmetic_operators):
|
| 214 |
+
msg = "operator '.*' not implemented for bool dtypes"
|
| 215 |
+
err = NotImplementedError
|
| 216 |
+
|
| 217 |
+
for other in [other, np.array(other)]:
|
| 218 |
+
with pytest.raises(err, match=msg):
|
| 219 |
+
op(data, other)
|
| 220 |
+
|
| 221 |
+
s = pd.Series(data)
|
| 222 |
+
with pytest.raises(err, match=msg):
|
| 223 |
+
op(s, other)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
@pytest.mark.parametrize("op", ["__neg__", "__abs__", "__invert__"])
|
| 227 |
+
def test_unary_op_does_not_propagate_mask(data, op):
|
| 228 |
+
# https://github.com/pandas-dev/pandas/issues/39943
|
| 229 |
+
data, _ = data
|
| 230 |
+
ser = pd.Series(data)
|
| 231 |
+
|
| 232 |
+
if op == "__invert__" and data.dtype.kind == "f":
|
| 233 |
+
# we follow numpy in raising
|
| 234 |
+
msg = "ufunc 'invert' not supported for the input types"
|
| 235 |
+
with pytest.raises(TypeError, match=msg):
|
| 236 |
+
getattr(ser, op)()
|
| 237 |
+
with pytest.raises(TypeError, match=msg):
|
| 238 |
+
getattr(data, op)()
|
| 239 |
+
with pytest.raises(TypeError, match=msg):
|
| 240 |
+
# Check that this is still the numpy behavior
|
| 241 |
+
getattr(data._data, op)()
|
| 242 |
+
|
| 243 |
+
return
|
| 244 |
+
|
| 245 |
+
result = getattr(ser, op)()
|
| 246 |
+
expected = result.copy(deep=True)
|
| 247 |
+
ser[0] = None
|
| 248 |
+
tm.assert_series_equal(result, expected)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/masked/test_arrow_compat.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ame:DeprecationWarning"
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
pa = pytest.importorskip("pyarrow")
|
| 13 |
+
|
| 14 |
+
from pandas.core.arrays.arrow._arrow_utils import pyarrow_array_to_numpy_and_mask
|
| 15 |
+
|
| 16 |
+
arrays = [pd.array([1, 2, 3, None], dtype=dtype) for dtype in tm.ALL_INT_EA_DTYPES]
|
| 17 |
+
arrays += [pd.array([0.1, 0.2, 0.3, None], dtype=dtype) for dtype in tm.FLOAT_EA_DTYPES]
|
| 18 |
+
arrays += [pd.array([True, False, True, None], dtype="boolean")]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@pytest.fixture(params=arrays, ids=[a.dtype.name for a in arrays])
|
| 22 |
+
def data(request):
|
| 23 |
+
"""
|
| 24 |
+
Fixture returning parametrized array from given dtype, including integer,
|
| 25 |
+
float and boolean
|
| 26 |
+
"""
|
| 27 |
+
return request.param
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def test_arrow_array(data):
|
| 31 |
+
arr = pa.array(data)
|
| 32 |
+
expected = pa.array(
|
| 33 |
+
data.to_numpy(object, na_value=None),
|
| 34 |
+
type=pa.from_numpy_dtype(data.dtype.numpy_dtype),
|
| 35 |
+
)
|
| 36 |
+
assert arr.equals(expected)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def test_arrow_roundtrip(data):
|
| 40 |
+
df = pd.DataFrame({"a": data})
|
| 41 |
+
table = pa.table(df)
|
| 42 |
+
assert table.field("a").type == str(data.dtype.numpy_dtype)
|
| 43 |
+
|
| 44 |
+
result = table.to_pandas()
|
| 45 |
+
assert result["a"].dtype == data.dtype
|
| 46 |
+
tm.assert_frame_equal(result, df)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def test_dataframe_from_arrow_types_mapper():
|
| 50 |
+
def types_mapper(arrow_type):
|
| 51 |
+
if pa.types.is_boolean(arrow_type):
|
| 52 |
+
return pd.BooleanDtype()
|
| 53 |
+
elif pa.types.is_integer(arrow_type):
|
| 54 |
+
return pd.Int64Dtype()
|
| 55 |
+
|
| 56 |
+
bools_array = pa.array([True, None, False], type=pa.bool_())
|
| 57 |
+
ints_array = pa.array([1, None, 2], type=pa.int64())
|
| 58 |
+
small_ints_array = pa.array([-1, 0, 7], type=pa.int8())
|
| 59 |
+
record_batch = pa.RecordBatch.from_arrays(
|
| 60 |
+
[bools_array, ints_array, small_ints_array], ["bools", "ints", "small_ints"]
|
| 61 |
+
)
|
| 62 |
+
result = record_batch.to_pandas(types_mapper=types_mapper)
|
| 63 |
+
bools = pd.Series([True, None, False], dtype="boolean")
|
| 64 |
+
ints = pd.Series([1, None, 2], dtype="Int64")
|
| 65 |
+
small_ints = pd.Series([-1, 0, 7], dtype="Int64")
|
| 66 |
+
expected = pd.DataFrame({"bools": bools, "ints": ints, "small_ints": small_ints})
|
| 67 |
+
tm.assert_frame_equal(result, expected)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def test_arrow_load_from_zero_chunks(data):
|
| 71 |
+
# GH-41040
|
| 72 |
+
|
| 73 |
+
df = pd.DataFrame({"a": data[0:0]})
|
| 74 |
+
table = pa.table(df)
|
| 75 |
+
assert table.field("a").type == str(data.dtype.numpy_dtype)
|
| 76 |
+
table = pa.table(
|
| 77 |
+
[pa.chunked_array([], type=table.field("a").type)], schema=table.schema
|
| 78 |
+
)
|
| 79 |
+
result = table.to_pandas()
|
| 80 |
+
assert result["a"].dtype == data.dtype
|
| 81 |
+
tm.assert_frame_equal(result, df)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def test_arrow_from_arrow_uint():
|
| 85 |
+
# https://github.com/pandas-dev/pandas/issues/31896
|
| 86 |
+
# possible mismatch in types
|
| 87 |
+
|
| 88 |
+
dtype = pd.UInt32Dtype()
|
| 89 |
+
result = dtype.__from_arrow__(pa.array([1, 2, 3, 4, None], type="int64"))
|
| 90 |
+
expected = pd.array([1, 2, 3, 4, None], dtype="UInt32")
|
| 91 |
+
|
| 92 |
+
tm.assert_extension_array_equal(result, expected)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def test_arrow_sliced(data):
|
| 96 |
+
# https://github.com/pandas-dev/pandas/issues/38525
|
| 97 |
+
|
| 98 |
+
df = pd.DataFrame({"a": data})
|
| 99 |
+
table = pa.table(df)
|
| 100 |
+
result = table.slice(2, None).to_pandas()
|
| 101 |
+
expected = df.iloc[2:].reset_index(drop=True)
|
| 102 |
+
tm.assert_frame_equal(result, expected)
|
| 103 |
+
|
| 104 |
+
# no missing values
|
| 105 |
+
df2 = df.fillna(data[0])
|
| 106 |
+
table = pa.table(df2)
|
| 107 |
+
result = table.slice(2, None).to_pandas()
|
| 108 |
+
expected = df2.iloc[2:].reset_index(drop=True)
|
| 109 |
+
tm.assert_frame_equal(result, expected)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@pytest.fixture
|
| 113 |
+
def np_dtype_to_arrays(any_real_numpy_dtype):
|
| 114 |
+
"""
|
| 115 |
+
Fixture returning actual and expected dtype, pandas and numpy arrays and
|
| 116 |
+
mask from a given numpy dtype
|
| 117 |
+
"""
|
| 118 |
+
np_dtype = np.dtype(any_real_numpy_dtype)
|
| 119 |
+
pa_type = pa.from_numpy_dtype(np_dtype)
|
| 120 |
+
|
| 121 |
+
# None ensures the creation of a bitmask buffer.
|
| 122 |
+
pa_array = pa.array([0, 1, 2, None], type=pa_type)
|
| 123 |
+
# Since masked Arrow buffer slots are not required to contain a specific
|
| 124 |
+
# value, assert only the first three values of the created np.array
|
| 125 |
+
np_expected = np.array([0, 1, 2], dtype=np_dtype)
|
| 126 |
+
mask_expected = np.array([True, True, True, False])
|
| 127 |
+
return np_dtype, pa_array, np_expected, mask_expected
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def test_pyarrow_array_to_numpy_and_mask(np_dtype_to_arrays):
|
| 131 |
+
"""
|
| 132 |
+
Test conversion from pyarrow array to numpy array.
|
| 133 |
+
|
| 134 |
+
Modifies the pyarrow buffer to contain padding and offset, which are
|
| 135 |
+
considered valid buffers by pyarrow.
|
| 136 |
+
|
| 137 |
+
Also tests empty pyarrow arrays with non empty buffers.
|
| 138 |
+
See https://github.com/pandas-dev/pandas/issues/40896
|
| 139 |
+
"""
|
| 140 |
+
np_dtype, pa_array, np_expected, mask_expected = np_dtype_to_arrays
|
| 141 |
+
data, mask = pyarrow_array_to_numpy_and_mask(pa_array, np_dtype)
|
| 142 |
+
tm.assert_numpy_array_equal(data[:3], np_expected)
|
| 143 |
+
tm.assert_numpy_array_equal(mask, mask_expected)
|
| 144 |
+
|
| 145 |
+
mask_buffer = pa_array.buffers()[0]
|
| 146 |
+
data_buffer = pa_array.buffers()[1]
|
| 147 |
+
data_buffer_bytes = pa_array.buffers()[1].to_pybytes()
|
| 148 |
+
|
| 149 |
+
# Add trailing padding to the buffer.
|
| 150 |
+
data_buffer_trail = pa.py_buffer(data_buffer_bytes + b"\x00")
|
| 151 |
+
pa_array_trail = pa.Array.from_buffers(
|
| 152 |
+
type=pa_array.type,
|
| 153 |
+
length=len(pa_array),
|
| 154 |
+
buffers=[mask_buffer, data_buffer_trail],
|
| 155 |
+
offset=pa_array.offset,
|
| 156 |
+
)
|
| 157 |
+
pa_array_trail.validate()
|
| 158 |
+
data, mask = pyarrow_array_to_numpy_and_mask(pa_array_trail, np_dtype)
|
| 159 |
+
tm.assert_numpy_array_equal(data[:3], np_expected)
|
| 160 |
+
tm.assert_numpy_array_equal(mask, mask_expected)
|
| 161 |
+
|
| 162 |
+
# Add offset to the buffer.
|
| 163 |
+
offset = b"\x00" * (pa_array.type.bit_width // 8)
|
| 164 |
+
data_buffer_offset = pa.py_buffer(offset + data_buffer_bytes)
|
| 165 |
+
mask_buffer_offset = pa.py_buffer(b"\x0E")
|
| 166 |
+
pa_array_offset = pa.Array.from_buffers(
|
| 167 |
+
type=pa_array.type,
|
| 168 |
+
length=len(pa_array),
|
| 169 |
+
buffers=[mask_buffer_offset, data_buffer_offset],
|
| 170 |
+
offset=pa_array.offset + 1,
|
| 171 |
+
)
|
| 172 |
+
pa_array_offset.validate()
|
| 173 |
+
data, mask = pyarrow_array_to_numpy_and_mask(pa_array_offset, np_dtype)
|
| 174 |
+
tm.assert_numpy_array_equal(data[:3], np_expected)
|
| 175 |
+
tm.assert_numpy_array_equal(mask, mask_expected)
|
| 176 |
+
|
| 177 |
+
# Empty array
|
| 178 |
+
np_expected_empty = np.array([], dtype=np_dtype)
|
| 179 |
+
mask_expected_empty = np.array([], dtype=np.bool_)
|
| 180 |
+
|
| 181 |
+
pa_array_offset = pa.Array.from_buffers(
|
| 182 |
+
type=pa_array.type,
|
| 183 |
+
length=0,
|
| 184 |
+
buffers=[mask_buffer, data_buffer],
|
| 185 |
+
offset=pa_array.offset,
|
| 186 |
+
)
|
| 187 |
+
pa_array_offset.validate()
|
| 188 |
+
data, mask = pyarrow_array_to_numpy_and_mask(pa_array_offset, np_dtype)
|
| 189 |
+
tm.assert_numpy_array_equal(data[:3], np_expected_empty)
|
| 190 |
+
tm.assert_numpy_array_equal(mask, mask_expected_empty)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
@pytest.mark.parametrize(
|
| 194 |
+
"arr", [pa.nulls(10), pa.chunked_array([pa.nulls(4), pa.nulls(6)])]
|
| 195 |
+
)
|
| 196 |
+
def test_from_arrow_null(data, arr):
|
| 197 |
+
res = data.dtype.__from_arrow__(arr)
|
| 198 |
+
assert res.isna().all()
|
| 199 |
+
assert len(res) == 10
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def test_from_arrow_type_error(data):
|
| 203 |
+
# ensure that __from_arrow__ returns a TypeError when getting a wrong
|
| 204 |
+
# array type
|
| 205 |
+
|
| 206 |
+
arr = pa.array(data).cast("string")
|
| 207 |
+
with pytest.raises(TypeError, match=None):
|
| 208 |
+
# we don't test the exact error message, only the fact that it raises
|
| 209 |
+
# a TypeError is relevant
|
| 210 |
+
data.dtype.__from_arrow__(arr)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/masked/test_function.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from pandas.core.dtypes.common import is_integer_dtype
|
| 5 |
+
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import pandas._testing as tm
|
| 8 |
+
from pandas.core.arrays import BaseMaskedArray
|
| 9 |
+
|
| 10 |
+
arrays = [pd.array([1, 2, 3, None], dtype=dtype) for dtype in tm.ALL_INT_EA_DTYPES]
|
| 11 |
+
arrays += [
|
| 12 |
+
pd.array([0.141, -0.268, 5.895, None], dtype=dtype) for dtype in tm.FLOAT_EA_DTYPES
|
| 13 |
+
]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@pytest.fixture(params=arrays, ids=[a.dtype.name for a in arrays])
|
| 17 |
+
def data(request):
|
| 18 |
+
"""
|
| 19 |
+
Fixture returning parametrized 'data' array with different integer and
|
| 20 |
+
floating point types
|
| 21 |
+
"""
|
| 22 |
+
return request.param
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@pytest.fixture()
|
| 26 |
+
def numpy_dtype(data):
|
| 27 |
+
"""
|
| 28 |
+
Fixture returning numpy dtype from 'data' input array.
|
| 29 |
+
"""
|
| 30 |
+
# For integer dtype, the numpy conversion must be done to float
|
| 31 |
+
if is_integer_dtype(data):
|
| 32 |
+
numpy_dtype = float
|
| 33 |
+
else:
|
| 34 |
+
numpy_dtype = data.dtype.type
|
| 35 |
+
return numpy_dtype
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def test_round(data, numpy_dtype):
|
| 39 |
+
# No arguments
|
| 40 |
+
result = data.round()
|
| 41 |
+
expected = pd.array(
|
| 42 |
+
np.round(data.to_numpy(dtype=numpy_dtype, na_value=None)), dtype=data.dtype
|
| 43 |
+
)
|
| 44 |
+
tm.assert_extension_array_equal(result, expected)
|
| 45 |
+
|
| 46 |
+
# Decimals argument
|
| 47 |
+
result = data.round(decimals=2)
|
| 48 |
+
expected = pd.array(
|
| 49 |
+
np.round(data.to_numpy(dtype=numpy_dtype, na_value=None), decimals=2),
|
| 50 |
+
dtype=data.dtype,
|
| 51 |
+
)
|
| 52 |
+
tm.assert_extension_array_equal(result, expected)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def test_tolist(data):
|
| 56 |
+
result = data.tolist()
|
| 57 |
+
expected = list(data)
|
| 58 |
+
tm.assert_equal(result, expected)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def test_to_numpy():
|
| 62 |
+
# GH#56991
|
| 63 |
+
|
| 64 |
+
class MyStringArray(BaseMaskedArray):
|
| 65 |
+
dtype = pd.StringDtype()
|
| 66 |
+
_dtype_cls = pd.StringDtype
|
| 67 |
+
_internal_fill_value = pd.NA
|
| 68 |
+
|
| 69 |
+
arr = MyStringArray(
|
| 70 |
+
values=np.array(["a", "b", "c"]), mask=np.array([False, True, False])
|
| 71 |
+
)
|
| 72 |
+
result = arr.to_numpy()
|
| 73 |
+
expected = np.array(["a", pd.NA, "c"])
|
| 74 |
+
tm.assert_numpy_array_equal(result, expected)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/pandas/tests/arrays/masked/test_indexing.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
import pandas as pd
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class TestSetitemValidation:
|
| 10 |
+
def _check_setitem_invalid(self, arr, invalid):
|
| 11 |
+
msg = f"Invalid value '{invalid!s}' for dtype '{arr.dtype}'"
|
| 12 |
+
msg = re.escape(msg)
|
| 13 |
+
with pytest.raises(TypeError, match=msg):
|
| 14 |
+
arr[0] = invalid
|
| 15 |
+
|
| 16 |
+
with pytest.raises(TypeError, match=msg):
|
| 17 |
+
arr[:] = invalid
|
| 18 |
+
|
| 19 |
+
with pytest.raises(TypeError, match=msg):
|
| 20 |
+
arr[[0]] = invalid
|
| 21 |
+
|
| 22 |
+
# FIXME: don't leave commented-out
|
| 23 |
+
# with pytest.raises(TypeError):
|
| 24 |
+
# arr[[0]] = [invalid]
|
| 25 |
+
|
| 26 |
+
# with pytest.raises(TypeError):
|
| 27 |
+
# arr[[0]] = np.array([invalid], dtype=object)
|
| 28 |
+
|
| 29 |
+
# Series non-coercion, behavior subject to change
|
| 30 |
+
ser = pd.Series(arr)
|
| 31 |
+
with pytest.raises(TypeError, match=msg):
|
| 32 |
+
ser[0] = invalid
|
| 33 |
+
# TODO: so, so many other variants of this...
|
| 34 |
+
|
| 35 |
+
_invalid_scalars = [
|
| 36 |
+
1 + 2j,
|
| 37 |
+
"True",
|
| 38 |
+
"1",
|
| 39 |
+
"1.0",
|
| 40 |
+
pd.NaT,
|
| 41 |
+
np.datetime64("NaT"),
|
| 42 |
+
np.timedelta64("NaT"),
|
| 43 |
+
]
|
| 44 |
+
|
| 45 |
+
@pytest.mark.parametrize(
|
| 46 |
+
"invalid", _invalid_scalars + [1, 1.0, np.int64(1), np.float64(1)]
|
| 47 |
+
)
|
| 48 |
+
def test_setitem_validation_scalar_bool(self, invalid):
|
| 49 |
+
arr = pd.array([True, False, None], dtype="boolean")
|
| 50 |
+
self._check_setitem_invalid(arr, invalid)
|
| 51 |
+
|
| 52 |
+
@pytest.mark.parametrize("invalid", _invalid_scalars + [True, 1.5, np.float64(1.5)])
|
| 53 |
+
def test_setitem_validation_scalar_int(self, invalid, any_int_ea_dtype):
|
| 54 |
+
arr = pd.array([1, 2, None], dtype=any_int_ea_dtype)
|
| 55 |
+
self._check_setitem_invalid(arr, invalid)
|
| 56 |
+
|
| 57 |
+
@pytest.mark.parametrize("invalid", _invalid_scalars + [True])
|
| 58 |
+
def test_setitem_validation_scalar_float(self, invalid, float_ea_dtype):
|
| 59 |
+
arr = pd.array([1, 2, None], dtype=float_ea_dtype)
|
| 60 |
+
self._check_setitem_invalid(arr, invalid)
|