content
stringlengths
1
103k
path
stringlengths
8
216
filename
stringlengths
2
179
language
stringclasses
15 values
size_bytes
int64
2
189k
quality_score
float64
0.5
0.95
complexity
float64
0
1
documentation_ratio
float64
0
1
repository
stringclasses
5 values
stars
int64
0
1k
created_date
stringdate
2023-07-10 19:21:08
2025-07-09 19:11:45
license
stringclasses
4 values
is_test
bool
2 classes
file_hash
stringlengths
32
32
import numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.core.arrays import IntervalArray\n\n\ndef test_arrow_extension_type():\n pa = pytest.importorskip("pyarrow")\n\n from pandas.core.arrays.arrow.extension_types import ArrowIntervalType\n\n p1 = ArrowIntervalType(pa.int64(), "left")\n p2 = ArrowIntervalType(pa.int64(), "left")\n p3 = ArrowIntervalType(pa.int64(), "right")\n\n assert p1.closed == "left"\n assert p1 == p2\n assert p1 != p3\n assert hash(p1) == hash(p2)\n assert hash(p1) != hash(p3)\n\n\ndef test_arrow_array():\n pa = pytest.importorskip("pyarrow")\n\n from pandas.core.arrays.arrow.extension_types import ArrowIntervalType\n\n intervals = pd.interval_range(1, 5, freq=1).array\n\n result = pa.array(intervals)\n assert isinstance(result.type, ArrowIntervalType)\n assert result.type.closed == intervals.closed\n assert result.type.subtype == pa.int64()\n assert result.storage.field("left").equals(pa.array([1, 2, 3, 4], type="int64"))\n assert result.storage.field("right").equals(pa.array([2, 3, 4, 5], type="int64"))\n\n expected = pa.array([{"left": i, "right": i + 1} for i in range(1, 5)])\n assert result.storage.equals(expected)\n\n # convert to its storage type\n result = pa.array(intervals, type=expected.type)\n assert result.equals(expected)\n\n # unsupported conversions\n with pytest.raises(TypeError, match="Not supported to convert IntervalArray"):\n pa.array(intervals, type="float64")\n\n with pytest.raises(TypeError, match="Not supported to convert IntervalArray"):\n pa.array(intervals, type=ArrowIntervalType(pa.float64(), "left"))\n\n\ndef test_arrow_array_missing():\n pa = pytest.importorskip("pyarrow")\n\n from pandas.core.arrays.arrow.extension_types import ArrowIntervalType\n\n arr = IntervalArray.from_breaks([0.0, 1.0, 2.0, 3.0])\n arr[1] = None\n\n result = pa.array(arr)\n assert isinstance(result.type, ArrowIntervalType)\n assert result.type.closed == arr.closed\n assert result.type.subtype == pa.float64()\n\n # fields have missing values (not NaN)\n left = pa.array([0.0, None, 2.0], type="float64")\n right = pa.array([1.0, None, 3.0], type="float64")\n assert result.storage.field("left").equals(left)\n assert result.storage.field("right").equals(right)\n\n # structarray itself also has missing values on the array level\n vals = [\n {"left": 0.0, "right": 1.0},\n {"left": None, "right": None},\n {"left": 2.0, "right": 3.0},\n ]\n expected = pa.StructArray.from_pandas(vals, mask=np.array([False, True, False]))\n assert result.storage.equals(expected)\n\n\n@pytest.mark.filterwarnings(\n "ignore:Passing a BlockManager to DataFrame:DeprecationWarning"\n)\n@pytest.mark.parametrize(\n "breaks",\n [[0.0, 1.0, 2.0, 3.0], pd.date_range("2017", periods=4, freq="D")],\n ids=["float", "datetime64[ns]"],\n)\ndef test_arrow_table_roundtrip(breaks):\n pa = pytest.importorskip("pyarrow")\n\n from pandas.core.arrays.arrow.extension_types import ArrowIntervalType\n\n arr = IntervalArray.from_breaks(breaks)\n arr[1] = None\n df = pd.DataFrame({"a": arr})\n\n table = pa.table(df)\n assert isinstance(table.field("a").type, ArrowIntervalType)\n result = table.to_pandas()\n assert isinstance(result["a"].dtype, pd.IntervalDtype)\n tm.assert_frame_equal(result, df)\n\n table2 = pa.concat_tables([table, table])\n result = table2.to_pandas()\n expected = pd.concat([df, df], ignore_index=True)\n tm.assert_frame_equal(result, expected)\n\n # GH#41040\n table = pa.table(\n [pa.chunked_array([], type=table.column(0).type)], schema=table.schema\n )\n result = table.to_pandas()\n tm.assert_frame_equal(result, expected[0:0])\n\n\n@pytest.mark.filterwarnings(\n "ignore:Passing a BlockManager to DataFrame:DeprecationWarning"\n)\n@pytest.mark.parametrize(\n "breaks",\n [[0.0, 1.0, 2.0, 3.0], pd.date_range("2017", periods=4, freq="D")],\n ids=["float", "datetime64[ns]"],\n)\ndef test_arrow_table_roundtrip_without_metadata(breaks):\n pa = pytest.importorskip("pyarrow")\n\n arr = IntervalArray.from_breaks(breaks)\n arr[1] = None\n df = pd.DataFrame({"a": arr})\n\n table = pa.table(df)\n # remove the metadata\n table = table.replace_schema_metadata()\n assert table.schema.metadata is None\n\n result = table.to_pandas()\n assert isinstance(result["a"].dtype, pd.IntervalDtype)\n tm.assert_frame_equal(result, df)\n\n\ndef test_from_arrow_from_raw_struct_array():\n # in case pyarrow lost the Interval extension type (eg on parquet roundtrip\n # with datetime64[ns] subtype, see GH-45881), still allow conversion\n # from arrow to IntervalArray\n pa = pytest.importorskip("pyarrow")\n\n arr = pa.array([{"left": 0, "right": 1}, {"left": 1, "right": 2}])\n dtype = pd.IntervalDtype(np.dtype("int64"), closed="neither")\n\n result = dtype.__from_arrow__(arr)\n expected = IntervalArray.from_breaks(\n np.array([0, 1, 2], dtype="int64"), closed="neither"\n )\n tm.assert_extension_array_equal(result, expected)\n\n result = dtype.__from_arrow__(pa.chunked_array([arr]))\n tm.assert_extension_array_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\arrays\interval\test_interval_pyarrow.py
test_interval_pyarrow.py
Python
5,202
0.95
0.04375
0.07438
python-kit
673
2024-06-04T00:58:44.484369
BSD-3-Clause
true
580d19171405b41905bfae3187e2f468
"""Tests for Interval-Interval operations, such as overlaps, contains, etc."""\nimport numpy as np\nimport pytest\n\nfrom pandas import (\n Interval,\n IntervalIndex,\n Timedelta,\n Timestamp,\n)\nimport pandas._testing as tm\nfrom pandas.core.arrays import IntervalArray\n\n\n@pytest.fixture(params=[IntervalArray, IntervalIndex])\ndef constructor(request):\n """\n Fixture for testing both interval container classes.\n """\n return request.param\n\n\n@pytest.fixture(\n params=[\n (Timedelta("0 days"), Timedelta("1 day")),\n (Timestamp("2018-01-01"), Timedelta("1 day")),\n (0, 1),\n ],\n ids=lambda x: type(x[0]).__name__,\n)\ndef start_shift(request):\n """\n Fixture for generating intervals of different types from a start value\n and a shift value that can be added to start to generate an endpoint.\n """\n return request.param\n\n\nclass TestOverlaps:\n def test_overlaps_interval(self, constructor, start_shift, closed, other_closed):\n start, shift = start_shift\n interval = Interval(start, start + 3 * shift, other_closed)\n\n # intervals: identical, nested, spanning, partial, adjacent, disjoint\n tuples = [\n (start, start + 3 * shift),\n (start + shift, start + 2 * shift),\n (start - shift, start + 4 * shift),\n (start + 2 * shift, start + 4 * shift),\n (start + 3 * shift, start + 4 * shift),\n (start + 4 * shift, start + 5 * shift),\n ]\n interval_container = constructor.from_tuples(tuples, closed)\n\n adjacent = interval.closed_right and interval_container.closed_left\n expected = np.array([True, True, True, True, adjacent, False])\n result = interval_container.overlaps(interval)\n tm.assert_numpy_array_equal(result, expected)\n\n @pytest.mark.parametrize("other_constructor", [IntervalArray, IntervalIndex])\n def test_overlaps_interval_container(self, constructor, other_constructor):\n # TODO: modify this test when implemented\n interval_container = constructor.from_breaks(range(5))\n other_container = other_constructor.from_breaks(range(5))\n with pytest.raises(NotImplementedError, match="^$"):\n interval_container.overlaps(other_container)\n\n def test_overlaps_na(self, constructor, start_shift):\n """NA values are marked as False"""\n start, shift = start_shift\n interval = Interval(start, start + shift)\n\n tuples = [\n (start, start + shift),\n np.nan,\n (start + 2 * shift, start + 3 * shift),\n ]\n interval_container = constructor.from_tuples(tuples)\n\n expected = np.array([True, False, False])\n result = interval_container.overlaps(interval)\n tm.assert_numpy_array_equal(result, expected)\n\n @pytest.mark.parametrize(\n "other",\n [10, True, "foo", Timedelta("1 day"), Timestamp("2018-01-01")],\n ids=lambda x: type(x).__name__,\n )\n def test_overlaps_invalid_type(self, constructor, other):\n interval_container = constructor.from_breaks(range(5))\n msg = f"`other` must be Interval-like, got {type(other).__name__}"\n with pytest.raises(TypeError, match=msg):\n interval_container.overlaps(other)\n
.venv\Lib\site-packages\pandas\tests\arrays\interval\test_overlaps.py
test_overlaps.py
Python
3,279
0.95
0.107527
0.025316
node-utils
206
2024-02-02T03:54:45.662980
BSD-3-Clause
true
e87819a597919a0402bd3b47f91aa450
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\interval\__pycache__\test_astype.cpython-313.pyc
test_astype.cpython-313.pyc
Other
1,611
0.8
0
0
node-utils
218
2024-03-27T13:01:29.819035
Apache-2.0
true
6bc92c69a020ad5b9cb674c4ad7902d3
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\interval\__pycache__\test_formats.cpython-313.pyc
test_formats.cpython-313.pyc
Other
652
0.8
0
0.153846
react-lib
146
2025-06-11T09:59:34.514549
Apache-2.0
true
c6ccaf45961d204c121e3dc4aae3396f
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\interval\__pycache__\test_interval.cpython-313.pyc
test_interval.cpython-313.pyc
Other
13,840
0.8
0.004808
0
awesome-app
578
2023-08-24T17:43:34.200157
GPL-3.0
true
ca1b52180b6913cb2da5a19915479037
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\interval\__pycache__\test_interval_pyarrow.cpython-313.pyc
test_interval_pyarrow.cpython-313.pyc
Other
9,042
0.95
0
0.05
node-utils
26
2023-11-22T00:54:33.545004
Apache-2.0
true
6fdbca79df5aad01d91a0b434f41e9a0
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\interval\__pycache__\test_overlaps.cpython-313.pyc
test_overlaps.cpython-313.pyc
Other
5,252
0.8
0.044118
0
awesome-app
221
2024-10-31T20:58:01.212697
BSD-3-Clause
true
2cd4c6da731ef8d2b781b004b50f19fd
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\interval\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
203
0.7
0
0
node-utils
904
2025-06-01T10:06:43.344598
BSD-3-Clause
true
d698cd90bb1e61d518458dae27d838df
from __future__ import annotations\n\nfrom typing import Any\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\n\n# integer dtypes\narrays = [pd.array([1, 2, 3, None], dtype=dtype) for dtype in tm.ALL_INT_EA_DTYPES]\nscalars: list[Any] = [2] * len(arrays)\n# floating dtypes\narrays += [pd.array([0.1, 0.2, 0.3, None], dtype=dtype) for dtype in tm.FLOAT_EA_DTYPES]\nscalars += [0.2, 0.2]\n# boolean\narrays += [pd.array([True, False, True, None], dtype="boolean")]\nscalars += [False]\n\n\n@pytest.fixture(params=zip(arrays, scalars), ids=[a.dtype.name for a in arrays])\ndef data(request):\n """Fixture returning parametrized (array, scalar) tuple.\n\n Used to test equivalence of scalars, numpy arrays with array ops, and the\n equivalence of DataFrame and Series ops.\n """\n return request.param\n\n\ndef check_skip(data, op_name):\n if isinstance(data.dtype, pd.BooleanDtype) and "sub" in op_name:\n pytest.skip("subtract not implemented for boolean")\n\n\ndef is_bool_not_implemented(data, op_name):\n # match non-masked behavior\n return data.dtype.kind == "b" and op_name.strip("_").lstrip("r") in [\n "pow",\n "truediv",\n "floordiv",\n ]\n\n\n# Test equivalence of scalars, numpy arrays with array ops\n# -----------------------------------------------------------------------------\n\n\ndef test_array_scalar_like_equivalence(data, all_arithmetic_operators):\n data, scalar = data\n op = tm.get_op_from_name(all_arithmetic_operators)\n check_skip(data, all_arithmetic_operators)\n\n scalar_array = pd.array([scalar] * len(data), dtype=data.dtype)\n\n # TODO also add len-1 array (np.array([scalar], dtype=data.dtype.numpy_dtype))\n for scalar in [scalar, data.dtype.type(scalar)]:\n if is_bool_not_implemented(data, all_arithmetic_operators):\n msg = "operator '.*' not implemented for bool dtypes"\n with pytest.raises(NotImplementedError, match=msg):\n op(data, scalar)\n with pytest.raises(NotImplementedError, match=msg):\n op(data, scalar_array)\n else:\n result = op(data, scalar)\n expected = op(data, scalar_array)\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_array_NA(data, all_arithmetic_operators):\n data, _ = data\n op = tm.get_op_from_name(all_arithmetic_operators)\n check_skip(data, all_arithmetic_operators)\n\n scalar = pd.NA\n scalar_array = pd.array([pd.NA] * len(data), dtype=data.dtype)\n\n mask = data._mask.copy()\n\n if is_bool_not_implemented(data, all_arithmetic_operators):\n msg = "operator '.*' not implemented for bool dtypes"\n with pytest.raises(NotImplementedError, match=msg):\n op(data, scalar)\n # GH#45421 check op doesn't alter data._mask inplace\n tm.assert_numpy_array_equal(mask, data._mask)\n return\n\n result = op(data, scalar)\n # GH#45421 check op doesn't alter data._mask inplace\n tm.assert_numpy_array_equal(mask, data._mask)\n\n expected = op(data, scalar_array)\n tm.assert_numpy_array_equal(mask, data._mask)\n\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_numpy_array_equivalence(data, all_arithmetic_operators):\n data, scalar = data\n op = tm.get_op_from_name(all_arithmetic_operators)\n check_skip(data, all_arithmetic_operators)\n\n numpy_array = np.array([scalar] * len(data), dtype=data.dtype.numpy_dtype)\n pd_array = pd.array(numpy_array, dtype=data.dtype)\n\n if is_bool_not_implemented(data, all_arithmetic_operators):\n msg = "operator '.*' not implemented for bool dtypes"\n with pytest.raises(NotImplementedError, match=msg):\n op(data, numpy_array)\n with pytest.raises(NotImplementedError, match=msg):\n op(data, pd_array)\n return\n\n result = op(data, numpy_array)\n expected = op(data, pd_array)\n tm.assert_extension_array_equal(result, expected)\n\n\n# Test equivalence with Series and DataFrame ops\n# -----------------------------------------------------------------------------\n\n\ndef test_frame(data, all_arithmetic_operators):\n data, scalar = data\n op = tm.get_op_from_name(all_arithmetic_operators)\n check_skip(data, all_arithmetic_operators)\n\n # DataFrame with scalar\n df = pd.DataFrame({"A": data})\n\n if is_bool_not_implemented(data, all_arithmetic_operators):\n msg = "operator '.*' not implemented for bool dtypes"\n with pytest.raises(NotImplementedError, match=msg):\n op(df, scalar)\n with pytest.raises(NotImplementedError, match=msg):\n op(data, scalar)\n return\n\n result = op(df, scalar)\n expected = pd.DataFrame({"A": op(data, scalar)})\n tm.assert_frame_equal(result, expected)\n\n\ndef test_series(data, all_arithmetic_operators):\n data, scalar = data\n op = tm.get_op_from_name(all_arithmetic_operators)\n check_skip(data, all_arithmetic_operators)\n\n ser = pd.Series(data)\n\n others = [\n scalar,\n np.array([scalar] * len(data), dtype=data.dtype.numpy_dtype),\n pd.array([scalar] * len(data), dtype=data.dtype),\n pd.Series([scalar] * len(data), dtype=data.dtype),\n ]\n\n for other in others:\n if is_bool_not_implemented(data, all_arithmetic_operators):\n msg = "operator '.*' not implemented for bool dtypes"\n with pytest.raises(NotImplementedError, match=msg):\n op(ser, other)\n\n else:\n result = op(ser, other)\n expected = pd.Series(op(data, other))\n tm.assert_series_equal(result, expected)\n\n\n# Test generic characteristics / errors\n# -----------------------------------------------------------------------------\n\n\ndef test_error_invalid_object(data, all_arithmetic_operators):\n data, _ = data\n\n op = all_arithmetic_operators\n opa = getattr(data, op)\n\n # 2d -> return NotImplemented\n result = opa(pd.DataFrame({"A": data}))\n assert result is NotImplemented\n\n msg = r"can only perform ops with 1-d structures"\n with pytest.raises(NotImplementedError, match=msg):\n opa(np.arange(len(data)).reshape(-1, len(data)))\n\n\ndef test_error_len_mismatch(data, all_arithmetic_operators):\n # operating with a list-like with non-matching length raises\n data, scalar = data\n op = tm.get_op_from_name(all_arithmetic_operators)\n\n other = [scalar] * (len(data) - 1)\n\n err = ValueError\n msg = "|".join(\n [\n r"operands could not be broadcast together with shapes \(3,\) \(4,\)",\n r"operands could not be broadcast together with shapes \(4,\) \(3,\)",\n ]\n )\n if data.dtype.kind == "b" and all_arithmetic_operators.strip("_") in [\n "sub",\n "rsub",\n ]:\n err = TypeError\n msg = (\n r"numpy boolean subtract, the `\-` operator, is not supported, use "\n r"the bitwise_xor, the `\^` operator, or the logical_xor function instead"\n )\n elif is_bool_not_implemented(data, all_arithmetic_operators):\n msg = "operator '.*' not implemented for bool dtypes"\n err = NotImplementedError\n\n for other in [other, np.array(other)]:\n with pytest.raises(err, match=msg):\n op(data, other)\n\n s = pd.Series(data)\n with pytest.raises(err, match=msg):\n op(s, other)\n\n\n@pytest.mark.parametrize("op", ["__neg__", "__abs__", "__invert__"])\ndef test_unary_op_does_not_propagate_mask(data, op):\n # https://github.com/pandas-dev/pandas/issues/39943\n data, _ = data\n ser = pd.Series(data)\n\n if op == "__invert__" and data.dtype.kind == "f":\n # we follow numpy in raising\n msg = "ufunc 'invert' not supported for the input types"\n with pytest.raises(TypeError, match=msg):\n getattr(ser, op)()\n with pytest.raises(TypeError, match=msg):\n getattr(data, op)()\n with pytest.raises(TypeError, match=msg):\n # Check that this is still the numpy behavior\n getattr(data._data, op)()\n\n return\n\n result = getattr(ser, op)()\n expected = result.copy(deep=True)\n ser[0] = None\n tm.assert_series_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\arrays\masked\test_arithmetic.py
test_arithmetic.py
Python
8,175
0.95
0.137097
0.101604
react-lib
771
2025-05-25T21:21:28.542142
GPL-3.0
true
aadd03def35e1cc2c2f12f50e7fa0156
import numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\n\npytestmark = pytest.mark.filterwarnings(\n "ignore:Passing a BlockManager to DataFrame:DeprecationWarning"\n)\n\n\npa = pytest.importorskip("pyarrow")\n\nfrom pandas.core.arrays.arrow._arrow_utils import pyarrow_array_to_numpy_and_mask\n\narrays = [pd.array([1, 2, 3, None], dtype=dtype) for dtype in tm.ALL_INT_EA_DTYPES]\narrays += [pd.array([0.1, 0.2, 0.3, None], dtype=dtype) for dtype in tm.FLOAT_EA_DTYPES]\narrays += [pd.array([True, False, True, None], dtype="boolean")]\n\n\n@pytest.fixture(params=arrays, ids=[a.dtype.name for a in arrays])\ndef data(request):\n """\n Fixture returning parametrized array from given dtype, including integer,\n float and boolean\n """\n return request.param\n\n\ndef test_arrow_array(data):\n arr = pa.array(data)\n expected = pa.array(\n data.to_numpy(object, na_value=None),\n type=pa.from_numpy_dtype(data.dtype.numpy_dtype),\n )\n assert arr.equals(expected)\n\n\ndef test_arrow_roundtrip(data):\n df = pd.DataFrame({"a": data})\n table = pa.table(df)\n assert table.field("a").type == str(data.dtype.numpy_dtype)\n\n result = table.to_pandas()\n assert result["a"].dtype == data.dtype\n tm.assert_frame_equal(result, df)\n\n\ndef test_dataframe_from_arrow_types_mapper():\n def types_mapper(arrow_type):\n if pa.types.is_boolean(arrow_type):\n return pd.BooleanDtype()\n elif pa.types.is_integer(arrow_type):\n return pd.Int64Dtype()\n\n bools_array = pa.array([True, None, False], type=pa.bool_())\n ints_array = pa.array([1, None, 2], type=pa.int64())\n small_ints_array = pa.array([-1, 0, 7], type=pa.int8())\n record_batch = pa.RecordBatch.from_arrays(\n [bools_array, ints_array, small_ints_array], ["bools", "ints", "small_ints"]\n )\n result = record_batch.to_pandas(types_mapper=types_mapper)\n bools = pd.Series([True, None, False], dtype="boolean")\n ints = pd.Series([1, None, 2], dtype="Int64")\n small_ints = pd.Series([-1, 0, 7], dtype="Int64")\n expected = pd.DataFrame({"bools": bools, "ints": ints, "small_ints": small_ints})\n tm.assert_frame_equal(result, expected)\n\n\ndef test_arrow_load_from_zero_chunks(data):\n # GH-41040\n\n df = pd.DataFrame({"a": data[0:0]})\n table = pa.table(df)\n assert table.field("a").type == str(data.dtype.numpy_dtype)\n table = pa.table(\n [pa.chunked_array([], type=table.field("a").type)], schema=table.schema\n )\n result = table.to_pandas()\n assert result["a"].dtype == data.dtype\n tm.assert_frame_equal(result, df)\n\n\ndef test_arrow_from_arrow_uint():\n # https://github.com/pandas-dev/pandas/issues/31896\n # possible mismatch in types\n\n dtype = pd.UInt32Dtype()\n result = dtype.__from_arrow__(pa.array([1, 2, 3, 4, None], type="int64"))\n expected = pd.array([1, 2, 3, 4, None], dtype="UInt32")\n\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_arrow_sliced(data):\n # https://github.com/pandas-dev/pandas/issues/38525\n\n df = pd.DataFrame({"a": data})\n table = pa.table(df)\n result = table.slice(2, None).to_pandas()\n expected = df.iloc[2:].reset_index(drop=True)\n tm.assert_frame_equal(result, expected)\n\n # no missing values\n df2 = df.fillna(data[0])\n table = pa.table(df2)\n result = table.slice(2, None).to_pandas()\n expected = df2.iloc[2:].reset_index(drop=True)\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.fixture\ndef np_dtype_to_arrays(any_real_numpy_dtype):\n """\n Fixture returning actual and expected dtype, pandas and numpy arrays and\n mask from a given numpy dtype\n """\n np_dtype = np.dtype(any_real_numpy_dtype)\n pa_type = pa.from_numpy_dtype(np_dtype)\n\n # None ensures the creation of a bitmask buffer.\n pa_array = pa.array([0, 1, 2, None], type=pa_type)\n # Since masked Arrow buffer slots are not required to contain a specific\n # value, assert only the first three values of the created np.array\n np_expected = np.array([0, 1, 2], dtype=np_dtype)\n mask_expected = np.array([True, True, True, False])\n return np_dtype, pa_array, np_expected, mask_expected\n\n\ndef test_pyarrow_array_to_numpy_and_mask(np_dtype_to_arrays):\n """\n Test conversion from pyarrow array to numpy array.\n\n Modifies the pyarrow buffer to contain padding and offset, which are\n considered valid buffers by pyarrow.\n\n Also tests empty pyarrow arrays with non empty buffers.\n See https://github.com/pandas-dev/pandas/issues/40896\n """\n np_dtype, pa_array, np_expected, mask_expected = np_dtype_to_arrays\n data, mask = pyarrow_array_to_numpy_and_mask(pa_array, np_dtype)\n tm.assert_numpy_array_equal(data[:3], np_expected)\n tm.assert_numpy_array_equal(mask, mask_expected)\n\n mask_buffer = pa_array.buffers()[0]\n data_buffer = pa_array.buffers()[1]\n data_buffer_bytes = pa_array.buffers()[1].to_pybytes()\n\n # Add trailing padding to the buffer.\n data_buffer_trail = pa.py_buffer(data_buffer_bytes + b"\x00")\n pa_array_trail = pa.Array.from_buffers(\n type=pa_array.type,\n length=len(pa_array),\n buffers=[mask_buffer, data_buffer_trail],\n offset=pa_array.offset,\n )\n pa_array_trail.validate()\n data, mask = pyarrow_array_to_numpy_and_mask(pa_array_trail, np_dtype)\n tm.assert_numpy_array_equal(data[:3], np_expected)\n tm.assert_numpy_array_equal(mask, mask_expected)\n\n # Add offset to the buffer.\n offset = b"\x00" * (pa_array.type.bit_width // 8)\n data_buffer_offset = pa.py_buffer(offset + data_buffer_bytes)\n mask_buffer_offset = pa.py_buffer(b"\x0E")\n pa_array_offset = pa.Array.from_buffers(\n type=pa_array.type,\n length=len(pa_array),\n buffers=[mask_buffer_offset, data_buffer_offset],\n offset=pa_array.offset + 1,\n )\n pa_array_offset.validate()\n data, mask = pyarrow_array_to_numpy_and_mask(pa_array_offset, np_dtype)\n tm.assert_numpy_array_equal(data[:3], np_expected)\n tm.assert_numpy_array_equal(mask, mask_expected)\n\n # Empty array\n np_expected_empty = np.array([], dtype=np_dtype)\n mask_expected_empty = np.array([], dtype=np.bool_)\n\n pa_array_offset = pa.Array.from_buffers(\n type=pa_array.type,\n length=0,\n buffers=[mask_buffer, data_buffer],\n offset=pa_array.offset,\n )\n pa_array_offset.validate()\n data, mask = pyarrow_array_to_numpy_and_mask(pa_array_offset, np_dtype)\n tm.assert_numpy_array_equal(data[:3], np_expected_empty)\n tm.assert_numpy_array_equal(mask, mask_expected_empty)\n\n\n@pytest.mark.parametrize(\n "arr", [pa.nulls(10), pa.chunked_array([pa.nulls(4), pa.nulls(6)])]\n)\ndef test_from_arrow_null(data, arr):\n res = data.dtype.__from_arrow__(arr)\n assert res.isna().all()\n assert len(res) == 10\n\n\ndef test_from_arrow_type_error(data):\n # ensure that __from_arrow__ returns a TypeError when getting a wrong\n # array type\n\n arr = pa.array(data).cast("string")\n with pytest.raises(TypeError, match=None):\n # we don't test the exact error message, only the fact that it raises\n # a TypeError is relevant\n data.dtype.__from_arrow__(arr)\n
.venv\Lib\site-packages\pandas\tests\arrays\masked\test_arrow_compat.py
test_arrow_compat.py
Python
7,194
0.95
0.07619
0.090361
awesome-app
170
2024-05-19T19:01:23.403195
MIT
true
e57cc06c74c1d9c7eb8b9ba5bea671c9
import numpy as np\nimport pytest\n\nfrom pandas.core.dtypes.common import is_integer_dtype\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.core.arrays import BaseMaskedArray\n\narrays = [pd.array([1, 2, 3, None], dtype=dtype) for dtype in tm.ALL_INT_EA_DTYPES]\narrays += [\n pd.array([0.141, -0.268, 5.895, None], dtype=dtype) for dtype in tm.FLOAT_EA_DTYPES\n]\n\n\n@pytest.fixture(params=arrays, ids=[a.dtype.name for a in arrays])\ndef data(request):\n """\n Fixture returning parametrized 'data' array with different integer and\n floating point types\n """\n return request.param\n\n\n@pytest.fixture()\ndef numpy_dtype(data):\n """\n Fixture returning numpy dtype from 'data' input array.\n """\n # For integer dtype, the numpy conversion must be done to float\n if is_integer_dtype(data):\n numpy_dtype = float\n else:\n numpy_dtype = data.dtype.type\n return numpy_dtype\n\n\ndef test_round(data, numpy_dtype):\n # No arguments\n result = data.round()\n expected = pd.array(\n np.round(data.to_numpy(dtype=numpy_dtype, na_value=None)), dtype=data.dtype\n )\n tm.assert_extension_array_equal(result, expected)\n\n # Decimals argument\n result = data.round(decimals=2)\n expected = pd.array(\n np.round(data.to_numpy(dtype=numpy_dtype, na_value=None), decimals=2),\n dtype=data.dtype,\n )\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_tolist(data):\n result = data.tolist()\n expected = list(data)\n tm.assert_equal(result, expected)\n\n\ndef test_to_numpy():\n # GH#56991\n\n class MyStringArray(BaseMaskedArray):\n dtype = pd.StringDtype()\n _dtype_cls = pd.StringDtype\n _internal_fill_value = pd.NA\n\n arr = MyStringArray(\n values=np.array(["a", "b", "c"]), mask=np.array([False, True, False])\n )\n result = arr.to_numpy()\n expected = np.array(["a", pd.NA, "c"])\n tm.assert_numpy_array_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\arrays\masked\test_function.py
test_function.py
Python
1,954
0.95
0.135135
0.068966
python-kit
559
2024-08-11T01:41:28.944078
BSD-3-Clause
true
23b88595ecda9da4a7e7931396f02862
import re\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\n\n\nclass TestSetitemValidation:\n def _check_setitem_invalid(self, arr, invalid):\n msg = f"Invalid value '{invalid!s}' for dtype '{arr.dtype}'"\n msg = re.escape(msg)\n with pytest.raises(TypeError, match=msg):\n arr[0] = invalid\n\n with pytest.raises(TypeError, match=msg):\n arr[:] = invalid\n\n with pytest.raises(TypeError, match=msg):\n arr[[0]] = invalid\n\n # FIXME: don't leave commented-out\n # with pytest.raises(TypeError):\n # arr[[0]] = [invalid]\n\n # with pytest.raises(TypeError):\n # arr[[0]] = np.array([invalid], dtype=object)\n\n # Series non-coercion, behavior subject to change\n ser = pd.Series(arr)\n with pytest.raises(TypeError, match=msg):\n ser[0] = invalid\n # TODO: so, so many other variants of this...\n\n _invalid_scalars = [\n 1 + 2j,\n "True",\n "1",\n "1.0",\n pd.NaT,\n np.datetime64("NaT"),\n np.timedelta64("NaT"),\n ]\n\n @pytest.mark.parametrize(\n "invalid", _invalid_scalars + [1, 1.0, np.int64(1), np.float64(1)]\n )\n def test_setitem_validation_scalar_bool(self, invalid):\n arr = pd.array([True, False, None], dtype="boolean")\n self._check_setitem_invalid(arr, invalid)\n\n @pytest.mark.parametrize("invalid", _invalid_scalars + [True, 1.5, np.float64(1.5)])\n def test_setitem_validation_scalar_int(self, invalid, any_int_ea_dtype):\n arr = pd.array([1, 2, None], dtype=any_int_ea_dtype)\n self._check_setitem_invalid(arr, invalid)\n\n @pytest.mark.parametrize("invalid", _invalid_scalars + [True])\n def test_setitem_validation_scalar_float(self, invalid, float_ea_dtype):\n arr = pd.array([1, 2, None], dtype=float_ea_dtype)\n self._check_setitem_invalid(arr, invalid)\n
.venv\Lib\site-packages\pandas\tests\arrays\masked\test_indexing.py
test_indexing.py
Python
1,915
0.95
0.1
0.148936
node-utils
758
2024-02-20T07:00:54.263764
GPL-3.0
true
f238c2ff04b72b636aac5d0e1c31758c
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\masked\__pycache__\test_arithmetic.cpython-313.pyc
test_arithmetic.cpython-313.pyc
Other
11,763
0.95
0.030303
0.047619
vue-tools
576
2024-03-27T00:45:25.328220
BSD-3-Clause
true
dcc9721e33bb1bc73489847b5bc28590
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\masked\__pycache__\test_arrow_compat.cpython-313.pyc
test_arrow_compat.cpython-313.pyc
Other
11,819
0.95
0
0.054264
awesome-app
102
2024-02-25T17:01:21.534559
GPL-3.0
true
73aa08ede7b265689646c977d2da6e73
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\masked\__pycache__\test_function.cpython-313.pyc
test_function.cpython-313.pyc
Other
3,825
0.95
0
0.027778
node-utils
621
2025-06-09T13:20:53.393528
BSD-3-Clause
true
025d4890ad1010ceff1c56441b5cf77c
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\masked\__pycache__\test_indexing.cpython-313.pyc
test_indexing.cpython-313.pyc
Other
3,446
0.8
0.02381
0
vue-tools
497
2024-01-21T08:21:48.621926
BSD-3-Clause
true
96a9107622e2054a482702582778d783
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\masked\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
201
0.7
0
0
react-lib
871
2024-06-23T01:15:13.174962
GPL-3.0
true
77e9262d1b134dccb2fa606356961388
import numpy as np\n\nfrom pandas.core.dtypes.common import is_scalar\n\nimport pandas as pd\nimport pandas._testing as tm\n\n\nclass TestSearchsorted:\n def test_searchsorted_string(self, string_dtype):\n arr = pd.array(["a", "b", "c"], dtype=string_dtype)\n\n result = arr.searchsorted("a", side="left")\n assert is_scalar(result)\n assert result == 0\n\n result = arr.searchsorted("a", side="right")\n assert is_scalar(result)\n assert result == 1\n\n def test_searchsorted_numeric_dtypes_scalar(self, any_real_numpy_dtype):\n arr = pd.array([1, 3, 90], dtype=any_real_numpy_dtype)\n result = arr.searchsorted(30)\n assert is_scalar(result)\n assert result == 2\n\n result = arr.searchsorted([30])\n expected = np.array([2], dtype=np.intp)\n tm.assert_numpy_array_equal(result, expected)\n\n def test_searchsorted_numeric_dtypes_vector(self, any_real_numpy_dtype):\n arr = pd.array([1, 3, 90], dtype=any_real_numpy_dtype)\n result = arr.searchsorted([2, 30])\n expected = np.array([1, 2], dtype=np.intp)\n tm.assert_numpy_array_equal(result, expected)\n\n def test_searchsorted_sorter(self, any_real_numpy_dtype):\n arr = pd.array([3, 1, 2], dtype=any_real_numpy_dtype)\n result = arr.searchsorted([0, 3], sorter=np.argsort(arr))\n expected = np.array([0, 2], dtype=np.intp)\n tm.assert_numpy_array_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\arrays\numpy_\test_indexing.py
test_indexing.py
Python
1,452
0.85
0.121951
0
node-utils
476
2024-07-01T18:53:53.782830
BSD-3-Clause
true
e2a91c89fc53dc58fa6870752a037406
"""\nAdditional tests for NumpyExtensionArray that aren't covered by\nthe interface tests.\n"""\nimport numpy as np\nimport pytest\n\nfrom pandas.core.dtypes.dtypes import NumpyEADtype\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.arrays import NumpyExtensionArray\n\n\n@pytest.fixture(\n params=[\n np.array(["a", "b"], dtype=object),\n np.array([0, 1], dtype=float),\n np.array([0, 1], dtype=int),\n np.array([0, 1 + 2j], dtype=complex),\n np.array([True, False], dtype=bool),\n np.array([0, 1], dtype="datetime64[ns]"),\n np.array([0, 1], dtype="timedelta64[ns]"),\n ],\n)\ndef any_numpy_array(request):\n """\n Parametrized fixture for NumPy arrays with different dtypes.\n\n This excludes string and bytes.\n """\n return request.param.copy()\n\n\n# ----------------------------------------------------------------------------\n# NumpyEADtype\n\n\n@pytest.mark.parametrize(\n "dtype, expected",\n [\n ("bool", True),\n ("int", True),\n ("uint", True),\n ("float", True),\n ("complex", True),\n ("str", False),\n ("bytes", False),\n ("datetime64[ns]", False),\n ("object", False),\n ("void", False),\n ],\n)\ndef test_is_numeric(dtype, expected):\n dtype = NumpyEADtype(dtype)\n assert dtype._is_numeric is expected\n\n\n@pytest.mark.parametrize(\n "dtype, expected",\n [\n ("bool", True),\n ("int", False),\n ("uint", False),\n ("float", False),\n ("complex", False),\n ("str", False),\n ("bytes", False),\n ("datetime64[ns]", False),\n ("object", False),\n ("void", False),\n ],\n)\ndef test_is_boolean(dtype, expected):\n dtype = NumpyEADtype(dtype)\n assert dtype._is_boolean is expected\n\n\ndef test_repr():\n dtype = NumpyEADtype(np.dtype("int64"))\n assert repr(dtype) == "NumpyEADtype('int64')"\n\n\ndef test_constructor_from_string():\n result = NumpyEADtype.construct_from_string("int64")\n expected = NumpyEADtype(np.dtype("int64"))\n assert result == expected\n\n\ndef test_dtype_idempotent(any_numpy_dtype):\n dtype = NumpyEADtype(any_numpy_dtype)\n\n result = NumpyEADtype(dtype)\n assert result == dtype\n\n\n# ----------------------------------------------------------------------------\n# Construction\n\n\ndef test_constructor_no_coercion():\n with pytest.raises(ValueError, match="NumPy array"):\n NumpyExtensionArray([1, 2, 3])\n\n\ndef test_series_constructor_with_copy():\n ndarray = np.array([1, 2, 3])\n ser = pd.Series(NumpyExtensionArray(ndarray), copy=True)\n\n assert ser.values is not ndarray\n\n\ndef test_series_constructor_with_astype():\n ndarray = np.array([1, 2, 3])\n result = pd.Series(NumpyExtensionArray(ndarray), dtype="float64")\n expected = pd.Series([1.0, 2.0, 3.0], dtype="float64")\n tm.assert_series_equal(result, expected)\n\n\ndef test_from_sequence_dtype():\n arr = np.array([1, 2, 3], dtype="int64")\n result = NumpyExtensionArray._from_sequence(arr, dtype="uint64")\n expected = NumpyExtensionArray(np.array([1, 2, 3], dtype="uint64"))\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_constructor_copy():\n arr = np.array([0, 1])\n result = NumpyExtensionArray(arr, copy=True)\n\n assert not tm.shares_memory(result, arr)\n\n\ndef test_constructor_with_data(any_numpy_array):\n nparr = any_numpy_array\n arr = NumpyExtensionArray(nparr)\n assert arr.dtype.numpy_dtype == nparr.dtype\n\n\n# ----------------------------------------------------------------------------\n# Conversion\n\n\ndef test_to_numpy():\n arr = NumpyExtensionArray(np.array([1, 2, 3]))\n result = arr.to_numpy()\n assert result is arr._ndarray\n\n result = arr.to_numpy(copy=True)\n assert result is not arr._ndarray\n\n result = arr.to_numpy(dtype="f8")\n expected = np.array([1, 2, 3], dtype="f8")\n tm.assert_numpy_array_equal(result, expected)\n\n\n# ----------------------------------------------------------------------------\n# Setitem\n\n\ndef test_setitem_series():\n ser = pd.Series([1, 2, 3])\n ser.array[0] = 10\n expected = pd.Series([10, 2, 3])\n tm.assert_series_equal(ser, expected)\n\n\ndef test_setitem(any_numpy_array):\n nparr = any_numpy_array\n arr = NumpyExtensionArray(nparr, copy=True)\n\n arr[0] = arr[1]\n nparr[0] = nparr[1]\n\n tm.assert_numpy_array_equal(arr.to_numpy(), nparr)\n\n\n# ----------------------------------------------------------------------------\n# Reductions\n\n\ndef test_bad_reduce_raises():\n arr = np.array([1, 2, 3], dtype="int64")\n arr = NumpyExtensionArray(arr)\n msg = "cannot perform not_a_method with type int"\n with pytest.raises(TypeError, match=msg):\n arr._reduce(msg)\n\n\ndef test_validate_reduction_keyword_args():\n arr = NumpyExtensionArray(np.array([1, 2, 3]))\n msg = "the 'keepdims' parameter is not supported .*all"\n with pytest.raises(ValueError, match=msg):\n arr.all(keepdims=True)\n\n\ndef test_np_max_nested_tuples():\n # case where checking in ufunc.nout works while checking for tuples\n # does not\n vals = [\n (("j", "k"), ("l", "m")),\n (("l", "m"), ("o", "p")),\n (("o", "p"), ("j", "k")),\n ]\n ser = pd.Series(vals)\n arr = ser.array\n\n assert arr.max() is arr[2]\n assert ser.max() is arr[2]\n\n result = np.maximum.reduce(arr)\n assert result == arr[2]\n\n result = np.maximum.reduce(ser)\n assert result == arr[2]\n\n\ndef test_np_reduce_2d():\n raw = np.arange(12).reshape(4, 3)\n arr = NumpyExtensionArray(raw)\n\n res = np.maximum.reduce(arr, axis=0)\n tm.assert_extension_array_equal(res, arr[-1])\n\n alt = arr.max(axis=0)\n tm.assert_extension_array_equal(alt, arr[-1])\n\n\n# ----------------------------------------------------------------------------\n# Ops\n\n\n@pytest.mark.parametrize("ufunc", [np.abs, np.negative, np.positive])\ndef test_ufunc_unary(ufunc):\n arr = NumpyExtensionArray(np.array([-1.0, 0.0, 1.0]))\n result = ufunc(arr)\n expected = NumpyExtensionArray(ufunc(arr._ndarray))\n tm.assert_extension_array_equal(result, expected)\n\n # same thing but with the 'out' keyword\n out = NumpyExtensionArray(np.array([-9.0, -9.0, -9.0]))\n ufunc(arr, out=out)\n tm.assert_extension_array_equal(out, expected)\n\n\ndef test_ufunc():\n arr = NumpyExtensionArray(np.array([-1.0, 0.0, 1.0]))\n\n r1, r2 = np.divmod(arr, np.add(arr, 2))\n e1, e2 = np.divmod(arr._ndarray, np.add(arr._ndarray, 2))\n e1 = NumpyExtensionArray(e1)\n e2 = NumpyExtensionArray(e2)\n tm.assert_extension_array_equal(r1, e1)\n tm.assert_extension_array_equal(r2, e2)\n\n\ndef test_basic_binop():\n # Just a basic smoke test. The EA interface tests exercise this\n # more thoroughly.\n x = NumpyExtensionArray(np.array([1, 2, 3]))\n result = x + x\n expected = NumpyExtensionArray(np.array([2, 4, 6]))\n tm.assert_extension_array_equal(result, expected)\n\n\n@pytest.mark.parametrize("dtype", [None, object])\ndef test_setitem_object_typecode(dtype):\n arr = NumpyExtensionArray(np.array(["a", "b", "c"], dtype=dtype))\n arr[0] = "t"\n expected = NumpyExtensionArray(np.array(["t", "b", "c"], dtype=dtype))\n tm.assert_extension_array_equal(arr, expected)\n\n\ndef test_setitem_no_coercion():\n # https://github.com/pandas-dev/pandas/issues/28150\n arr = NumpyExtensionArray(np.array([1, 2, 3]))\n with pytest.raises(ValueError, match="int"):\n arr[0] = "a"\n\n # With a value that we do coerce, check that we coerce the value\n # and not the underlying array.\n arr[0] = 2.5\n assert isinstance(arr[0], (int, np.integer)), type(arr[0])\n\n\ndef test_setitem_preserves_views():\n # GH#28150, see also extension test of the same name\n arr = NumpyExtensionArray(np.array([1, 2, 3]))\n view1 = arr.view()\n view2 = arr[:]\n view3 = np.asarray(arr)\n\n arr[0] = 9\n assert view1[0] == 9\n assert view2[0] == 9\n assert view3[0] == 9\n\n arr[-1] = 2.5\n view1[-1] = 5\n assert arr[-1] == 5\n\n\n@pytest.mark.parametrize("dtype", [np.int64, np.uint64])\ndef test_quantile_empty(dtype):\n # we should get back np.nans, not -1s\n arr = NumpyExtensionArray(np.array([], dtype=dtype))\n idx = pd.Index([0.0, 0.5])\n\n result = arr._quantile(idx, interpolation="linear")\n expected = NumpyExtensionArray(np.array([np.nan, np.nan]))\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_factorize_unsigned():\n # don't raise when calling factorize on unsigned int NumpyExtensionArray\n arr = np.array([1, 2, 3], dtype=np.uint64)\n obj = NumpyExtensionArray(arr)\n\n res_codes, res_unique = obj.factorize()\n exp_codes, exp_unique = pd.factorize(arr)\n\n tm.assert_numpy_array_equal(res_codes, exp_codes)\n\n tm.assert_extension_array_equal(res_unique, NumpyExtensionArray(exp_unique))\n\n\n# ----------------------------------------------------------------------------\n# Output formatting\n\n\ndef test_array_repr(any_numpy_array):\n # GH#61085\n nparray = any_numpy_array\n arr = NumpyExtensionArray(nparray)\n if nparray.dtype == "object":\n values = "['a', 'b']"\n elif nparray.dtype == "float64":\n values = "[0.0, 1.0]"\n elif str(nparray.dtype).startswith("int"):\n values = "[0, 1]"\n elif nparray.dtype == "complex128":\n values = "[0j, (1+2j)]"\n elif nparray.dtype == "bool":\n values = "[True, False]"\n elif nparray.dtype == "datetime64[ns]":\n values = "[1970-01-01T00:00:00.000000000, 1970-01-01T00:00:00.000000001]"\n elif nparray.dtype == "timedelta64[ns]":\n values = "[0 nanoseconds, 1 nanoseconds]"\n expected = f"<NumpyExtensionArray>\n{values}\nLength: 2, dtype: {nparray.dtype}"\n result = repr(arr)\n assert result == expected, f"{result} vs {expected}"\n
.venv\Lib\site-packages\pandas\tests\arrays\numpy_\test_numpy.py
test_numpy.py
Python
9,726
0.95
0.094017
0.101167
vue-tools
984
2024-11-05T04:00:44.335325
MIT
true
36f2365ac2a0eb92802919ac9c624136
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\numpy_\__pycache__\test_indexing.cpython-313.pyc
test_indexing.cpython-313.pyc
Other
3,019
0.8
0
0
react-lib
999
2025-04-21T17:53:09.548985
Apache-2.0
true
8084ac3a100bddde75bf3c5b0f2aa7b5
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\numpy_\__pycache__\test_numpy.cpython-313.pyc
test_numpy.cpython-313.pyc
Other
15,411
0.8
0.010753
0.016949
vue-tools
232
2025-06-04T14:06:27.864170
BSD-3-Clause
true
35d02834303a354d4d10270de769555a
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\numpy_\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
201
0.7
0
0
node-utils
384
2023-09-21T13:36:58.837686
MIT
true
c651b44d09a4d3726321bc9f06e48c5c
import pytest\n\nfrom pandas.compat.pyarrow import pa_version_under10p1\n\nfrom pandas.core.dtypes.dtypes import PeriodDtype\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.core.arrays import (\n PeriodArray,\n period_array,\n)\n\npytestmark = pytest.mark.filterwarnings(\n "ignore:Passing a BlockManager to DataFrame:DeprecationWarning"\n)\n\n\npa = pytest.importorskip("pyarrow")\n\n\ndef test_arrow_extension_type():\n from pandas.core.arrays.arrow.extension_types import ArrowPeriodType\n\n p1 = ArrowPeriodType("D")\n p2 = ArrowPeriodType("D")\n p3 = ArrowPeriodType("M")\n\n assert p1.freq == "D"\n assert p1 == p2\n assert p1 != p3\n assert hash(p1) == hash(p2)\n assert hash(p1) != hash(p3)\n\n\n@pytest.mark.xfail(not pa_version_under10p1, reason="Wrong behavior with pyarrow 10")\n@pytest.mark.parametrize(\n "data, freq",\n [\n (pd.date_range("2017", periods=3), "D"),\n (pd.date_range("2017", periods=3, freq="YE"), "Y-DEC"),\n ],\n)\ndef test_arrow_array(data, freq):\n from pandas.core.arrays.arrow.extension_types import ArrowPeriodType\n\n periods = period_array(data, freq=freq)\n result = pa.array(periods)\n assert isinstance(result.type, ArrowPeriodType)\n assert result.type.freq == freq\n expected = pa.array(periods.asi8, type="int64")\n assert result.storage.equals(expected)\n\n # convert to its storage type\n result = pa.array(periods, type=pa.int64())\n assert result.equals(expected)\n\n # unsupported conversions\n msg = "Not supported to convert PeriodArray to 'double' type"\n with pytest.raises(TypeError, match=msg):\n pa.array(periods, type="float64")\n\n with pytest.raises(TypeError, match="different 'freq'"):\n pa.array(periods, type=ArrowPeriodType("T"))\n\n\ndef test_arrow_array_missing():\n from pandas.core.arrays.arrow.extension_types import ArrowPeriodType\n\n arr = PeriodArray([1, 2, 3], dtype="period[D]")\n arr[1] = pd.NaT\n\n result = pa.array(arr)\n assert isinstance(result.type, ArrowPeriodType)\n assert result.type.freq == "D"\n expected = pa.array([1, None, 3], type="int64")\n assert result.storage.equals(expected)\n\n\ndef test_arrow_table_roundtrip():\n from pandas.core.arrays.arrow.extension_types import ArrowPeriodType\n\n arr = PeriodArray([1, 2, 3], dtype="period[D]")\n arr[1] = pd.NaT\n df = pd.DataFrame({"a": arr})\n\n table = pa.table(df)\n assert isinstance(table.field("a").type, ArrowPeriodType)\n result = table.to_pandas()\n assert isinstance(result["a"].dtype, PeriodDtype)\n tm.assert_frame_equal(result, df)\n\n table2 = pa.concat_tables([table, table])\n result = table2.to_pandas()\n expected = pd.concat([df, df], ignore_index=True)\n tm.assert_frame_equal(result, expected)\n\n\ndef test_arrow_load_from_zero_chunks():\n # GH-41040\n\n from pandas.core.arrays.arrow.extension_types import ArrowPeriodType\n\n arr = PeriodArray([], dtype="period[D]")\n df = pd.DataFrame({"a": arr})\n\n table = pa.table(df)\n assert isinstance(table.field("a").type, ArrowPeriodType)\n table = pa.table(\n [pa.chunked_array([], type=table.column(0).type)], schema=table.schema\n )\n\n result = table.to_pandas()\n assert isinstance(result["a"].dtype, PeriodDtype)\n tm.assert_frame_equal(result, df)\n\n\ndef test_arrow_table_roundtrip_without_metadata():\n arr = PeriodArray([1, 2, 3], dtype="period[h]")\n arr[1] = pd.NaT\n df = pd.DataFrame({"a": arr})\n\n table = pa.table(df)\n # remove the metadata\n table = table.replace_schema_metadata()\n assert table.schema.metadata is None\n\n result = table.to_pandas()\n assert isinstance(result["a"].dtype, PeriodDtype)\n tm.assert_frame_equal(result, df)\n
.venv\Lib\site-packages\pandas\tests\arrays\period\test_arrow_compat.py
test_arrow_compat.py
Python
3,709
0.95
0.046154
0.042105
react-lib
636
2024-05-22T11:23:41.050183
GPL-3.0
true
538d607c5c40b5a1771f005084c5f4b4
import numpy as np\nimport pytest\n\nfrom pandas.core.dtypes.dtypes import PeriodDtype\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.core.arrays import period_array\n\n\n@pytest.mark.parametrize("dtype", [int, np.int32, np.int64, "uint32", "uint64"])\ndef test_astype_int(dtype):\n # We choose to ignore the sign and size of integers for\n # Period/Datetime/Timedelta astype\n arr = period_array(["2000", "2001", None], freq="D")\n\n if np.dtype(dtype) != np.int64:\n with pytest.raises(TypeError, match=r"Do obj.astype\('int64'\)"):\n arr.astype(dtype)\n return\n\n result = arr.astype(dtype)\n expected = arr._ndarray.view("i8")\n tm.assert_numpy_array_equal(result, expected)\n\n\ndef test_astype_copies():\n arr = period_array(["2000", "2001", None], freq="D")\n result = arr.astype(np.int64, copy=False)\n\n # Add the `.base`, since we now use `.asi8` which returns a view.\n # We could maybe override it in PeriodArray to return ._ndarray directly.\n assert result.base is arr._ndarray\n\n result = arr.astype(np.int64, copy=True)\n assert result is not arr._ndarray\n tm.assert_numpy_array_equal(result, arr._ndarray.view("i8"))\n\n\ndef test_astype_categorical():\n arr = period_array(["2000", "2001", "2001", None], freq="D")\n result = arr.astype("category")\n categories = pd.PeriodIndex(["2000", "2001"], freq="D")\n expected = pd.Categorical.from_codes([0, 1, 1, -1], categories=categories)\n tm.assert_categorical_equal(result, expected)\n\n\ndef test_astype_period():\n arr = period_array(["2000", "2001", None], freq="D")\n result = arr.astype(PeriodDtype("M"))\n expected = period_array(["2000", "2001", None], freq="M")\n tm.assert_period_array_equal(result, expected)\n\n\n@pytest.mark.parametrize("dtype", ["datetime64[ns]", "timedelta64[ns]"])\ndef test_astype_datetime(dtype):\n arr = period_array(["2000", "2001", None], freq="D")\n # slice off the [ns] so that the regex matches.\n if dtype == "timedelta64[ns]":\n with pytest.raises(TypeError, match=dtype[:-4]):\n arr.astype(dtype)\n\n else:\n # GH#45038 allow period->dt64 because we allow dt64->period\n result = arr.astype(dtype)\n expected = pd.DatetimeIndex(["2000", "2001", pd.NaT], dtype=dtype)._data\n tm.assert_datetime_array_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\arrays\period\test_astype.py
test_astype.py
Python
2,344
0.95
0.119403
0.12
node-utils
344
2025-01-25T18:52:22.069095
GPL-3.0
true
e1fae7d6c506f92f87e63fb42b7f022d
import numpy as np\nimport pytest\n\nfrom pandas._libs.tslibs import iNaT\nfrom pandas._libs.tslibs.offsets import MonthEnd\nfrom pandas._libs.tslibs.period import IncompatibleFrequency\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.core.arrays import (\n PeriodArray,\n period_array,\n)\n\n\n@pytest.mark.parametrize(\n "data, freq, expected",\n [\n ([pd.Period("2017", "D")], None, [17167]),\n ([pd.Period("2017", "D")], "D", [17167]),\n ([2017], "D", [17167]),\n (["2017"], "D", [17167]),\n ([pd.Period("2017", "D")], pd.tseries.offsets.Day(), [17167]),\n ([pd.Period("2017", "D"), None], None, [17167, iNaT]),\n (pd.Series(pd.date_range("2017", periods=3)), None, [17167, 17168, 17169]),\n (pd.date_range("2017", periods=3), None, [17167, 17168, 17169]),\n (pd.period_range("2017", periods=4, freq="Q"), None, [188, 189, 190, 191]),\n ],\n)\ndef test_period_array_ok(data, freq, expected):\n result = period_array(data, freq=freq).asi8\n expected = np.asarray(expected, dtype=np.int64)\n tm.assert_numpy_array_equal(result, expected)\n\n\ndef test_period_array_readonly_object():\n # https://github.com/pandas-dev/pandas/issues/25403\n pa = period_array([pd.Period("2019-01-01")])\n arr = np.asarray(pa, dtype="object")\n arr.setflags(write=False)\n\n result = period_array(arr)\n tm.assert_period_array_equal(result, pa)\n\n result = pd.Series(arr)\n tm.assert_series_equal(result, pd.Series(pa))\n\n result = pd.DataFrame({"A": arr})\n tm.assert_frame_equal(result, pd.DataFrame({"A": pa}))\n\n\ndef test_from_datetime64_freq_changes():\n # https://github.com/pandas-dev/pandas/issues/23438\n arr = pd.date_range("2017", periods=3, freq="D")\n result = PeriodArray._from_datetime64(arr, freq="M")\n expected = period_array(["2017-01-01", "2017-01-01", "2017-01-01"], freq="M")\n tm.assert_period_array_equal(result, expected)\n\n\n@pytest.mark.parametrize("freq", ["2M", MonthEnd(2)])\ndef test_from_datetime64_freq_2M(freq):\n arr = np.array(\n ["2020-01-01T00:00:00", "2020-01-02T00:00:00"], dtype="datetime64[ns]"\n )\n result = PeriodArray._from_datetime64(arr, freq)\n expected = period_array(["2020-01", "2020-01"], freq=freq)\n tm.assert_period_array_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "data, freq, msg",\n [\n (\n [pd.Period("2017", "D"), pd.Period("2017", "Y")],\n None,\n "Input has different freq",\n ),\n ([pd.Period("2017", "D")], "Y", "Input has different freq"),\n ],\n)\ndef test_period_array_raises(data, freq, msg):\n with pytest.raises(IncompatibleFrequency, match=msg):\n period_array(data, freq)\n\n\ndef test_period_array_non_period_series_raies():\n ser = pd.Series([1, 2, 3])\n with pytest.raises(TypeError, match="dtype"):\n PeriodArray(ser, dtype="period[D]")\n\n\ndef test_period_array_freq_mismatch():\n arr = period_array(["2000", "2001"], freq="D")\n with pytest.raises(IncompatibleFrequency, match="freq"):\n PeriodArray(arr, dtype="period[M]")\n\n dtype = pd.PeriodDtype(pd.tseries.offsets.MonthEnd())\n with pytest.raises(IncompatibleFrequency, match="freq"):\n PeriodArray(arr, dtype=dtype)\n\n\ndef test_from_sequence_disallows_i8():\n arr = period_array(["2000", "2001"], freq="D")\n\n msg = str(arr[0].ordinal)\n with pytest.raises(TypeError, match=msg):\n PeriodArray._from_sequence(arr.asi8, dtype=arr.dtype)\n\n with pytest.raises(TypeError, match=msg):\n PeriodArray._from_sequence(list(arr.asi8), dtype=arr.dtype)\n\n\ndef test_from_td64nat_sequence_raises():\n # GH#44507\n td = pd.NaT.to_numpy("m8[ns]")\n\n dtype = pd.period_range("2005-01-01", periods=3, freq="D").dtype\n\n arr = np.array([None], dtype=object)\n arr[0] = td\n\n msg = "Value must be Period, string, integer, or datetime"\n with pytest.raises(ValueError, match=msg):\n PeriodArray._from_sequence(arr, dtype=dtype)\n\n with pytest.raises(ValueError, match=msg):\n pd.PeriodIndex(arr, dtype=dtype)\n with pytest.raises(ValueError, match=msg):\n pd.Index(arr, dtype=dtype)\n with pytest.raises(ValueError, match=msg):\n pd.array(arr, dtype=dtype)\n with pytest.raises(ValueError, match=msg):\n pd.Series(arr, dtype=dtype)\n with pytest.raises(ValueError, match=msg):\n pd.DataFrame(arr, dtype=dtype)\n\n\ndef test_freq_deprecated():\n # GH#52462\n data = np.arange(5).astype(np.int64)\n msg = "The 'freq' keyword in the PeriodArray constructor is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n res = PeriodArray(data, freq="M")\n\n expected = PeriodArray(data, dtype="period[M]")\n tm.assert_equal(res, expected)\n\n\ndef test_period_array_from_datetime64():\n arr = np.array(\n ["2020-01-01T00:00:00", "2020-02-02T00:00:00"], dtype="datetime64[ns]"\n )\n result = PeriodArray._from_datetime64(arr, freq=MonthEnd(2))\n\n expected = period_array(["2020-01-01", "2020-02-01"], freq=MonthEnd(2))\n tm.assert_period_array_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\arrays\period\test_constructors.py
test_constructors.py
Python
5,089
0.95
0.070513
0.033333
react-lib
355
2023-10-17T03:14:15.555002
GPL-3.0
true
9ed91bd486e549514038f37e9d391fb3
import pytest\n\nimport pandas as pd\nfrom pandas.core.arrays import period_array\n\n\nclass TestReductions:\n def test_min_max(self):\n arr = period_array(\n [\n "2000-01-03",\n "2000-01-03",\n "NaT",\n "2000-01-02",\n "2000-01-05",\n "2000-01-04",\n ],\n freq="D",\n )\n\n result = arr.min()\n expected = pd.Period("2000-01-02", freq="D")\n assert result == expected\n\n result = arr.max()\n expected = pd.Period("2000-01-05", freq="D")\n assert result == expected\n\n result = arr.min(skipna=False)\n assert result is pd.NaT\n\n result = arr.max(skipna=False)\n assert result is pd.NaT\n\n @pytest.mark.parametrize("skipna", [True, False])\n def test_min_max_empty(self, skipna):\n arr = period_array([], freq="D")\n result = arr.min(skipna=skipna)\n assert result is pd.NaT\n\n result = arr.max(skipna=skipna)\n assert result is pd.NaT\n
.venv\Lib\site-packages\pandas\tests\arrays\period\test_reductions.py
test_reductions.py
Python
1,050
0.85
0.071429
0
awesome-app
537
2024-03-10T22:09:52.378905
BSD-3-Clause
true
5aba5a0bf577c1a413723e30e7d860ba
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\period\__pycache__\test_arrow_compat.cpython-313.pyc
test_arrow_compat.cpython-313.pyc
Other
6,874
0.95
0
0
react-lib
2
2024-02-14T13:55:14.308368
MIT
true
8ddc95d7e39a9b803ede010d7b50600c
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\period\__pycache__\test_astype.cpython-313.pyc
test_astype.cpython-313.pyc
Other
3,998
0.8
0
0.018519
vue-tools
974
2024-03-04T16:03:20.676184
Apache-2.0
true
7de649c762789acd626d010ed5795b73
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\period\__pycache__\test_constructors.cpython-313.pyc
test_constructors.cpython-313.pyc
Other
9,746
0.8
0
0.028169
python-kit
591
2024-12-29T19:01:05.711745
Apache-2.0
true
90d363308a7706483cedc805269d15b4
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\period\__pycache__\test_reductions.cpython-313.pyc
test_reductions.cpython-313.pyc
Other
1,909
0.8
0
0
awesome-app
653
2024-10-26T04:14:45.680911
BSD-3-Clause
true
de6f7abcbd8ee2f13821a4049d3c5aef
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\period\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
201
0.7
0
0
awesome-app
156
2024-06-05T15:20:00.735543
Apache-2.0
true
258d59662da336963608d2772edf8135
import string\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import SparseDtype\nimport pandas._testing as tm\nfrom pandas.core.arrays.sparse import SparseArray\n\n\nclass TestSeriesAccessor:\n def test_to_dense(self):\n ser = pd.Series([0, 1, 0, 10], dtype="Sparse[int64]")\n result = ser.sparse.to_dense()\n expected = pd.Series([0, 1, 0, 10])\n tm.assert_series_equal(result, expected)\n\n @pytest.mark.parametrize("attr", ["npoints", "density", "fill_value", "sp_values"])\n def test_get_attributes(self, attr):\n arr = SparseArray([0, 1])\n ser = pd.Series(arr)\n\n result = getattr(ser.sparse, attr)\n expected = getattr(arr, attr)\n assert result == expected\n\n def test_from_coo(self):\n scipy_sparse = pytest.importorskip("scipy.sparse")\n\n row = [0, 3, 1, 0]\n col = [0, 3, 1, 2]\n data = [4, 5, 7, 9]\n\n sp_array = scipy_sparse.coo_matrix((data, (row, col)))\n result = pd.Series.sparse.from_coo(sp_array)\n\n index = pd.MultiIndex.from_arrays(\n [\n np.array([0, 0, 1, 3], dtype=np.int32),\n np.array([0, 2, 1, 3], dtype=np.int32),\n ],\n )\n expected = pd.Series([4, 9, 7, 5], index=index, dtype="Sparse[int]")\n tm.assert_series_equal(result, expected)\n\n @pytest.mark.parametrize(\n "sort_labels, expected_rows, expected_cols, expected_values_pos",\n [\n (\n False,\n [("b", 2), ("a", 2), ("b", 1), ("a", 1)],\n [("z", 1), ("z", 2), ("x", 2), ("z", 0)],\n {1: (1, 0), 3: (3, 3)},\n ),\n (\n True,\n [("a", 1), ("a", 2), ("b", 1), ("b", 2)],\n [("x", 2), ("z", 0), ("z", 1), ("z", 2)],\n {1: (1, 2), 3: (0, 1)},\n ),\n ],\n )\n def test_to_coo(\n self, sort_labels, expected_rows, expected_cols, expected_values_pos\n ):\n sp_sparse = pytest.importorskip("scipy.sparse")\n\n values = SparseArray([0, np.nan, 1, 0, None, 3], fill_value=0)\n index = pd.MultiIndex.from_tuples(\n [\n ("b", 2, "z", 1),\n ("a", 2, "z", 2),\n ("a", 2, "z", 1),\n ("a", 2, "x", 2),\n ("b", 1, "z", 1),\n ("a", 1, "z", 0),\n ]\n )\n ss = pd.Series(values, index=index)\n\n expected_A = np.zeros((4, 4))\n for value, (row, col) in expected_values_pos.items():\n expected_A[row, col] = value\n\n A, rows, cols = ss.sparse.to_coo(\n row_levels=(0, 1), column_levels=(2, 3), sort_labels=sort_labels\n )\n assert isinstance(A, sp_sparse.coo_matrix)\n tm.assert_numpy_array_equal(A.toarray(), expected_A)\n assert rows == expected_rows\n assert cols == expected_cols\n\n def test_non_sparse_raises(self):\n ser = pd.Series([1, 2, 3])\n with pytest.raises(AttributeError, match=".sparse"):\n ser.sparse.density\n\n\nclass TestFrameAccessor:\n def test_accessor_raises(self):\n df = pd.DataFrame({"A": [0, 1]})\n with pytest.raises(AttributeError, match="sparse"):\n df.sparse\n\n @pytest.mark.parametrize("format", ["csc", "csr", "coo"])\n @pytest.mark.parametrize("labels", [None, list(string.ascii_letters[:10])])\n @pytest.mark.parametrize("dtype", ["float64", "int64"])\n def test_from_spmatrix(self, format, labels, dtype):\n sp_sparse = pytest.importorskip("scipy.sparse")\n\n sp_dtype = SparseDtype(dtype, np.array(0, dtype=dtype).item())\n\n mat = sp_sparse.eye(10, format=format, dtype=dtype)\n result = pd.DataFrame.sparse.from_spmatrix(mat, index=labels, columns=labels)\n expected = pd.DataFrame(\n np.eye(10, dtype=dtype), index=labels, columns=labels\n ).astype(sp_dtype)\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("format", ["csc", "csr", "coo"])\n def test_from_spmatrix_including_explicit_zero(self, format):\n sp_sparse = pytest.importorskip("scipy.sparse")\n\n mat = sp_sparse.random(10, 2, density=0.5, format=format)\n mat.data[0] = 0\n result = pd.DataFrame.sparse.from_spmatrix(mat)\n dtype = SparseDtype("float64", 0.0)\n expected = pd.DataFrame(mat.todense()).astype(dtype)\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "columns",\n [["a", "b"], pd.MultiIndex.from_product([["A"], ["a", "b"]]), ["a", "a"]],\n )\n def test_from_spmatrix_columns(self, columns):\n sp_sparse = pytest.importorskip("scipy.sparse")\n\n dtype = SparseDtype("float64", 0.0)\n\n mat = sp_sparse.random(10, 2, density=0.5)\n result = pd.DataFrame.sparse.from_spmatrix(mat, columns=columns)\n expected = pd.DataFrame(mat.toarray(), columns=columns).astype(dtype)\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "colnames", [("A", "B"), (1, 2), (1, pd.NA), (0.1, 0.2), ("x", "x"), (0, 0)]\n )\n def test_to_coo(self, colnames):\n sp_sparse = pytest.importorskip("scipy.sparse")\n\n df = pd.DataFrame(\n {colnames[0]: [0, 1, 0], colnames[1]: [1, 0, 0]}, dtype="Sparse[int64, 0]"\n )\n result = df.sparse.to_coo()\n expected = sp_sparse.coo_matrix(np.asarray(df))\n assert (result != expected).nnz == 0\n\n @pytest.mark.parametrize("fill_value", [1, np.nan])\n def test_to_coo_nonzero_fill_val_raises(self, fill_value):\n pytest.importorskip("scipy")\n df = pd.DataFrame(\n {\n "A": SparseArray(\n [fill_value, fill_value, fill_value, 2], fill_value=fill_value\n ),\n "B": SparseArray(\n [fill_value, 2, fill_value, fill_value], fill_value=fill_value\n ),\n }\n )\n with pytest.raises(ValueError, match="fill value must be 0"):\n df.sparse.to_coo()\n\n def test_to_coo_midx_categorical(self):\n # GH#50996\n sp_sparse = pytest.importorskip("scipy.sparse")\n\n midx = pd.MultiIndex.from_arrays(\n [\n pd.CategoricalIndex(list("ab"), name="x"),\n pd.CategoricalIndex([0, 1], name="y"),\n ]\n )\n\n ser = pd.Series(1, index=midx, dtype="Sparse[int]")\n result = ser.sparse.to_coo(row_levels=["x"], column_levels=["y"])[0]\n expected = sp_sparse.coo_matrix(\n (np.array([1, 1]), (np.array([0, 1]), np.array([0, 1]))), shape=(2, 2)\n )\n assert (result != expected).nnz == 0\n\n def test_to_dense(self):\n df = pd.DataFrame(\n {\n "A": SparseArray([1, 0], dtype=SparseDtype("int64", 0)),\n "B": SparseArray([1, 0], dtype=SparseDtype("int64", 1)),\n "C": SparseArray([1.0, 0.0], dtype=SparseDtype("float64", 0.0)),\n },\n index=["b", "a"],\n )\n result = df.sparse.to_dense()\n expected = pd.DataFrame(\n {"A": [1, 0], "B": [1, 0], "C": [1.0, 0.0]}, index=["b", "a"]\n )\n tm.assert_frame_equal(result, expected)\n\n def test_density(self):\n df = pd.DataFrame(\n {\n "A": SparseArray([1, 0, 2, 1], fill_value=0),\n "B": SparseArray([0, 1, 1, 1], fill_value=0),\n }\n )\n res = df.sparse.density\n expected = 0.75\n assert res == expected\n\n @pytest.mark.parametrize("dtype", ["int64", "float64"])\n @pytest.mark.parametrize("dense_index", [True, False])\n def test_series_from_coo(self, dtype, dense_index):\n sp_sparse = pytest.importorskip("scipy.sparse")\n\n A = sp_sparse.eye(3, format="coo", dtype=dtype)\n result = pd.Series.sparse.from_coo(A, dense_index=dense_index)\n\n index = pd.MultiIndex.from_tuples(\n [\n np.array([0, 0], dtype=np.int32),\n np.array([1, 1], dtype=np.int32),\n np.array([2, 2], dtype=np.int32),\n ],\n )\n expected = pd.Series(SparseArray(np.array([1, 1, 1], dtype=dtype)), index=index)\n if dense_index:\n expected = expected.reindex(pd.MultiIndex.from_product(index.levels))\n\n tm.assert_series_equal(result, expected)\n\n def test_series_from_coo_incorrect_format_raises(self):\n # gh-26554\n sp_sparse = pytest.importorskip("scipy.sparse")\n\n m = sp_sparse.csr_matrix(np.array([[0, 1], [0, 0]]))\n with pytest.raises(\n TypeError, match="Expected coo_matrix. Got csr_matrix instead."\n ):\n pd.Series.sparse.from_coo(m)\n\n def test_with_column_named_sparse(self):\n # https://github.com/pandas-dev/pandas/issues/30758\n df = pd.DataFrame({"sparse": pd.arrays.SparseArray([1, 2])})\n assert isinstance(df.sparse, pd.core.arrays.sparse.accessor.SparseFrameAccessor)\n
.venv\Lib\site-packages\pandas\tests\arrays\sparse\test_accessor.py
test_accessor.py
Python
9,025
0.95
0.083004
0.014085
awesome-app
102
2025-04-07T03:25:15.413587
BSD-3-Clause
true
3502701099a3bddf99a7810f708aeec8
import operator\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import SparseDtype\nimport pandas._testing as tm\nfrom pandas.core.arrays.sparse import SparseArray\n\n\n@pytest.fixture(params=["integer", "block"])\ndef kind(request):\n """kind kwarg to pass to SparseArray"""\n return request.param\n\n\n@pytest.fixture(params=[True, False])\ndef mix(request):\n """\n Fixture returning True or False, determining whether to operate\n op(sparse, dense) instead of op(sparse, sparse)\n """\n return request.param\n\n\nclass TestSparseArrayArithmetics:\n def _assert(self, a, b):\n # We have to use tm.assert_sp_array_equal. See GH #45126\n tm.assert_numpy_array_equal(a, b)\n\n def _check_numeric_ops(self, a, b, a_dense, b_dense, mix: bool, op):\n # Check that arithmetic behavior matches non-Sparse Series arithmetic\n\n if isinstance(a_dense, np.ndarray):\n expected = op(pd.Series(a_dense), b_dense).values\n elif isinstance(b_dense, np.ndarray):\n expected = op(a_dense, pd.Series(b_dense)).values\n else:\n raise NotImplementedError\n\n with np.errstate(invalid="ignore", divide="ignore"):\n if mix:\n result = op(a, b_dense).to_dense()\n else:\n result = op(a, b).to_dense()\n\n self._assert(result, expected)\n\n def _check_bool_result(self, res):\n assert isinstance(res, SparseArray)\n assert isinstance(res.dtype, SparseDtype)\n assert res.dtype.subtype == np.bool_\n assert isinstance(res.fill_value, bool)\n\n def _check_comparison_ops(self, a, b, a_dense, b_dense):\n with np.errstate(invalid="ignore"):\n # Unfortunately, trying to wrap the computation of each expected\n # value is with np.errstate() is too tedious.\n #\n # sparse & sparse\n self._check_bool_result(a == b)\n self._assert((a == b).to_dense(), a_dense == b_dense)\n\n self._check_bool_result(a != b)\n self._assert((a != b).to_dense(), a_dense != b_dense)\n\n self._check_bool_result(a >= b)\n self._assert((a >= b).to_dense(), a_dense >= b_dense)\n\n self._check_bool_result(a <= b)\n self._assert((a <= b).to_dense(), a_dense <= b_dense)\n\n self._check_bool_result(a > b)\n self._assert((a > b).to_dense(), a_dense > b_dense)\n\n self._check_bool_result(a < b)\n self._assert((a < b).to_dense(), a_dense < b_dense)\n\n # sparse & dense\n self._check_bool_result(a == b_dense)\n self._assert((a == b_dense).to_dense(), a_dense == b_dense)\n\n self._check_bool_result(a != b_dense)\n self._assert((a != b_dense).to_dense(), a_dense != b_dense)\n\n self._check_bool_result(a >= b_dense)\n self._assert((a >= b_dense).to_dense(), a_dense >= b_dense)\n\n self._check_bool_result(a <= b_dense)\n self._assert((a <= b_dense).to_dense(), a_dense <= b_dense)\n\n self._check_bool_result(a > b_dense)\n self._assert((a > b_dense).to_dense(), a_dense > b_dense)\n\n self._check_bool_result(a < b_dense)\n self._assert((a < b_dense).to_dense(), a_dense < b_dense)\n\n def _check_logical_ops(self, a, b, a_dense, b_dense):\n # sparse & sparse\n self._check_bool_result(a & b)\n self._assert((a & b).to_dense(), a_dense & b_dense)\n\n self._check_bool_result(a | b)\n self._assert((a | b).to_dense(), a_dense | b_dense)\n # sparse & dense\n self._check_bool_result(a & b_dense)\n self._assert((a & b_dense).to_dense(), a_dense & b_dense)\n\n self._check_bool_result(a | b_dense)\n self._assert((a | b_dense).to_dense(), a_dense | b_dense)\n\n @pytest.mark.parametrize("scalar", [0, 1, 3])\n @pytest.mark.parametrize("fill_value", [None, 0, 2])\n def test_float_scalar(\n self, kind, mix, all_arithmetic_functions, fill_value, scalar, request\n ):\n op = all_arithmetic_functions\n values = np.array([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])\n a = SparseArray(values, kind=kind, fill_value=fill_value)\n self._check_numeric_ops(a, scalar, values, scalar, mix, op)\n\n def test_float_scalar_comparison(self, kind):\n values = np.array([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])\n\n a = SparseArray(values, kind=kind)\n self._check_comparison_ops(a, 1, values, 1)\n self._check_comparison_ops(a, 0, values, 0)\n self._check_comparison_ops(a, 3, values, 3)\n\n a = SparseArray(values, kind=kind, fill_value=0)\n self._check_comparison_ops(a, 1, values, 1)\n self._check_comparison_ops(a, 0, values, 0)\n self._check_comparison_ops(a, 3, values, 3)\n\n a = SparseArray(values, kind=kind, fill_value=2)\n self._check_comparison_ops(a, 1, values, 1)\n self._check_comparison_ops(a, 0, values, 0)\n self._check_comparison_ops(a, 3, values, 3)\n\n def test_float_same_index_without_nans(self, kind, mix, all_arithmetic_functions):\n # when sp_index are the same\n op = all_arithmetic_functions\n\n values = np.array([0.0, 1.0, 2.0, 6.0, 0.0, 0.0, 1.0, 2.0, 1.0, 0.0])\n rvalues = np.array([0.0, 2.0, 3.0, 4.0, 0.0, 0.0, 1.0, 3.0, 2.0, 0.0])\n\n a = SparseArray(values, kind=kind, fill_value=0)\n b = SparseArray(rvalues, kind=kind, fill_value=0)\n self._check_numeric_ops(a, b, values, rvalues, mix, op)\n\n def test_float_same_index_with_nans(\n self, kind, mix, all_arithmetic_functions, request\n ):\n # when sp_index are the same\n op = all_arithmetic_functions\n values = np.array([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])\n rvalues = np.array([np.nan, 2, 3, 4, np.nan, 0, 1, 3, 2, np.nan])\n\n a = SparseArray(values, kind=kind)\n b = SparseArray(rvalues, kind=kind)\n self._check_numeric_ops(a, b, values, rvalues, mix, op)\n\n def test_float_same_index_comparison(self, kind):\n # when sp_index are the same\n values = np.array([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])\n rvalues = np.array([np.nan, 2, 3, 4, np.nan, 0, 1, 3, 2, np.nan])\n\n a = SparseArray(values, kind=kind)\n b = SparseArray(rvalues, kind=kind)\n self._check_comparison_ops(a, b, values, rvalues)\n\n values = np.array([0.0, 1.0, 2.0, 6.0, 0.0, 0.0, 1.0, 2.0, 1.0, 0.0])\n rvalues = np.array([0.0, 2.0, 3.0, 4.0, 0.0, 0.0, 1.0, 3.0, 2.0, 0.0])\n\n a = SparseArray(values, kind=kind, fill_value=0)\n b = SparseArray(rvalues, kind=kind, fill_value=0)\n self._check_comparison_ops(a, b, values, rvalues)\n\n def test_float_array(self, kind, mix, all_arithmetic_functions):\n op = all_arithmetic_functions\n\n values = np.array([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])\n rvalues = np.array([2, np.nan, 2, 3, np.nan, 0, 1, 5, 2, np.nan])\n\n a = SparseArray(values, kind=kind)\n b = SparseArray(rvalues, kind=kind)\n self._check_numeric_ops(a, b, values, rvalues, mix, op)\n self._check_numeric_ops(a, b * 0, values, rvalues * 0, mix, op)\n\n a = SparseArray(values, kind=kind, fill_value=0)\n b = SparseArray(rvalues, kind=kind)\n self._check_numeric_ops(a, b, values, rvalues, mix, op)\n\n a = SparseArray(values, kind=kind, fill_value=0)\n b = SparseArray(rvalues, kind=kind, fill_value=0)\n self._check_numeric_ops(a, b, values, rvalues, mix, op)\n\n a = SparseArray(values, kind=kind, fill_value=1)\n b = SparseArray(rvalues, kind=kind, fill_value=2)\n self._check_numeric_ops(a, b, values, rvalues, mix, op)\n\n def test_float_array_different_kind(self, mix, all_arithmetic_functions):\n op = all_arithmetic_functions\n\n values = np.array([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])\n rvalues = np.array([2, np.nan, 2, 3, np.nan, 0, 1, 5, 2, np.nan])\n\n a = SparseArray(values, kind="integer")\n b = SparseArray(rvalues, kind="block")\n self._check_numeric_ops(a, b, values, rvalues, mix, op)\n self._check_numeric_ops(a, b * 0, values, rvalues * 0, mix, op)\n\n a = SparseArray(values, kind="integer", fill_value=0)\n b = SparseArray(rvalues, kind="block")\n self._check_numeric_ops(a, b, values, rvalues, mix, op)\n\n a = SparseArray(values, kind="integer", fill_value=0)\n b = SparseArray(rvalues, kind="block", fill_value=0)\n self._check_numeric_ops(a, b, values, rvalues, mix, op)\n\n a = SparseArray(values, kind="integer", fill_value=1)\n b = SparseArray(rvalues, kind="block", fill_value=2)\n self._check_numeric_ops(a, b, values, rvalues, mix, op)\n\n def test_float_array_comparison(self, kind):\n values = np.array([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])\n rvalues = np.array([2, np.nan, 2, 3, np.nan, 0, 1, 5, 2, np.nan])\n\n a = SparseArray(values, kind=kind)\n b = SparseArray(rvalues, kind=kind)\n self._check_comparison_ops(a, b, values, rvalues)\n self._check_comparison_ops(a, b * 0, values, rvalues * 0)\n\n a = SparseArray(values, kind=kind, fill_value=0)\n b = SparseArray(rvalues, kind=kind)\n self._check_comparison_ops(a, b, values, rvalues)\n\n a = SparseArray(values, kind=kind, fill_value=0)\n b = SparseArray(rvalues, kind=kind, fill_value=0)\n self._check_comparison_ops(a, b, values, rvalues)\n\n a = SparseArray(values, kind=kind, fill_value=1)\n b = SparseArray(rvalues, kind=kind, fill_value=2)\n self._check_comparison_ops(a, b, values, rvalues)\n\n def test_int_array(self, kind, mix, all_arithmetic_functions):\n op = all_arithmetic_functions\n\n # have to specify dtype explicitly until fixing GH 667\n dtype = np.int64\n\n values = np.array([0, 1, 2, 0, 0, 0, 1, 2, 1, 0], dtype=dtype)\n rvalues = np.array([2, 0, 2, 3, 0, 0, 1, 5, 2, 0], dtype=dtype)\n\n a = SparseArray(values, dtype=dtype, kind=kind)\n assert a.dtype == SparseDtype(dtype)\n b = SparseArray(rvalues, dtype=dtype, kind=kind)\n assert b.dtype == SparseDtype(dtype)\n\n self._check_numeric_ops(a, b, values, rvalues, mix, op)\n self._check_numeric_ops(a, b * 0, values, rvalues * 0, mix, op)\n\n a = SparseArray(values, fill_value=0, dtype=dtype, kind=kind)\n assert a.dtype == SparseDtype(dtype)\n b = SparseArray(rvalues, dtype=dtype, kind=kind)\n assert b.dtype == SparseDtype(dtype)\n\n self._check_numeric_ops(a, b, values, rvalues, mix, op)\n\n a = SparseArray(values, fill_value=0, dtype=dtype, kind=kind)\n assert a.dtype == SparseDtype(dtype)\n b = SparseArray(rvalues, fill_value=0, dtype=dtype, kind=kind)\n assert b.dtype == SparseDtype(dtype)\n self._check_numeric_ops(a, b, values, rvalues, mix, op)\n\n a = SparseArray(values, fill_value=1, dtype=dtype, kind=kind)\n assert a.dtype == SparseDtype(dtype, fill_value=1)\n b = SparseArray(rvalues, fill_value=2, dtype=dtype, kind=kind)\n assert b.dtype == SparseDtype(dtype, fill_value=2)\n self._check_numeric_ops(a, b, values, rvalues, mix, op)\n\n def test_int_array_comparison(self, kind):\n dtype = "int64"\n # int32 NI ATM\n\n values = np.array([0, 1, 2, 0, 0, 0, 1, 2, 1, 0], dtype=dtype)\n rvalues = np.array([2, 0, 2, 3, 0, 0, 1, 5, 2, 0], dtype=dtype)\n\n a = SparseArray(values, dtype=dtype, kind=kind)\n b = SparseArray(rvalues, dtype=dtype, kind=kind)\n self._check_comparison_ops(a, b, values, rvalues)\n self._check_comparison_ops(a, b * 0, values, rvalues * 0)\n\n a = SparseArray(values, dtype=dtype, kind=kind, fill_value=0)\n b = SparseArray(rvalues, dtype=dtype, kind=kind)\n self._check_comparison_ops(a, b, values, rvalues)\n\n a = SparseArray(values, dtype=dtype, kind=kind, fill_value=0)\n b = SparseArray(rvalues, dtype=dtype, kind=kind, fill_value=0)\n self._check_comparison_ops(a, b, values, rvalues)\n\n a = SparseArray(values, dtype=dtype, kind=kind, fill_value=1)\n b = SparseArray(rvalues, dtype=dtype, kind=kind, fill_value=2)\n self._check_comparison_ops(a, b, values, rvalues)\n\n @pytest.mark.parametrize("fill_value", [True, False, np.nan])\n def test_bool_same_index(self, kind, fill_value):\n # GH 14000\n # when sp_index are the same\n values = np.array([True, False, True, True], dtype=np.bool_)\n rvalues = np.array([True, False, True, True], dtype=np.bool_)\n\n a = SparseArray(values, kind=kind, dtype=np.bool_, fill_value=fill_value)\n b = SparseArray(rvalues, kind=kind, dtype=np.bool_, fill_value=fill_value)\n self._check_logical_ops(a, b, values, rvalues)\n\n @pytest.mark.parametrize("fill_value", [True, False, np.nan])\n def test_bool_array_logical(self, kind, fill_value):\n # GH 14000\n # when sp_index are the same\n values = np.array([True, False, True, False, True, True], dtype=np.bool_)\n rvalues = np.array([True, False, False, True, False, True], dtype=np.bool_)\n\n a = SparseArray(values, kind=kind, dtype=np.bool_, fill_value=fill_value)\n b = SparseArray(rvalues, kind=kind, dtype=np.bool_, fill_value=fill_value)\n self._check_logical_ops(a, b, values, rvalues)\n\n def test_mixed_array_float_int(self, kind, mix, all_arithmetic_functions, request):\n op = all_arithmetic_functions\n rdtype = "int64"\n values = np.array([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])\n rvalues = np.array([2, 0, 2, 3, 0, 0, 1, 5, 2, 0], dtype=rdtype)\n\n a = SparseArray(values, kind=kind)\n b = SparseArray(rvalues, kind=kind)\n assert b.dtype == SparseDtype(rdtype)\n\n self._check_numeric_ops(a, b, values, rvalues, mix, op)\n self._check_numeric_ops(a, b * 0, values, rvalues * 0, mix, op)\n\n a = SparseArray(values, kind=kind, fill_value=0)\n b = SparseArray(rvalues, kind=kind)\n assert b.dtype == SparseDtype(rdtype)\n self._check_numeric_ops(a, b, values, rvalues, mix, op)\n\n a = SparseArray(values, kind=kind, fill_value=0)\n b = SparseArray(rvalues, kind=kind, fill_value=0)\n assert b.dtype == SparseDtype(rdtype)\n self._check_numeric_ops(a, b, values, rvalues, mix, op)\n\n a = SparseArray(values, kind=kind, fill_value=1)\n b = SparseArray(rvalues, kind=kind, fill_value=2)\n assert b.dtype == SparseDtype(rdtype, fill_value=2)\n self._check_numeric_ops(a, b, values, rvalues, mix, op)\n\n def test_mixed_array_comparison(self, kind):\n rdtype = "int64"\n # int32 NI ATM\n\n values = np.array([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])\n rvalues = np.array([2, 0, 2, 3, 0, 0, 1, 5, 2, 0], dtype=rdtype)\n\n a = SparseArray(values, kind=kind)\n b = SparseArray(rvalues, kind=kind)\n assert b.dtype == SparseDtype(rdtype)\n\n self._check_comparison_ops(a, b, values, rvalues)\n self._check_comparison_ops(a, b * 0, values, rvalues * 0)\n\n a = SparseArray(values, kind=kind, fill_value=0)\n b = SparseArray(rvalues, kind=kind)\n assert b.dtype == SparseDtype(rdtype)\n self._check_comparison_ops(a, b, values, rvalues)\n\n a = SparseArray(values, kind=kind, fill_value=0)\n b = SparseArray(rvalues, kind=kind, fill_value=0)\n assert b.dtype == SparseDtype(rdtype)\n self._check_comparison_ops(a, b, values, rvalues)\n\n a = SparseArray(values, kind=kind, fill_value=1)\n b = SparseArray(rvalues, kind=kind, fill_value=2)\n assert b.dtype == SparseDtype(rdtype, fill_value=2)\n self._check_comparison_ops(a, b, values, rvalues)\n\n def test_xor(self):\n s = SparseArray([True, True, False, False])\n t = SparseArray([True, False, True, False])\n result = s ^ t\n sp_index = pd.core.arrays.sparse.IntIndex(4, np.array([0, 1, 2], dtype="int32"))\n expected = SparseArray([False, True, True], sparse_index=sp_index)\n tm.assert_sp_array_equal(result, expected)\n\n\n@pytest.mark.parametrize("op", [operator.eq, operator.add])\ndef test_with_list(op):\n arr = SparseArray([0, 1], fill_value=0)\n result = op(arr, [0, 1])\n expected = op(arr, SparseArray([0, 1]))\n tm.assert_sp_array_equal(result, expected)\n\n\ndef test_with_dataframe():\n # GH#27910\n arr = SparseArray([0, 1], fill_value=0)\n df = pd.DataFrame([[1, 2], [3, 4]])\n result = arr.__add__(df)\n assert result is NotImplemented\n\n\ndef test_with_zerodim_ndarray():\n # GH#27910\n arr = SparseArray([0, 1], fill_value=0)\n\n result = arr * np.array(2)\n expected = arr * 2\n tm.assert_sp_array_equal(result, expected)\n\n\n@pytest.mark.parametrize("ufunc", [np.abs, np.exp])\n@pytest.mark.parametrize(\n "arr", [SparseArray([0, 0, -1, 1]), SparseArray([None, None, -1, 1])]\n)\ndef test_ufuncs(ufunc, arr):\n result = ufunc(arr)\n fill_value = ufunc(arr.fill_value)\n expected = SparseArray(ufunc(np.asarray(arr)), fill_value=fill_value)\n tm.assert_sp_array_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "a, b",\n [\n (SparseArray([0, 0, 0]), np.array([0, 1, 2])),\n (SparseArray([0, 0, 0], fill_value=1), np.array([0, 1, 2])),\n (SparseArray([0, 0, 0], fill_value=1), np.array([0, 1, 2])),\n (SparseArray([0, 0, 0], fill_value=1), np.array([0, 1, 2])),\n (SparseArray([0, 0, 0], fill_value=1), np.array([0, 1, 2])),\n ],\n)\n@pytest.mark.parametrize("ufunc", [np.add, np.greater])\ndef test_binary_ufuncs(ufunc, a, b):\n # can't say anything about fill value here.\n result = ufunc(a, b)\n expected = ufunc(np.asarray(a), np.asarray(b))\n assert isinstance(result, SparseArray)\n tm.assert_numpy_array_equal(np.asarray(result), expected)\n\n\ndef test_ndarray_inplace():\n sparray = SparseArray([0, 2, 0, 0])\n ndarray = np.array([0, 1, 2, 3])\n ndarray += sparray\n expected = np.array([0, 3, 2, 3])\n tm.assert_numpy_array_equal(ndarray, expected)\n\n\ndef test_sparray_inplace():\n sparray = SparseArray([0, 2, 0, 0])\n ndarray = np.array([0, 1, 2, 3])\n sparray += ndarray\n expected = SparseArray([0, 3, 2, 3], fill_value=0)\n tm.assert_sp_array_equal(sparray, expected)\n\n\n@pytest.mark.parametrize("cons", [list, np.array, SparseArray])\ndef test_mismatched_length_cmp_op(cons):\n left = SparseArray([True, True])\n right = cons([True, True, True])\n with pytest.raises(ValueError, match="operands have mismatched length"):\n left & right\n\n\n@pytest.mark.parametrize("op", ["add", "sub", "mul", "truediv", "floordiv", "pow"])\n@pytest.mark.parametrize("fill_value", [np.nan, 3])\ndef test_binary_operators(op, fill_value):\n op = getattr(operator, op)\n data1 = np.random.default_rng(2).standard_normal(20)\n data2 = np.random.default_rng(2).standard_normal(20)\n\n data1[::2] = fill_value\n data2[::3] = fill_value\n\n first = SparseArray(data1, fill_value=fill_value)\n second = SparseArray(data2, fill_value=fill_value)\n\n with np.errstate(all="ignore"):\n res = op(first, second)\n exp = SparseArray(\n op(first.to_dense(), second.to_dense()), fill_value=first.fill_value\n )\n assert isinstance(res, SparseArray)\n tm.assert_almost_equal(res.to_dense(), exp.to_dense())\n\n res2 = op(first, second.to_dense())\n assert isinstance(res2, SparseArray)\n tm.assert_sp_array_equal(res, res2)\n\n res3 = op(first.to_dense(), second)\n assert isinstance(res3, SparseArray)\n tm.assert_sp_array_equal(res, res3)\n\n res4 = op(first, 4)\n assert isinstance(res4, SparseArray)\n\n # Ignore this if the actual op raises (e.g. pow).\n try:\n exp = op(first.to_dense(), 4)\n exp_fv = op(first.fill_value, 4)\n except ValueError:\n pass\n else:\n tm.assert_almost_equal(res4.fill_value, exp_fv)\n tm.assert_almost_equal(res4.to_dense(), exp)\n
.venv\Lib\site-packages\pandas\tests\arrays\sparse\test_arithmetics.py
test_arithmetics.py
Python
20,152
0.95
0.070039
0.058081
python-kit
151
2023-08-25T04:14:42.326600
Apache-2.0
true
b5ba5db163b9647fc4a965f9de43a5f6
import re\n\nimport numpy as np\nimport pytest\n\nfrom pandas._libs.sparse import IntIndex\nfrom pandas.compat.numpy import np_version_gt2\n\nimport pandas as pd\nfrom pandas import (\n SparseDtype,\n isna,\n)\nimport pandas._testing as tm\nfrom pandas.core.arrays.sparse import SparseArray\n\n\n@pytest.fixture\ndef arr_data():\n """Fixture returning numpy array with valid and missing entries"""\n return np.array([np.nan, np.nan, 1, 2, 3, np.nan, 4, 5, np.nan, 6])\n\n\n@pytest.fixture\ndef arr(arr_data):\n """Fixture returning SparseArray from 'arr_data'"""\n return SparseArray(arr_data)\n\n\n@pytest.fixture\ndef zarr():\n """Fixture returning SparseArray with integer entries and 'fill_value=0'"""\n return SparseArray([0, 0, 1, 2, 3, 0, 4, 5, 0, 6], fill_value=0)\n\n\nclass TestSparseArray:\n @pytest.mark.parametrize("fill_value", [0, None, np.nan])\n def test_shift_fill_value(self, fill_value):\n # GH #24128\n sparse = SparseArray(np.array([1, 0, 0, 3, 0]), fill_value=8.0)\n res = sparse.shift(1, fill_value=fill_value)\n if isna(fill_value):\n fill_value = res.dtype.na_value\n exp = SparseArray(np.array([fill_value, 1, 0, 0, 3]), fill_value=8.0)\n tm.assert_sp_array_equal(res, exp)\n\n def test_set_fill_value(self):\n arr = SparseArray([1.0, np.nan, 2.0], fill_value=np.nan)\n arr.fill_value = 2\n assert arr.fill_value == 2\n\n arr = SparseArray([1, 0, 2], fill_value=0, dtype=np.int64)\n arr.fill_value = 2\n assert arr.fill_value == 2\n\n msg = "Allowing arbitrary scalar fill_value in SparseDtype is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n arr.fill_value = 3.1\n assert arr.fill_value == 3.1\n\n arr.fill_value = np.nan\n assert np.isnan(arr.fill_value)\n\n arr = SparseArray([True, False, True], fill_value=False, dtype=np.bool_)\n arr.fill_value = True\n assert arr.fill_value is True\n\n with tm.assert_produces_warning(FutureWarning, match=msg):\n arr.fill_value = 0\n\n arr.fill_value = np.nan\n assert np.isnan(arr.fill_value)\n\n @pytest.mark.parametrize("val", [[1, 2, 3], np.array([1, 2]), (1, 2, 3)])\n def test_set_fill_invalid_non_scalar(self, val):\n arr = SparseArray([True, False, True], fill_value=False, dtype=np.bool_)\n msg = "fill_value must be a scalar"\n\n with pytest.raises(ValueError, match=msg):\n arr.fill_value = val\n\n def test_copy(self, arr):\n arr2 = arr.copy()\n assert arr2.sp_values is not arr.sp_values\n assert arr2.sp_index is arr.sp_index\n\n def test_values_asarray(self, arr_data, arr):\n tm.assert_almost_equal(arr.to_dense(), arr_data)\n\n @pytest.mark.parametrize(\n "data,shape,dtype",\n [\n ([0, 0, 0, 0, 0], (5,), None),\n ([], (0,), None),\n ([0], (1,), None),\n (["A", "A", np.nan, "B"], (4,), object),\n ],\n )\n def test_shape(self, data, shape, dtype):\n # GH 21126\n out = SparseArray(data, dtype=dtype)\n assert out.shape == shape\n\n @pytest.mark.parametrize(\n "vals",\n [\n [np.nan, np.nan, np.nan, np.nan, np.nan],\n [1, np.nan, np.nan, 3, np.nan],\n [1, np.nan, 0, 3, 0],\n ],\n )\n @pytest.mark.parametrize("fill_value", [None, 0])\n def test_dense_repr(self, vals, fill_value):\n vals = np.array(vals)\n arr = SparseArray(vals, fill_value=fill_value)\n\n res = arr.to_dense()\n tm.assert_numpy_array_equal(res, vals)\n\n @pytest.mark.parametrize("fix", ["arr", "zarr"])\n def test_pickle(self, fix, request):\n obj = request.getfixturevalue(fix)\n unpickled = tm.round_trip_pickle(obj)\n tm.assert_sp_array_equal(unpickled, obj)\n\n def test_generator_warnings(self):\n sp_arr = SparseArray([1, 2, 3])\n with tm.assert_produces_warning(None):\n for _ in sp_arr:\n pass\n\n def test_where_retain_fill_value(self):\n # GH#45691 don't lose fill_value on _where\n arr = SparseArray([np.nan, 1.0], fill_value=0)\n\n mask = np.array([True, False])\n\n res = arr._where(~mask, 1)\n exp = SparseArray([1, 1.0], fill_value=0)\n tm.assert_sp_array_equal(res, exp)\n\n ser = pd.Series(arr)\n res = ser.where(~mask, 1)\n tm.assert_series_equal(res, pd.Series(exp))\n\n def test_fillna(self):\n s = SparseArray([1, np.nan, np.nan, 3, np.nan])\n res = s.fillna(-1)\n exp = SparseArray([1, -1, -1, 3, -1], fill_value=-1, dtype=np.float64)\n tm.assert_sp_array_equal(res, exp)\n\n s = SparseArray([1, np.nan, np.nan, 3, np.nan], fill_value=0)\n res = s.fillna(-1)\n exp = SparseArray([1, -1, -1, 3, -1], fill_value=0, dtype=np.float64)\n tm.assert_sp_array_equal(res, exp)\n\n s = SparseArray([1, np.nan, 0, 3, 0])\n res = s.fillna(-1)\n exp = SparseArray([1, -1, 0, 3, 0], fill_value=-1, dtype=np.float64)\n tm.assert_sp_array_equal(res, exp)\n\n s = SparseArray([1, np.nan, 0, 3, 0], fill_value=0)\n res = s.fillna(-1)\n exp = SparseArray([1, -1, 0, 3, 0], fill_value=0, dtype=np.float64)\n tm.assert_sp_array_equal(res, exp)\n\n s = SparseArray([np.nan, np.nan, np.nan, np.nan])\n res = s.fillna(-1)\n exp = SparseArray([-1, -1, -1, -1], fill_value=-1, dtype=np.float64)\n tm.assert_sp_array_equal(res, exp)\n\n s = SparseArray([np.nan, np.nan, np.nan, np.nan], fill_value=0)\n res = s.fillna(-1)\n exp = SparseArray([-1, -1, -1, -1], fill_value=0, dtype=np.float64)\n tm.assert_sp_array_equal(res, exp)\n\n # float dtype's fill_value is np.nan, replaced by -1\n s = SparseArray([0.0, 0.0, 0.0, 0.0])\n res = s.fillna(-1)\n exp = SparseArray([0.0, 0.0, 0.0, 0.0], fill_value=-1)\n tm.assert_sp_array_equal(res, exp)\n\n # int dtype shouldn't have missing. No changes.\n s = SparseArray([0, 0, 0, 0])\n assert s.dtype == SparseDtype(np.int64)\n assert s.fill_value == 0\n res = s.fillna(-1)\n tm.assert_sp_array_equal(res, s)\n\n s = SparseArray([0, 0, 0, 0], fill_value=0)\n assert s.dtype == SparseDtype(np.int64)\n assert s.fill_value == 0\n res = s.fillna(-1)\n exp = SparseArray([0, 0, 0, 0], fill_value=0)\n tm.assert_sp_array_equal(res, exp)\n\n # fill_value can be nan if there is no missing hole.\n # only fill_value will be changed\n s = SparseArray([0, 0, 0, 0], fill_value=np.nan)\n assert s.dtype == SparseDtype(np.int64, fill_value=np.nan)\n assert np.isnan(s.fill_value)\n res = s.fillna(-1)\n exp = SparseArray([0, 0, 0, 0], fill_value=-1)\n tm.assert_sp_array_equal(res, exp)\n\n def test_fillna_overlap(self):\n s = SparseArray([1, np.nan, np.nan, 3, np.nan])\n # filling with existing value doesn't replace existing value with\n # fill_value, i.e. existing 3 remains in sp_values\n res = s.fillna(3)\n exp = np.array([1, 3, 3, 3, 3], dtype=np.float64)\n tm.assert_numpy_array_equal(res.to_dense(), exp)\n\n s = SparseArray([1, np.nan, np.nan, 3, np.nan], fill_value=0)\n res = s.fillna(3)\n exp = SparseArray([1, 3, 3, 3, 3], fill_value=0, dtype=np.float64)\n tm.assert_sp_array_equal(res, exp)\n\n def test_nonzero(self):\n # Tests regression #21172.\n sa = SparseArray([float("nan"), float("nan"), 1, 0, 0, 2, 0, 0, 0, 3, 0, 0])\n expected = np.array([2, 5, 9], dtype=np.int32)\n (result,) = sa.nonzero()\n tm.assert_numpy_array_equal(expected, result)\n\n sa = SparseArray([0, 0, 1, 0, 0, 2, 0, 0, 0, 3, 0, 0])\n (result,) = sa.nonzero()\n tm.assert_numpy_array_equal(expected, result)\n\n\nclass TestSparseArrayAnalytics:\n @pytest.mark.parametrize(\n "data,expected",\n [\n (\n np.array([1, 2, 3, 4, 5], dtype=float), # non-null data\n SparseArray(np.array([1.0, 3.0, 6.0, 10.0, 15.0])),\n ),\n (\n np.array([1, 2, np.nan, 4, 5], dtype=float), # null data\n SparseArray(np.array([1.0, 3.0, np.nan, 7.0, 12.0])),\n ),\n ],\n )\n @pytest.mark.parametrize("numpy", [True, False])\n def test_cumsum(self, data, expected, numpy):\n cumsum = np.cumsum if numpy else lambda s: s.cumsum()\n\n out = cumsum(SparseArray(data))\n tm.assert_sp_array_equal(out, expected)\n\n out = cumsum(SparseArray(data, fill_value=np.nan))\n tm.assert_sp_array_equal(out, expected)\n\n out = cumsum(SparseArray(data, fill_value=2))\n tm.assert_sp_array_equal(out, expected)\n\n if numpy: # numpy compatibility checks.\n msg = "the 'dtype' parameter is not supported"\n with pytest.raises(ValueError, match=msg):\n np.cumsum(SparseArray(data), dtype=np.int64)\n\n msg = "the 'out' parameter is not supported"\n with pytest.raises(ValueError, match=msg):\n np.cumsum(SparseArray(data), out=out)\n else:\n axis = 1 # SparseArray currently 1-D, so only axis = 0 is valid.\n msg = re.escape(f"axis(={axis}) out of bounds")\n with pytest.raises(ValueError, match=msg):\n SparseArray(data).cumsum(axis=axis)\n\n def test_ufunc(self):\n # GH 13853 make sure ufunc is applied to fill_value\n sparse = SparseArray([1, np.nan, 2, np.nan, -2])\n result = SparseArray([1, np.nan, 2, np.nan, 2])\n tm.assert_sp_array_equal(abs(sparse), result)\n tm.assert_sp_array_equal(np.abs(sparse), result)\n\n sparse = SparseArray([1, -1, 2, -2], fill_value=1)\n result = SparseArray([1, 2, 2], sparse_index=sparse.sp_index, fill_value=1)\n tm.assert_sp_array_equal(abs(sparse), result)\n tm.assert_sp_array_equal(np.abs(sparse), result)\n\n sparse = SparseArray([1, -1, 2, -2], fill_value=-1)\n exp = SparseArray([1, 1, 2, 2], fill_value=1)\n tm.assert_sp_array_equal(abs(sparse), exp)\n tm.assert_sp_array_equal(np.abs(sparse), exp)\n\n sparse = SparseArray([1, np.nan, 2, np.nan, -2])\n result = SparseArray(np.sin([1, np.nan, 2, np.nan, -2]))\n tm.assert_sp_array_equal(np.sin(sparse), result)\n\n sparse = SparseArray([1, -1, 2, -2], fill_value=1)\n result = SparseArray(np.sin([1, -1, 2, -2]), fill_value=np.sin(1))\n tm.assert_sp_array_equal(np.sin(sparse), result)\n\n sparse = SparseArray([1, -1, 0, -2], fill_value=0)\n result = SparseArray(np.sin([1, -1, 0, -2]), fill_value=np.sin(0))\n tm.assert_sp_array_equal(np.sin(sparse), result)\n\n def test_ufunc_args(self):\n # GH 13853 make sure ufunc is applied to fill_value, including its arg\n sparse = SparseArray([1, np.nan, 2, np.nan, -2])\n result = SparseArray([2, np.nan, 3, np.nan, -1])\n tm.assert_sp_array_equal(np.add(sparse, 1), result)\n\n sparse = SparseArray([1, -1, 2, -2], fill_value=1)\n result = SparseArray([2, 0, 3, -1], fill_value=2)\n tm.assert_sp_array_equal(np.add(sparse, 1), result)\n\n sparse = SparseArray([1, -1, 0, -2], fill_value=0)\n result = SparseArray([2, 0, 1, -1], fill_value=1)\n tm.assert_sp_array_equal(np.add(sparse, 1), result)\n\n @pytest.mark.parametrize("fill_value", [0.0, np.nan])\n def test_modf(self, fill_value):\n # https://github.com/pandas-dev/pandas/issues/26946\n sparse = SparseArray([fill_value] * 10 + [1.1, 2.2], fill_value=fill_value)\n r1, r2 = np.modf(sparse)\n e1, e2 = np.modf(np.asarray(sparse))\n tm.assert_sp_array_equal(r1, SparseArray(e1, fill_value=fill_value))\n tm.assert_sp_array_equal(r2, SparseArray(e2, fill_value=fill_value))\n\n def test_nbytes_integer(self):\n arr = SparseArray([1, 0, 0, 0, 2], kind="integer")\n result = arr.nbytes\n # (2 * 8) + 2 * 4\n assert result == 24\n\n def test_nbytes_block(self):\n arr = SparseArray([1, 2, 0, 0, 0], kind="block")\n result = arr.nbytes\n # (2 * 8) + 4 + 4\n # sp_values, blocs, blengths\n assert result == 24\n\n def test_asarray_datetime64(self):\n s = SparseArray(pd.to_datetime(["2012", None, None, "2013"]))\n np.asarray(s)\n\n def test_density(self):\n arr = SparseArray([0, 1])\n assert arr.density == 0.5\n\n def test_npoints(self):\n arr = SparseArray([0, 1])\n assert arr.npoints == 1\n\n\ndef test_setting_fill_value_fillna_still_works():\n # This is why letting users update fill_value / dtype is bad\n # astype has the same problem.\n arr = SparseArray([1.0, np.nan, 1.0], fill_value=0.0)\n arr.fill_value = np.nan\n result = arr.isna()\n # Can't do direct comparison, since the sp_index will be different\n # So let's convert to ndarray and check there.\n result = np.asarray(result)\n\n expected = np.array([False, True, False])\n tm.assert_numpy_array_equal(result, expected)\n\n\ndef test_setting_fill_value_updates():\n arr = SparseArray([0.0, np.nan], fill_value=0)\n arr.fill_value = np.nan\n # use private constructor to get the index right\n # otherwise both nans would be un-stored.\n expected = SparseArray._simple_new(\n sparse_array=np.array([np.nan]),\n sparse_index=IntIndex(2, [1]),\n dtype=SparseDtype(float, np.nan),\n )\n tm.assert_sp_array_equal(arr, expected)\n\n\n@pytest.mark.parametrize(\n "arr,fill_value,loc",\n [\n ([None, 1, 2], None, 0),\n ([0, None, 2], None, 1),\n ([0, 1, None], None, 2),\n ([0, 1, 1, None, None], None, 3),\n ([1, 1, 1, 2], None, -1),\n ([], None, -1),\n ([None, 1, 0, 0, None, 2], None, 0),\n ([None, 1, 0, 0, None, 2], 1, 1),\n ([None, 1, 0, 0, None, 2], 2, 5),\n ([None, 1, 0, 0, None, 2], 3, -1),\n ([None, 0, 0, 1, 2, 1], 0, 1),\n ([None, 0, 0, 1, 2, 1], 1, 3),\n ],\n)\ndef test_first_fill_value_loc(arr, fill_value, loc):\n result = SparseArray(arr, fill_value=fill_value)._first_fill_value_loc()\n assert result == loc\n\n\n@pytest.mark.parametrize(\n "arr",\n [\n [1, 2, np.nan, np.nan],\n [1, np.nan, 2, np.nan],\n [1, 2, np.nan],\n [np.nan, 1, 0, 0, np.nan, 2],\n [np.nan, 0, 0, 1, 2, 1],\n ],\n)\n@pytest.mark.parametrize("fill_value", [np.nan, 0, 1])\ndef test_unique_na_fill(arr, fill_value):\n a = SparseArray(arr, fill_value=fill_value).unique()\n b = pd.Series(arr).unique()\n assert isinstance(a, SparseArray)\n a = np.asarray(a)\n tm.assert_numpy_array_equal(a, b)\n\n\ndef test_unique_all_sparse():\n # https://github.com/pandas-dev/pandas/issues/23168\n arr = SparseArray([0, 0])\n result = arr.unique()\n expected = SparseArray([0])\n tm.assert_sp_array_equal(result, expected)\n\n\ndef test_map():\n arr = SparseArray([0, 1, 2])\n expected = SparseArray([10, 11, 12], fill_value=10)\n\n # dict\n result = arr.map({0: 10, 1: 11, 2: 12})\n tm.assert_sp_array_equal(result, expected)\n\n # series\n result = arr.map(pd.Series({0: 10, 1: 11, 2: 12}))\n tm.assert_sp_array_equal(result, expected)\n\n # function\n result = arr.map(pd.Series({0: 10, 1: 11, 2: 12}))\n expected = SparseArray([10, 11, 12], fill_value=10)\n tm.assert_sp_array_equal(result, expected)\n\n\ndef test_map_missing():\n arr = SparseArray([0, 1, 2])\n expected = SparseArray([10, 11, None], fill_value=10)\n\n result = arr.map({0: 10, 1: 11})\n tm.assert_sp_array_equal(result, expected)\n\n\n@pytest.mark.parametrize("fill_value", [np.nan, 1])\ndef test_dropna(fill_value):\n # GH-28287\n arr = SparseArray([np.nan, 1], fill_value=fill_value)\n exp = SparseArray([1.0], fill_value=fill_value)\n tm.assert_sp_array_equal(arr.dropna(), exp)\n\n df = pd.DataFrame({"a": [0, 1], "b": arr})\n expected_df = pd.DataFrame({"a": [1], "b": exp}, index=pd.Index([1]))\n tm.assert_equal(df.dropna(), expected_df)\n\n\ndef test_drop_duplicates_fill_value():\n # GH 11726\n df = pd.DataFrame(np.zeros((5, 5))).apply(lambda x: SparseArray(x, fill_value=0))\n result = df.drop_duplicates()\n expected = pd.DataFrame({i: SparseArray([0.0], fill_value=0) for i in range(5)})\n tm.assert_frame_equal(result, expected)\n\n\ndef test_zero_sparse_column():\n # GH 27781\n df1 = pd.DataFrame({"A": SparseArray([0, 0, 0]), "B": [1, 2, 3]})\n df2 = pd.DataFrame({"A": SparseArray([0, 1, 0]), "B": [1, 2, 3]})\n result = df1.loc[df1["B"] != 2]\n expected = df2.loc[df2["B"] != 2]\n tm.assert_frame_equal(result, expected)\n\n expected = pd.DataFrame({"A": SparseArray([0, 0]), "B": [1, 3]}, index=[0, 2])\n tm.assert_frame_equal(result, expected)\n\n\ndef test_array_interface(arr_data, arr):\n # https://github.com/pandas-dev/pandas/pull/60046\n result = np.asarray(arr)\n tm.assert_numpy_array_equal(result, arr_data)\n\n # it always gives a copy by default\n result_copy1 = np.asarray(arr)\n result_copy2 = np.asarray(arr)\n assert not np.may_share_memory(result_copy1, result_copy2)\n\n # or with explicit copy=True\n result_copy1 = np.array(arr, copy=True)\n result_copy2 = np.array(arr, copy=True)\n assert not np.may_share_memory(result_copy1, result_copy2)\n\n if not np_version_gt2:\n # copy=False semantics are only supported in NumPy>=2.\n return\n\n msg = "Starting with NumPy 2.0, the behavior of the 'copy' keyword has changed"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n np.array(arr, copy=False)\n\n # except when there are actually no sparse filled values\n arr2 = SparseArray(np.array([1, 2, 3]))\n result_nocopy1 = np.array(arr2, copy=False)\n result_nocopy2 = np.array(arr2, copy=False)\n assert np.may_share_memory(result_nocopy1, result_nocopy2)\n
.venv\Lib\site-packages\pandas\tests\arrays\sparse\test_array.py
test_array.py
Python
17,929
0.95
0.09002
0.082927
python-kit
399
2024-06-19T17:14:29.963088
BSD-3-Clause
true
ac5df0e78f366ba1050897c7caf3a48b
import numpy as np\nimport pytest\n\nfrom pandas._libs.sparse import IntIndex\n\nfrom pandas import (\n SparseDtype,\n Timestamp,\n)\nimport pandas._testing as tm\nfrom pandas.core.arrays.sparse import SparseArray\n\n\nclass TestAstype:\n def test_astype(self):\n # float -> float\n arr = SparseArray([None, None, 0, 2])\n result = arr.astype("Sparse[float32]")\n expected = SparseArray([None, None, 0, 2], dtype=np.dtype("float32"))\n tm.assert_sp_array_equal(result, expected)\n\n dtype = SparseDtype("float64", fill_value=0)\n result = arr.astype(dtype)\n expected = SparseArray._simple_new(\n np.array([0.0, 2.0], dtype=dtype.subtype), IntIndex(4, [2, 3]), dtype\n )\n tm.assert_sp_array_equal(result, expected)\n\n dtype = SparseDtype("int64", 0)\n result = arr.astype(dtype)\n expected = SparseArray._simple_new(\n np.array([0, 2], dtype=np.int64), IntIndex(4, [2, 3]), dtype\n )\n tm.assert_sp_array_equal(result, expected)\n\n arr = SparseArray([0, np.nan, 0, 1], fill_value=0)\n with pytest.raises(ValueError, match="NA"):\n arr.astype("Sparse[i8]")\n\n def test_astype_bool(self):\n a = SparseArray([1, 0, 0, 1], dtype=SparseDtype(int, 0))\n result = a.astype(bool)\n expected = np.array([1, 0, 0, 1], dtype=bool)\n tm.assert_numpy_array_equal(result, expected)\n\n # update fill value\n result = a.astype(SparseDtype(bool, False))\n expected = SparseArray(\n [True, False, False, True], dtype=SparseDtype(bool, False)\n )\n tm.assert_sp_array_equal(result, expected)\n\n def test_astype_all(self, any_real_numpy_dtype):\n vals = np.array([1, 2, 3])\n arr = SparseArray(vals, fill_value=1)\n typ = np.dtype(any_real_numpy_dtype)\n res = arr.astype(typ)\n tm.assert_numpy_array_equal(res, vals.astype(any_real_numpy_dtype))\n\n @pytest.mark.parametrize(\n "arr, dtype, expected",\n [\n (\n SparseArray([0, 1]),\n "float",\n SparseArray([0.0, 1.0], dtype=SparseDtype(float, 0.0)),\n ),\n (SparseArray([0, 1]), bool, SparseArray([False, True])),\n (\n SparseArray([0, 1], fill_value=1),\n bool,\n SparseArray([False, True], dtype=SparseDtype(bool, True)),\n ),\n pytest.param(\n SparseArray([0, 1]),\n "datetime64[ns]",\n SparseArray(\n np.array([0, 1], dtype="datetime64[ns]"),\n dtype=SparseDtype("datetime64[ns]", Timestamp("1970")),\n ),\n ),\n (\n SparseArray([0, 1, 10]),\n np.str_,\n SparseArray(["0", "1", "10"], dtype=SparseDtype(np.str_, "0")),\n ),\n (SparseArray(["10", "20"]), float, SparseArray([10.0, 20.0])),\n (\n SparseArray([0, 1, 0]),\n object,\n SparseArray([0, 1, 0], dtype=SparseDtype(object, 0)),\n ),\n ],\n )\n def test_astype_more(self, arr, dtype, expected):\n result = arr.astype(arr.dtype.update_dtype(dtype))\n tm.assert_sp_array_equal(result, expected)\n\n def test_astype_nan_raises(self):\n arr = SparseArray([1.0, np.nan])\n with pytest.raises(ValueError, match="Cannot convert non-finite"):\n arr.astype(int)\n\n def test_astype_copy_false(self):\n # GH#34456 bug caused by using .view instead of .astype in astype_nansafe\n arr = SparseArray([1, 2, 3])\n\n dtype = SparseDtype(float, 0)\n\n result = arr.astype(dtype, copy=False)\n expected = SparseArray([1.0, 2.0, 3.0], fill_value=0.0)\n tm.assert_sp_array_equal(result, expected)\n\n def test_astype_dt64_to_int64(self):\n # GH#49631 match non-sparse behavior\n values = np.array(["NaT", "2016-01-02", "2016-01-03"], dtype="M8[ns]")\n\n arr = SparseArray(values)\n result = arr.astype("int64")\n expected = values.astype("int64")\n tm.assert_numpy_array_equal(result, expected)\n\n # we should also be able to cast to equivalent Sparse[int64]\n dtype_int64 = SparseDtype("int64", np.iinfo(np.int64).min)\n result2 = arr.astype(dtype_int64)\n tm.assert_numpy_array_equal(result2.to_numpy(), expected)\n\n # GH#50087 we should match the non-sparse behavior regardless of\n # if we have a fill_value other than NaT\n dtype = SparseDtype("datetime64[ns]", values[1])\n arr3 = SparseArray(values, dtype=dtype)\n result3 = arr3.astype("int64")\n tm.assert_numpy_array_equal(result3, expected)\n
.venv\Lib\site-packages\pandas\tests\arrays\sparse\test_astype.py
test_astype.py
Python
4,771
0.95
0.067669
0.061404
python-kit
667
2025-03-31T02:30:20.080119
Apache-2.0
true
884774c82441cfc980590cf456dbc801
import numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.core.arrays.sparse import SparseArray\n\n\nclass TestSparseArrayConcat:\n @pytest.mark.parametrize("kind", ["integer", "block"])\n def test_basic(self, kind):\n a = SparseArray([1, 0, 0, 2], kind=kind)\n b = SparseArray([1, 0, 2, 2], kind=kind)\n\n result = SparseArray._concat_same_type([a, b])\n # Can't make any assertions about the sparse index itself\n # since we aren't don't merge sparse blocs across arrays\n # in to_concat\n expected = np.array([1, 2, 1, 2, 2], dtype="int64")\n tm.assert_numpy_array_equal(result.sp_values, expected)\n assert result.kind == kind\n\n @pytest.mark.parametrize("kind", ["integer", "block"])\n def test_uses_first_kind(self, kind):\n other = "integer" if kind == "block" else "block"\n a = SparseArray([1, 0, 0, 2], kind=kind)\n b = SparseArray([1, 0, 2, 2], kind=other)\n\n result = SparseArray._concat_same_type([a, b])\n expected = np.array([1, 2, 1, 2, 2], dtype="int64")\n tm.assert_numpy_array_equal(result.sp_values, expected)\n assert result.kind == kind\n\n\n@pytest.mark.parametrize(\n "other, expected_dtype",\n [\n # compatible dtype -> preserve sparse\n (pd.Series([3, 4, 5], dtype="int64"), pd.SparseDtype("int64", 0)),\n # (pd.Series([3, 4, 5], dtype="Int64"), pd.SparseDtype("int64", 0)),\n # incompatible dtype -> Sparse[common dtype]\n (pd.Series([1.5, 2.5, 3.5], dtype="float64"), pd.SparseDtype("float64", 0)),\n # incompatible dtype -> Sparse[object] dtype\n (pd.Series(["a", "b", "c"], dtype=object), pd.SparseDtype(object, 0)),\n # categorical with compatible categories -> dtype of the categories\n (pd.Series([3, 4, 5], dtype="category"), np.dtype("int64")),\n (pd.Series([1.5, 2.5, 3.5], dtype="category"), np.dtype("float64")),\n # categorical with incompatible categories -> object dtype\n (pd.Series(["a", "b", "c"], dtype="category"), np.dtype(object)),\n ],\n)\ndef test_concat_with_non_sparse(other, expected_dtype):\n # https://github.com/pandas-dev/pandas/issues/34336\n s_sparse = pd.Series([1, 0, 2], dtype=pd.SparseDtype("int64", 0))\n\n result = pd.concat([s_sparse, other], ignore_index=True)\n expected = pd.Series(list(s_sparse) + list(other)).astype(expected_dtype)\n tm.assert_series_equal(result, expected)\n\n result = pd.concat([other, s_sparse], ignore_index=True)\n expected = pd.Series(list(other) + list(s_sparse)).astype(expected_dtype)\n tm.assert_series_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\arrays\sparse\test_combine_concat.py
test_combine_concat.py
Python
2,651
0.95
0.080645
0.192308
react-lib
858
2025-05-30T10:02:26.625909
GPL-3.0
true
a7a2665c4b78e5391d3166a97e3a4ba6
import numpy as np\nimport pytest\n\nfrom pandas._libs.sparse import IntIndex\n\nimport pandas as pd\nfrom pandas import (\n SparseDtype,\n isna,\n)\nimport pandas._testing as tm\nfrom pandas.core.arrays.sparse import SparseArray\n\n\nclass TestConstructors:\n def test_constructor_dtype(self):\n arr = SparseArray([np.nan, 1, 2, np.nan])\n assert arr.dtype == SparseDtype(np.float64, np.nan)\n assert arr.dtype.subtype == np.float64\n assert np.isnan(arr.fill_value)\n\n arr = SparseArray([np.nan, 1, 2, np.nan], fill_value=0)\n assert arr.dtype == SparseDtype(np.float64, 0)\n assert arr.fill_value == 0\n\n arr = SparseArray([0, 1, 2, 4], dtype=np.float64)\n assert arr.dtype == SparseDtype(np.float64, np.nan)\n assert np.isnan(arr.fill_value)\n\n arr = SparseArray([0, 1, 2, 4], dtype=np.int64)\n assert arr.dtype == SparseDtype(np.int64, 0)\n assert arr.fill_value == 0\n\n arr = SparseArray([0, 1, 2, 4], fill_value=0, dtype=np.int64)\n assert arr.dtype == SparseDtype(np.int64, 0)\n assert arr.fill_value == 0\n\n arr = SparseArray([0, 1, 2, 4], dtype=None)\n assert arr.dtype == SparseDtype(np.int64, 0)\n assert arr.fill_value == 0\n\n arr = SparseArray([0, 1, 2, 4], fill_value=0, dtype=None)\n assert arr.dtype == SparseDtype(np.int64, 0)\n assert arr.fill_value == 0\n\n def test_constructor_dtype_str(self):\n result = SparseArray([1, 2, 3], dtype="int")\n expected = SparseArray([1, 2, 3], dtype=int)\n tm.assert_sp_array_equal(result, expected)\n\n def test_constructor_sparse_dtype(self):\n result = SparseArray([1, 0, 0, 1], dtype=SparseDtype("int64", -1))\n expected = SparseArray([1, 0, 0, 1], fill_value=-1, dtype=np.int64)\n tm.assert_sp_array_equal(result, expected)\n assert result.sp_values.dtype == np.dtype("int64")\n\n def test_constructor_sparse_dtype_str(self):\n result = SparseArray([1, 0, 0, 1], dtype="Sparse[int32]")\n expected = SparseArray([1, 0, 0, 1], dtype=np.int32)\n tm.assert_sp_array_equal(result, expected)\n assert result.sp_values.dtype == np.dtype("int32")\n\n def test_constructor_object_dtype(self):\n # GH#11856\n arr = SparseArray(["A", "A", np.nan, "B"], dtype=object)\n assert arr.dtype == SparseDtype(object)\n assert np.isnan(arr.fill_value)\n\n arr = SparseArray(["A", "A", np.nan, "B"], dtype=object, fill_value="A")\n assert arr.dtype == SparseDtype(object, "A")\n assert arr.fill_value == "A"\n\n def test_constructor_object_dtype_bool_fill(self):\n # GH#17574\n data = [False, 0, 100.0, 0.0]\n arr = SparseArray(data, dtype=object, fill_value=False)\n assert arr.dtype == SparseDtype(object, False)\n assert arr.fill_value is False\n arr_expected = np.array(data, dtype=object)\n it = (type(x) == type(y) and x == y for x, y in zip(arr, arr_expected))\n assert np.fromiter(it, dtype=np.bool_).all()\n\n @pytest.mark.parametrize("dtype", [SparseDtype(int, 0), int])\n def test_constructor_na_dtype(self, dtype):\n with pytest.raises(ValueError, match="Cannot convert"):\n SparseArray([0, 1, np.nan], dtype=dtype)\n\n def test_constructor_warns_when_losing_timezone(self):\n # GH#32501 warn when losing timezone information\n dti = pd.date_range("2016-01-01", periods=3, tz="US/Pacific")\n\n expected = SparseArray(np.asarray(dti, dtype="datetime64[ns]"))\n\n with tm.assert_produces_warning(UserWarning):\n result = SparseArray(dti)\n\n tm.assert_sp_array_equal(result, expected)\n\n with tm.assert_produces_warning(UserWarning):\n result = SparseArray(pd.Series(dti))\n\n tm.assert_sp_array_equal(result, expected)\n\n def test_constructor_spindex_dtype(self):\n arr = SparseArray(data=[1, 2], sparse_index=IntIndex(4, [1, 2]))\n # TODO: actionable?\n # XXX: Behavior change: specifying SparseIndex no longer changes the\n # fill_value\n expected = SparseArray([0, 1, 2, 0], kind="integer")\n tm.assert_sp_array_equal(arr, expected)\n assert arr.dtype == SparseDtype(np.int64)\n assert arr.fill_value == 0\n\n arr = SparseArray(\n data=[1, 2, 3],\n sparse_index=IntIndex(4, [1, 2, 3]),\n dtype=np.int64,\n fill_value=0,\n )\n exp = SparseArray([0, 1, 2, 3], dtype=np.int64, fill_value=0)\n tm.assert_sp_array_equal(arr, exp)\n assert arr.dtype == SparseDtype(np.int64)\n assert arr.fill_value == 0\n\n arr = SparseArray(\n data=[1, 2], sparse_index=IntIndex(4, [1, 2]), fill_value=0, dtype=np.int64\n )\n exp = SparseArray([0, 1, 2, 0], fill_value=0, dtype=np.int64)\n tm.assert_sp_array_equal(arr, exp)\n assert arr.dtype == SparseDtype(np.int64)\n assert arr.fill_value == 0\n\n arr = SparseArray(\n data=[1, 2, 3],\n sparse_index=IntIndex(4, [1, 2, 3]),\n dtype=None,\n fill_value=0,\n )\n exp = SparseArray([0, 1, 2, 3], dtype=None)\n tm.assert_sp_array_equal(arr, exp)\n assert arr.dtype == SparseDtype(np.int64)\n assert arr.fill_value == 0\n\n @pytest.mark.parametrize("sparse_index", [None, IntIndex(1, [0])])\n def test_constructor_spindex_dtype_scalar(self, sparse_index):\n # scalar input\n msg = "Constructing SparseArray with scalar data is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n arr = SparseArray(data=1, sparse_index=sparse_index, dtype=None)\n exp = SparseArray([1], dtype=None)\n tm.assert_sp_array_equal(arr, exp)\n assert arr.dtype == SparseDtype(np.int64)\n assert arr.fill_value == 0\n\n with tm.assert_produces_warning(FutureWarning, match=msg):\n arr = SparseArray(data=1, sparse_index=IntIndex(1, [0]), dtype=None)\n exp = SparseArray([1], dtype=None)\n tm.assert_sp_array_equal(arr, exp)\n assert arr.dtype == SparseDtype(np.int64)\n assert arr.fill_value == 0\n\n def test_constructor_spindex_dtype_scalar_broadcasts(self):\n arr = SparseArray(\n data=[1, 2], sparse_index=IntIndex(4, [1, 2]), fill_value=0, dtype=None\n )\n exp = SparseArray([0, 1, 2, 0], fill_value=0, dtype=None)\n tm.assert_sp_array_equal(arr, exp)\n assert arr.dtype == SparseDtype(np.int64)\n assert arr.fill_value == 0\n\n @pytest.mark.parametrize(\n "data, fill_value",\n [\n (np.array([1, 2]), 0),\n (np.array([1.0, 2.0]), np.nan),\n ([True, False], False),\n ([pd.Timestamp("2017-01-01")], pd.NaT),\n ],\n )\n def test_constructor_inferred_fill_value(self, data, fill_value):\n result = SparseArray(data).fill_value\n\n if isna(fill_value):\n assert isna(result)\n else:\n assert result == fill_value\n\n @pytest.mark.parametrize("format", ["coo", "csc", "csr"])\n @pytest.mark.parametrize("size", [0, 10])\n def test_from_spmatrix(self, size, format):\n sp_sparse = pytest.importorskip("scipy.sparse")\n\n mat = sp_sparse.random(size, 1, density=0.5, format=format)\n result = SparseArray.from_spmatrix(mat)\n\n result = np.asarray(result)\n expected = mat.toarray().ravel()\n tm.assert_numpy_array_equal(result, expected)\n\n @pytest.mark.parametrize("format", ["coo", "csc", "csr"])\n def test_from_spmatrix_including_explicit_zero(self, format):\n sp_sparse = pytest.importorskip("scipy.sparse")\n\n mat = sp_sparse.random(10, 1, density=0.5, format=format)\n mat.data[0] = 0\n result = SparseArray.from_spmatrix(mat)\n\n result = np.asarray(result)\n expected = mat.toarray().ravel()\n tm.assert_numpy_array_equal(result, expected)\n\n def test_from_spmatrix_raises(self):\n sp_sparse = pytest.importorskip("scipy.sparse")\n\n mat = sp_sparse.eye(5, 4, format="csc")\n\n with pytest.raises(ValueError, match="not '4'"):\n SparseArray.from_spmatrix(mat)\n\n def test_constructor_from_too_large_array(self):\n with pytest.raises(TypeError, match="expected dimension <= 1 data"):\n SparseArray(np.arange(10).reshape((2, 5)))\n\n def test_constructor_from_sparse(self):\n zarr = SparseArray([0, 0, 1, 2, 3, 0, 4, 5, 0, 6], fill_value=0)\n res = SparseArray(zarr)\n assert res.fill_value == 0\n tm.assert_almost_equal(res.sp_values, zarr.sp_values)\n\n def test_constructor_copy(self):\n arr_data = np.array([np.nan, np.nan, 1, 2, 3, np.nan, 4, 5, np.nan, 6])\n arr = SparseArray(arr_data)\n\n cp = SparseArray(arr, copy=True)\n cp.sp_values[:3] = 0\n assert not (arr.sp_values[:3] == 0).any()\n\n not_copy = SparseArray(arr)\n not_copy.sp_values[:3] = 0\n assert (arr.sp_values[:3] == 0).all()\n\n def test_constructor_bool(self):\n # GH#10648\n data = np.array([False, False, True, True, False, False])\n arr = SparseArray(data, fill_value=False, dtype=bool)\n\n assert arr.dtype == SparseDtype(bool)\n tm.assert_numpy_array_equal(arr.sp_values, np.array([True, True]))\n # Behavior change: np.asarray densifies.\n # tm.assert_numpy_array_equal(arr.sp_values, np.asarray(arr))\n tm.assert_numpy_array_equal(arr.sp_index.indices, np.array([2, 3], np.int32))\n\n dense = arr.to_dense()\n assert dense.dtype == bool\n tm.assert_numpy_array_equal(dense, data)\n\n def test_constructor_bool_fill_value(self):\n arr = SparseArray([True, False, True], dtype=None)\n assert arr.dtype == SparseDtype(np.bool_)\n assert not arr.fill_value\n\n arr = SparseArray([True, False, True], dtype=np.bool_)\n assert arr.dtype == SparseDtype(np.bool_)\n assert not arr.fill_value\n\n arr = SparseArray([True, False, True], dtype=np.bool_, fill_value=True)\n assert arr.dtype == SparseDtype(np.bool_, True)\n assert arr.fill_value\n\n def test_constructor_float32(self):\n # GH#10648\n data = np.array([1.0, np.nan, 3], dtype=np.float32)\n arr = SparseArray(data, dtype=np.float32)\n\n assert arr.dtype == SparseDtype(np.float32)\n tm.assert_numpy_array_equal(arr.sp_values, np.array([1, 3], dtype=np.float32))\n # Behavior change: np.asarray densifies.\n # tm.assert_numpy_array_equal(arr.sp_values, np.asarray(arr))\n tm.assert_numpy_array_equal(\n arr.sp_index.indices, np.array([0, 2], dtype=np.int32)\n )\n\n dense = arr.to_dense()\n assert dense.dtype == np.float32\n tm.assert_numpy_array_equal(dense, data)\n
.venv\Lib\site-packages\pandas\tests\arrays\sparse\test_constructors.py
test_constructors.py
Python
10,835
0.95
0.084211
0.056522
vue-tools
938
2024-03-23T18:28:26.641248
MIT
true
3cd0c309991692d70d7ca7f5ad9c360c
import re\nimport warnings\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import SparseDtype\n\n\n@pytest.mark.parametrize(\n "dtype, fill_value",\n [\n ("int", 0),\n ("float", np.nan),\n ("bool", False),\n ("object", np.nan),\n ("datetime64[ns]", np.datetime64("NaT", "ns")),\n ("timedelta64[ns]", np.timedelta64("NaT", "ns")),\n ],\n)\ndef test_inferred_dtype(dtype, fill_value):\n sparse_dtype = SparseDtype(dtype)\n result = sparse_dtype.fill_value\n if pd.isna(fill_value):\n assert pd.isna(result) and type(result) == type(fill_value)\n else:\n assert result == fill_value\n\n\ndef test_from_sparse_dtype():\n dtype = SparseDtype("float", 0)\n result = SparseDtype(dtype)\n assert result.fill_value == 0\n\n\ndef test_from_sparse_dtype_fill_value():\n dtype = SparseDtype("int", 1)\n result = SparseDtype(dtype, fill_value=2)\n expected = SparseDtype("int", 2)\n assert result == expected\n\n\n@pytest.mark.parametrize(\n "dtype, fill_value",\n [\n ("int", None),\n ("float", None),\n ("bool", None),\n ("object", None),\n ("datetime64[ns]", None),\n ("timedelta64[ns]", None),\n ("int", np.nan),\n ("float", 0),\n ],\n)\ndef test_equal(dtype, fill_value):\n a = SparseDtype(dtype, fill_value)\n b = SparseDtype(dtype, fill_value)\n assert a == b\n assert b == a\n\n\ndef test_nans_equal():\n a = SparseDtype(float, float("nan"))\n b = SparseDtype(float, np.nan)\n assert a == b\n assert b == a\n\n\nwith warnings.catch_warnings():\n msg = "Allowing arbitrary scalar fill_value in SparseDtype is deprecated"\n warnings.filterwarnings("ignore", msg, category=FutureWarning)\n\n tups = [\n (SparseDtype("float64"), SparseDtype("float32")),\n (SparseDtype("float64"), SparseDtype("float64", 0)),\n (SparseDtype("float64"), SparseDtype("datetime64[ns]", np.nan)),\n (SparseDtype(int, pd.NaT), SparseDtype(float, pd.NaT)),\n (SparseDtype("float64"), np.dtype("float64")),\n ]\n\n\n@pytest.mark.parametrize(\n "a, b",\n tups,\n)\ndef test_not_equal(a, b):\n assert a != b\n\n\ndef test_construct_from_string_raises():\n with pytest.raises(\n TypeError, match="Cannot construct a 'SparseDtype' from 'not a dtype'"\n ):\n SparseDtype.construct_from_string("not a dtype")\n\n\n@pytest.mark.parametrize(\n "dtype, expected",\n [\n (SparseDtype(int), True),\n (SparseDtype(float), True),\n (SparseDtype(bool), True),\n (SparseDtype(object), False),\n (SparseDtype(str), False),\n ],\n)\ndef test_is_numeric(dtype, expected):\n assert dtype._is_numeric is expected\n\n\ndef test_str_uses_object():\n result = SparseDtype(str).subtype\n assert result == np.dtype("object")\n\n\n@pytest.mark.parametrize(\n "string, expected",\n [\n ("Sparse[float64]", SparseDtype(np.dtype("float64"))),\n ("Sparse[float32]", SparseDtype(np.dtype("float32"))),\n ("Sparse[int]", SparseDtype(np.dtype("int"))),\n ("Sparse[str]", SparseDtype(np.dtype("str"))),\n ("Sparse[datetime64[ns]]", SparseDtype(np.dtype("datetime64[ns]"))),\n ("Sparse", SparseDtype(np.dtype("float"), np.nan)),\n ],\n)\ndef test_construct_from_string(string, expected):\n result = SparseDtype.construct_from_string(string)\n assert result == expected\n\n\n@pytest.mark.parametrize(\n "a, b, expected",\n [\n (SparseDtype(float, 0.0), SparseDtype(np.dtype("float"), 0.0), True),\n (SparseDtype(int, 0), SparseDtype(int, 0), True),\n (SparseDtype(float, float("nan")), SparseDtype(float, np.nan), True),\n (SparseDtype(float, 0), SparseDtype(float, np.nan), False),\n (SparseDtype(int, 0.0), SparseDtype(float, 0.0), False),\n ],\n)\ndef test_hash_equal(a, b, expected):\n result = a == b\n assert result is expected\n\n result = hash(a) == hash(b)\n assert result is expected\n\n\n@pytest.mark.parametrize(\n "string, expected",\n [\n ("Sparse[int]", "int"),\n ("Sparse[int, 0]", "int"),\n ("Sparse[int64]", "int64"),\n ("Sparse[int64, 0]", "int64"),\n ("Sparse[datetime64[ns], 0]", "datetime64[ns]"),\n ],\n)\ndef test_parse_subtype(string, expected):\n subtype, _ = SparseDtype._parse_subtype(string)\n assert subtype == expected\n\n\n@pytest.mark.parametrize(\n "string", ["Sparse[int, 1]", "Sparse[float, 0.0]", "Sparse[bool, True]"]\n)\ndef test_construct_from_string_fill_value_raises(string):\n with pytest.raises(TypeError, match="fill_value in the string is not"):\n SparseDtype.construct_from_string(string)\n\n\n@pytest.mark.parametrize(\n "original, dtype, expected",\n [\n (SparseDtype(int, 0), float, SparseDtype(float, 0.0)),\n (SparseDtype(int, 1), float, SparseDtype(float, 1.0)),\n (SparseDtype(int, 1), np.str_, SparseDtype(object, "1")),\n (SparseDtype(float, 1.5), int, SparseDtype(int, 1)),\n ],\n)\ndef test_update_dtype(original, dtype, expected):\n result = original.update_dtype(dtype)\n assert result == expected\n\n\n@pytest.mark.parametrize(\n "original, dtype, expected_error_msg",\n [\n (\n SparseDtype(float, np.nan),\n int,\n re.escape("Cannot convert non-finite values (NA or inf) to integer"),\n ),\n (\n SparseDtype(str, "abc"),\n int,\n r"invalid literal for int\(\) with base 10: ('abc'|np\.str_\('abc'\))",\n ),\n ],\n)\ndef test_update_dtype_raises(original, dtype, expected_error_msg):\n with pytest.raises(ValueError, match=expected_error_msg):\n original.update_dtype(dtype)\n\n\ndef test_repr():\n # GH-34352\n result = str(SparseDtype("int64", fill_value=0))\n expected = "Sparse[int64, 0]"\n assert result == expected\n\n result = str(SparseDtype(object, fill_value="0"))\n expected = "Sparse[object, '0']"\n assert result == expected\n\n\ndef test_sparse_dtype_subtype_must_be_numpy_dtype():\n # GH#53160\n msg = "SparseDtype subtype must be a numpy dtype"\n with pytest.raises(TypeError, match=msg):\n SparseDtype("category", fill_value="c")\n
.venv\Lib\site-packages\pandas\tests\arrays\sparse\test_dtype.py
test_dtype.py
Python
6,126
0.95
0.084821
0.010929
python-kit
801
2025-02-06T11:34:02.221047
MIT
true
66bf0fbbb11dc28664eb9520b2476c82
import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import SparseDtype\nimport pandas._testing as tm\nfrom pandas.core.arrays.sparse import SparseArray\n\n\n@pytest.fixture\ndef arr_data():\n return np.array([np.nan, np.nan, 1, 2, 3, np.nan, 4, 5, np.nan, 6])\n\n\n@pytest.fixture\ndef arr(arr_data):\n return SparseArray(arr_data)\n\n\nclass TestGetitem:\n def test_getitem(self, arr):\n dense = arr.to_dense()\n for i, value in enumerate(arr):\n tm.assert_almost_equal(value, dense[i])\n tm.assert_almost_equal(arr[-i], dense[-i])\n\n def test_getitem_arraylike_mask(self, arr):\n arr = SparseArray([0, 1, 2])\n result = arr[[True, False, True]]\n expected = SparseArray([0, 2])\n tm.assert_sp_array_equal(result, expected)\n\n @pytest.mark.parametrize(\n "slc",\n [\n np.s_[:],\n np.s_[1:10],\n np.s_[1:100],\n np.s_[10:1],\n np.s_[:-3],\n np.s_[-5:-4],\n np.s_[:-12],\n np.s_[-12:],\n np.s_[2:],\n np.s_[2::3],\n np.s_[::2],\n np.s_[::-1],\n np.s_[::-2],\n np.s_[1:6:2],\n np.s_[:-6:-2],\n ],\n )\n @pytest.mark.parametrize(\n "as_dense", [[np.nan] * 10, [1] * 10, [np.nan] * 5 + [1] * 5, []]\n )\n def test_getslice(self, slc, as_dense):\n as_dense = np.array(as_dense)\n arr = SparseArray(as_dense)\n\n result = arr[slc]\n expected = SparseArray(as_dense[slc])\n\n tm.assert_sp_array_equal(result, expected)\n\n def test_getslice_tuple(self):\n dense = np.array([np.nan, 0, 3, 4, 0, 5, np.nan, np.nan, 0])\n\n sparse = SparseArray(dense)\n res = sparse[(slice(4, None),)]\n exp = SparseArray(dense[4:])\n tm.assert_sp_array_equal(res, exp)\n\n sparse = SparseArray(dense, fill_value=0)\n res = sparse[(slice(4, None),)]\n exp = SparseArray(dense[4:], fill_value=0)\n tm.assert_sp_array_equal(res, exp)\n\n msg = "too many indices for array"\n with pytest.raises(IndexError, match=msg):\n sparse[4:, :]\n\n with pytest.raises(IndexError, match=msg):\n # check numpy compat\n dense[4:, :]\n\n def test_boolean_slice_empty(self):\n arr = SparseArray([0, 1, 2])\n res = arr[[False, False, False]]\n assert res.dtype == arr.dtype\n\n def test_getitem_bool_sparse_array(self, arr):\n # GH 23122\n spar_bool = SparseArray([False, True] * 5, dtype=np.bool_, fill_value=True)\n exp = SparseArray([np.nan, 2, np.nan, 5, 6])\n tm.assert_sp_array_equal(arr[spar_bool], exp)\n\n spar_bool = ~spar_bool\n res = arr[spar_bool]\n exp = SparseArray([np.nan, 1, 3, 4, np.nan])\n tm.assert_sp_array_equal(res, exp)\n\n spar_bool = SparseArray(\n [False, True, np.nan] * 3, dtype=np.bool_, fill_value=np.nan\n )\n res = arr[spar_bool]\n exp = SparseArray([np.nan, 3, 5])\n tm.assert_sp_array_equal(res, exp)\n\n def test_getitem_bool_sparse_array_as_comparison(self):\n # GH 45110\n arr = SparseArray([1, 2, 3, 4, np.nan, np.nan], fill_value=np.nan)\n res = arr[arr > 2]\n exp = SparseArray([3.0, 4.0], fill_value=np.nan)\n tm.assert_sp_array_equal(res, exp)\n\n def test_get_item(self, arr):\n zarr = SparseArray([0, 0, 1, 2, 3, 0, 4, 5, 0, 6], fill_value=0)\n\n assert np.isnan(arr[1])\n assert arr[2] == 1\n assert arr[7] == 5\n\n assert zarr[0] == 0\n assert zarr[2] == 1\n assert zarr[7] == 5\n\n errmsg = "must be an integer between -10 and 10"\n\n with pytest.raises(IndexError, match=errmsg):\n arr[11]\n\n with pytest.raises(IndexError, match=errmsg):\n arr[-11]\n\n assert arr[-1] == arr[len(arr) - 1]\n\n\nclass TestSetitem:\n def test_set_item(self, arr_data):\n arr = SparseArray(arr_data).copy()\n\n def setitem():\n arr[5] = 3\n\n def setslice():\n arr[1:5] = 2\n\n with pytest.raises(TypeError, match="assignment via setitem"):\n setitem()\n\n with pytest.raises(TypeError, match="assignment via setitem"):\n setslice()\n\n\nclass TestTake:\n def test_take_scalar_raises(self, arr):\n msg = "'indices' must be an array, not a scalar '2'."\n with pytest.raises(ValueError, match=msg):\n arr.take(2)\n\n def test_take(self, arr_data, arr):\n exp = SparseArray(np.take(arr_data, [2, 3]))\n tm.assert_sp_array_equal(arr.take([2, 3]), exp)\n\n exp = SparseArray(np.take(arr_data, [0, 1, 2]))\n tm.assert_sp_array_equal(arr.take([0, 1, 2]), exp)\n\n def test_take_all_empty(self):\n sparse = pd.array([0, 0], dtype=SparseDtype("int64"))\n result = sparse.take([0, 1], allow_fill=True, fill_value=np.nan)\n tm.assert_sp_array_equal(sparse, result)\n\n def test_take_different_fill_value(self):\n # Take with a different fill value shouldn't overwrite the original\n sparse = pd.array([0.0], dtype=SparseDtype("float64", fill_value=0.0))\n result = sparse.take([0, -1], allow_fill=True, fill_value=np.nan)\n expected = pd.array([0, np.nan], dtype=sparse.dtype)\n tm.assert_sp_array_equal(expected, result)\n\n def test_take_fill_value(self):\n data = np.array([1, np.nan, 0, 3, 0])\n sparse = SparseArray(data, fill_value=0)\n\n exp = SparseArray(np.take(data, [0]), fill_value=0)\n tm.assert_sp_array_equal(sparse.take([0]), exp)\n\n exp = SparseArray(np.take(data, [1, 3, 4]), fill_value=0)\n tm.assert_sp_array_equal(sparse.take([1, 3, 4]), exp)\n\n def test_take_negative(self, arr_data, arr):\n exp = SparseArray(np.take(arr_data, [-1]))\n tm.assert_sp_array_equal(arr.take([-1]), exp)\n\n exp = SparseArray(np.take(arr_data, [-4, -3, -2]))\n tm.assert_sp_array_equal(arr.take([-4, -3, -2]), exp)\n\n def test_bad_take(self, arr):\n with pytest.raises(IndexError, match="bounds"):\n arr.take([11])\n\n def test_take_filling(self):\n # similar tests as GH 12631\n sparse = SparseArray([np.nan, np.nan, 1, np.nan, 4])\n result = sparse.take(np.array([1, 0, -1]))\n expected = SparseArray([np.nan, np.nan, 4])\n tm.assert_sp_array_equal(result, expected)\n\n # TODO: actionable?\n # XXX: test change: fill_value=True -> allow_fill=True\n result = sparse.take(np.array([1, 0, -1]), allow_fill=True)\n expected = SparseArray([np.nan, np.nan, np.nan])\n tm.assert_sp_array_equal(result, expected)\n\n # allow_fill=False\n result = sparse.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True)\n expected = SparseArray([np.nan, np.nan, 4])\n tm.assert_sp_array_equal(result, expected)\n\n msg = "Invalid value in 'indices'"\n with pytest.raises(ValueError, match=msg):\n sparse.take(np.array([1, 0, -2]), allow_fill=True)\n\n with pytest.raises(ValueError, match=msg):\n sparse.take(np.array([1, 0, -5]), allow_fill=True)\n\n msg = "out of bounds value in 'indices'"\n with pytest.raises(IndexError, match=msg):\n sparse.take(np.array([1, -6]))\n with pytest.raises(IndexError, match=msg):\n sparse.take(np.array([1, 5]))\n with pytest.raises(IndexError, match=msg):\n sparse.take(np.array([1, 5]), allow_fill=True)\n\n def test_take_filling_fill_value(self):\n # same tests as GH#12631\n sparse = SparseArray([np.nan, 0, 1, 0, 4], fill_value=0)\n result = sparse.take(np.array([1, 0, -1]))\n expected = SparseArray([0, np.nan, 4], fill_value=0)\n tm.assert_sp_array_equal(result, expected)\n\n # fill_value\n result = sparse.take(np.array([1, 0, -1]), allow_fill=True)\n # TODO: actionable?\n # XXX: behavior change.\n # the old way of filling self.fill_value doesn't follow EA rules.\n # It's supposed to be self.dtype.na_value (nan in this case)\n expected = SparseArray([0, np.nan, np.nan], fill_value=0)\n tm.assert_sp_array_equal(result, expected)\n\n # allow_fill=False\n result = sparse.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True)\n expected = SparseArray([0, np.nan, 4], fill_value=0)\n tm.assert_sp_array_equal(result, expected)\n\n msg = "Invalid value in 'indices'."\n with pytest.raises(ValueError, match=msg):\n sparse.take(np.array([1, 0, -2]), allow_fill=True)\n with pytest.raises(ValueError, match=msg):\n sparse.take(np.array([1, 0, -5]), allow_fill=True)\n\n msg = "out of bounds value in 'indices'"\n with pytest.raises(IndexError, match=msg):\n sparse.take(np.array([1, -6]))\n with pytest.raises(IndexError, match=msg):\n sparse.take(np.array([1, 5]))\n with pytest.raises(IndexError, match=msg):\n sparse.take(np.array([1, 5]), fill_value=True)\n\n @pytest.mark.parametrize("kind", ["block", "integer"])\n def test_take_filling_all_nan(self, kind):\n sparse = SparseArray([np.nan, np.nan, np.nan, np.nan, np.nan], kind=kind)\n result = sparse.take(np.array([1, 0, -1]))\n expected = SparseArray([np.nan, np.nan, np.nan], kind=kind)\n tm.assert_sp_array_equal(result, expected)\n\n result = sparse.take(np.array([1, 0, -1]), fill_value=True)\n expected = SparseArray([np.nan, np.nan, np.nan], kind=kind)\n tm.assert_sp_array_equal(result, expected)\n\n msg = "out of bounds value in 'indices'"\n with pytest.raises(IndexError, match=msg):\n sparse.take(np.array([1, -6]))\n with pytest.raises(IndexError, match=msg):\n sparse.take(np.array([1, 5]))\n with pytest.raises(IndexError, match=msg):\n sparse.take(np.array([1, 5]), fill_value=True)\n\n\nclass TestWhere:\n def test_where_retain_fill_value(self):\n # GH#45691 don't lose fill_value on _where\n arr = SparseArray([np.nan, 1.0], fill_value=0)\n\n mask = np.array([True, False])\n\n res = arr._where(~mask, 1)\n exp = SparseArray([1, 1.0], fill_value=0)\n tm.assert_sp_array_equal(res, exp)\n\n ser = pd.Series(arr)\n res = ser.where(~mask, 1)\n tm.assert_series_equal(res, pd.Series(exp))\n
.venv\Lib\site-packages\pandas\tests\arrays\sparse\test_indexing.py
test_indexing.py
Python
10,425
0.95
0.099338
0.067511
react-lib
497
2023-11-03T16:04:52.843339
Apache-2.0
true
157469a7b953d68e37e5358e5446965e
import operator\n\nimport numpy as np\nimport pytest\n\nimport pandas._libs.sparse as splib\nimport pandas.util._test_decorators as td\n\nfrom pandas import Series\nimport pandas._testing as tm\nfrom pandas.core.arrays.sparse import (\n BlockIndex,\n IntIndex,\n make_sparse_index,\n)\n\n\n@pytest.fixture\ndef test_length():\n return 20\n\n\n@pytest.fixture(\n params=[\n [\n [0, 7, 15],\n [3, 5, 5],\n [2, 9, 14],\n [2, 3, 5],\n [2, 9, 15],\n [1, 3, 4],\n ],\n [\n [0, 5],\n [4, 4],\n [1],\n [4],\n [1],\n [3],\n ],\n [\n [0],\n [10],\n [0, 5],\n [3, 7],\n [0, 5],\n [3, 5],\n ],\n [\n [10],\n [5],\n [0, 12],\n [5, 3],\n [12],\n [3],\n ],\n [\n [0, 10],\n [4, 6],\n [5, 17],\n [4, 2],\n [],\n [],\n ],\n [\n [0],\n [5],\n [],\n [],\n [],\n [],\n ],\n ],\n ids=[\n "plain_case",\n "delete_blocks",\n "split_blocks",\n "skip_block",\n "no_intersect",\n "one_empty",\n ],\n)\ndef cases(request):\n return request.param\n\n\nclass TestSparseIndexUnion:\n @pytest.mark.parametrize(\n "xloc, xlen, yloc, ylen, eloc, elen",\n [\n [[0], [5], [5], [4], [0], [9]],\n [[0, 10], [5, 5], [2, 17], [5, 2], [0, 10, 17], [7, 5, 2]],\n [[1], [5], [3], [5], [1], [7]],\n [[2, 10], [4, 4], [4], [8], [2], [12]],\n [[0, 5], [3, 5], [0], [7], [0], [10]],\n [[2, 10], [4, 4], [4, 13], [8, 4], [2], [15]],\n [[2], [15], [4, 9, 14], [3, 2, 2], [2], [15]],\n [[0, 10], [3, 3], [5, 15], [2, 2], [0, 5, 10, 15], [3, 2, 3, 2]],\n ],\n )\n def test_index_make_union(self, xloc, xlen, yloc, ylen, eloc, elen, test_length):\n # Case 1\n # x: ----\n # y: ----\n # r: --------\n # Case 2\n # x: ----- -----\n # y: ----- --\n # Case 3\n # x: ------\n # y: -------\n # r: ----------\n # Case 4\n # x: ------ -----\n # y: -------\n # r: -------------\n # Case 5\n # x: --- -----\n # y: -------\n # r: -------------\n # Case 6\n # x: ------ -----\n # y: ------- ---\n # r: -------------\n # Case 7\n # x: ----------------------\n # y: ---- ---- ---\n # r: ----------------------\n # Case 8\n # x: ---- ---\n # y: --- ---\n xindex = BlockIndex(test_length, xloc, xlen)\n yindex = BlockIndex(test_length, yloc, ylen)\n bresult = xindex.make_union(yindex)\n assert isinstance(bresult, BlockIndex)\n tm.assert_numpy_array_equal(bresult.blocs, np.array(eloc, dtype=np.int32))\n tm.assert_numpy_array_equal(bresult.blengths, np.array(elen, dtype=np.int32))\n\n ixindex = xindex.to_int_index()\n iyindex = yindex.to_int_index()\n iresult = ixindex.make_union(iyindex)\n assert isinstance(iresult, IntIndex)\n tm.assert_numpy_array_equal(iresult.indices, bresult.to_int_index().indices)\n\n def test_int_index_make_union(self):\n a = IntIndex(5, np.array([0, 3, 4], dtype=np.int32))\n b = IntIndex(5, np.array([0, 2], dtype=np.int32))\n res = a.make_union(b)\n exp = IntIndex(5, np.array([0, 2, 3, 4], np.int32))\n assert res.equals(exp)\n\n a = IntIndex(5, np.array([], dtype=np.int32))\n b = IntIndex(5, np.array([0, 2], dtype=np.int32))\n res = a.make_union(b)\n exp = IntIndex(5, np.array([0, 2], np.int32))\n assert res.equals(exp)\n\n a = IntIndex(5, np.array([], dtype=np.int32))\n b = IntIndex(5, np.array([], dtype=np.int32))\n res = a.make_union(b)\n exp = IntIndex(5, np.array([], np.int32))\n assert res.equals(exp)\n\n a = IntIndex(5, np.array([0, 1, 2, 3, 4], dtype=np.int32))\n b = IntIndex(5, np.array([0, 1, 2, 3, 4], dtype=np.int32))\n res = a.make_union(b)\n exp = IntIndex(5, np.array([0, 1, 2, 3, 4], np.int32))\n assert res.equals(exp)\n\n a = IntIndex(5, np.array([0, 1], dtype=np.int32))\n b = IntIndex(4, np.array([0, 1], dtype=np.int32))\n\n msg = "Indices must reference same underlying length"\n with pytest.raises(ValueError, match=msg):\n a.make_union(b)\n\n\nclass TestSparseIndexIntersect:\n @td.skip_if_windows\n def test_intersect(self, cases, test_length):\n xloc, xlen, yloc, ylen, eloc, elen = cases\n xindex = BlockIndex(test_length, xloc, xlen)\n yindex = BlockIndex(test_length, yloc, ylen)\n expected = BlockIndex(test_length, eloc, elen)\n longer_index = BlockIndex(test_length + 1, yloc, ylen)\n\n result = xindex.intersect(yindex)\n assert result.equals(expected)\n result = xindex.to_int_index().intersect(yindex.to_int_index())\n assert result.equals(expected.to_int_index())\n\n msg = "Indices must reference same underlying length"\n with pytest.raises(Exception, match=msg):\n xindex.intersect(longer_index)\n with pytest.raises(Exception, match=msg):\n xindex.to_int_index().intersect(longer_index.to_int_index())\n\n def test_intersect_empty(self):\n xindex = IntIndex(4, np.array([], dtype=np.int32))\n yindex = IntIndex(4, np.array([2, 3], dtype=np.int32))\n assert xindex.intersect(yindex).equals(xindex)\n assert yindex.intersect(xindex).equals(xindex)\n\n xindex = xindex.to_block_index()\n yindex = yindex.to_block_index()\n assert xindex.intersect(yindex).equals(xindex)\n assert yindex.intersect(xindex).equals(xindex)\n\n @pytest.mark.parametrize(\n "case",\n [\n # Argument 2 to "IntIndex" has incompatible type "ndarray[Any,\n # dtype[signedinteger[_32Bit]]]"; expected "Sequence[int]"\n IntIndex(5, np.array([1, 2], dtype=np.int32)), # type: ignore[arg-type]\n IntIndex(5, np.array([0, 2, 4], dtype=np.int32)), # type: ignore[arg-type]\n IntIndex(0, np.array([], dtype=np.int32)), # type: ignore[arg-type]\n IntIndex(5, np.array([], dtype=np.int32)), # type: ignore[arg-type]\n ],\n )\n def test_intersect_identical(self, case):\n assert case.intersect(case).equals(case)\n case = case.to_block_index()\n assert case.intersect(case).equals(case)\n\n\nclass TestSparseIndexCommon:\n def test_int_internal(self):\n idx = make_sparse_index(4, np.array([2, 3], dtype=np.int32), kind="integer")\n assert isinstance(idx, IntIndex)\n assert idx.npoints == 2\n tm.assert_numpy_array_equal(idx.indices, np.array([2, 3], dtype=np.int32))\n\n idx = make_sparse_index(4, np.array([], dtype=np.int32), kind="integer")\n assert isinstance(idx, IntIndex)\n assert idx.npoints == 0\n tm.assert_numpy_array_equal(idx.indices, np.array([], dtype=np.int32))\n\n idx = make_sparse_index(\n 4, np.array([0, 1, 2, 3], dtype=np.int32), kind="integer"\n )\n assert isinstance(idx, IntIndex)\n assert idx.npoints == 4\n tm.assert_numpy_array_equal(idx.indices, np.array([0, 1, 2, 3], dtype=np.int32))\n\n def test_block_internal(self):\n idx = make_sparse_index(4, np.array([2, 3], dtype=np.int32), kind="block")\n assert isinstance(idx, BlockIndex)\n assert idx.npoints == 2\n tm.assert_numpy_array_equal(idx.blocs, np.array([2], dtype=np.int32))\n tm.assert_numpy_array_equal(idx.blengths, np.array([2], dtype=np.int32))\n\n idx = make_sparse_index(4, np.array([], dtype=np.int32), kind="block")\n assert isinstance(idx, BlockIndex)\n assert idx.npoints == 0\n tm.assert_numpy_array_equal(idx.blocs, np.array([], dtype=np.int32))\n tm.assert_numpy_array_equal(idx.blengths, np.array([], dtype=np.int32))\n\n idx = make_sparse_index(4, np.array([0, 1, 2, 3], dtype=np.int32), kind="block")\n assert isinstance(idx, BlockIndex)\n assert idx.npoints == 4\n tm.assert_numpy_array_equal(idx.blocs, np.array([0], dtype=np.int32))\n tm.assert_numpy_array_equal(idx.blengths, np.array([4], dtype=np.int32))\n\n idx = make_sparse_index(4, np.array([0, 2, 3], dtype=np.int32), kind="block")\n assert isinstance(idx, BlockIndex)\n assert idx.npoints == 3\n tm.assert_numpy_array_equal(idx.blocs, np.array([0, 2], dtype=np.int32))\n tm.assert_numpy_array_equal(idx.blengths, np.array([1, 2], dtype=np.int32))\n\n @pytest.mark.parametrize("kind", ["integer", "block"])\n def test_lookup(self, kind):\n idx = make_sparse_index(4, np.array([2, 3], dtype=np.int32), kind=kind)\n assert idx.lookup(-1) == -1\n assert idx.lookup(0) == -1\n assert idx.lookup(1) == -1\n assert idx.lookup(2) == 0\n assert idx.lookup(3) == 1\n assert idx.lookup(4) == -1\n\n idx = make_sparse_index(4, np.array([], dtype=np.int32), kind=kind)\n\n for i in range(-1, 5):\n assert idx.lookup(i) == -1\n\n idx = make_sparse_index(4, np.array([0, 1, 2, 3], dtype=np.int32), kind=kind)\n assert idx.lookup(-1) == -1\n assert idx.lookup(0) == 0\n assert idx.lookup(1) == 1\n assert idx.lookup(2) == 2\n assert idx.lookup(3) == 3\n assert idx.lookup(4) == -1\n\n idx = make_sparse_index(4, np.array([0, 2, 3], dtype=np.int32), kind=kind)\n assert idx.lookup(-1) == -1\n assert idx.lookup(0) == 0\n assert idx.lookup(1) == -1\n assert idx.lookup(2) == 1\n assert idx.lookup(3) == 2\n assert idx.lookup(4) == -1\n\n @pytest.mark.parametrize("kind", ["integer", "block"])\n def test_lookup_array(self, kind):\n idx = make_sparse_index(4, np.array([2, 3], dtype=np.int32), kind=kind)\n\n res = idx.lookup_array(np.array([-1, 0, 2], dtype=np.int32))\n exp = np.array([-1, -1, 0], dtype=np.int32)\n tm.assert_numpy_array_equal(res, exp)\n\n res = idx.lookup_array(np.array([4, 2, 1, 3], dtype=np.int32))\n exp = np.array([-1, 0, -1, 1], dtype=np.int32)\n tm.assert_numpy_array_equal(res, exp)\n\n idx = make_sparse_index(4, np.array([], dtype=np.int32), kind=kind)\n res = idx.lookup_array(np.array([-1, 0, 2, 4], dtype=np.int32))\n exp = np.array([-1, -1, -1, -1], dtype=np.int32)\n tm.assert_numpy_array_equal(res, exp)\n\n idx = make_sparse_index(4, np.array([0, 1, 2, 3], dtype=np.int32), kind=kind)\n res = idx.lookup_array(np.array([-1, 0, 2], dtype=np.int32))\n exp = np.array([-1, 0, 2], dtype=np.int32)\n tm.assert_numpy_array_equal(res, exp)\n\n res = idx.lookup_array(np.array([4, 2, 1, 3], dtype=np.int32))\n exp = np.array([-1, 2, 1, 3], dtype=np.int32)\n tm.assert_numpy_array_equal(res, exp)\n\n idx = make_sparse_index(4, np.array([0, 2, 3], dtype=np.int32), kind=kind)\n res = idx.lookup_array(np.array([2, 1, 3, 0], dtype=np.int32))\n exp = np.array([1, -1, 2, 0], dtype=np.int32)\n tm.assert_numpy_array_equal(res, exp)\n\n res = idx.lookup_array(np.array([1, 4, 2, 5], dtype=np.int32))\n exp = np.array([-1, -1, 1, -1], dtype=np.int32)\n tm.assert_numpy_array_equal(res, exp)\n\n @pytest.mark.parametrize(\n "idx, expected",\n [\n [0, -1],\n [5, 0],\n [7, 2],\n [8, -1],\n [9, -1],\n [10, -1],\n [11, -1],\n [12, 3],\n [17, 8],\n [18, -1],\n ],\n )\n def test_lookup_basics(self, idx, expected):\n bindex = BlockIndex(20, [5, 12], [3, 6])\n assert bindex.lookup(idx) == expected\n\n iindex = bindex.to_int_index()\n assert iindex.lookup(idx) == expected\n\n\nclass TestBlockIndex:\n def test_block_internal(self):\n idx = make_sparse_index(4, np.array([2, 3], dtype=np.int32), kind="block")\n assert isinstance(idx, BlockIndex)\n assert idx.npoints == 2\n tm.assert_numpy_array_equal(idx.blocs, np.array([2], dtype=np.int32))\n tm.assert_numpy_array_equal(idx.blengths, np.array([2], dtype=np.int32))\n\n idx = make_sparse_index(4, np.array([], dtype=np.int32), kind="block")\n assert isinstance(idx, BlockIndex)\n assert idx.npoints == 0\n tm.assert_numpy_array_equal(idx.blocs, np.array([], dtype=np.int32))\n tm.assert_numpy_array_equal(idx.blengths, np.array([], dtype=np.int32))\n\n idx = make_sparse_index(4, np.array([0, 1, 2, 3], dtype=np.int32), kind="block")\n assert isinstance(idx, BlockIndex)\n assert idx.npoints == 4\n tm.assert_numpy_array_equal(idx.blocs, np.array([0], dtype=np.int32))\n tm.assert_numpy_array_equal(idx.blengths, np.array([4], dtype=np.int32))\n\n idx = make_sparse_index(4, np.array([0, 2, 3], dtype=np.int32), kind="block")\n assert isinstance(idx, BlockIndex)\n assert idx.npoints == 3\n tm.assert_numpy_array_equal(idx.blocs, np.array([0, 2], dtype=np.int32))\n tm.assert_numpy_array_equal(idx.blengths, np.array([1, 2], dtype=np.int32))\n\n @pytest.mark.parametrize("i", [5, 10, 100, 101])\n def test_make_block_boundary(self, i):\n idx = make_sparse_index(i, np.arange(0, i, 2, dtype=np.int32), kind="block")\n\n exp = np.arange(0, i, 2, dtype=np.int32)\n tm.assert_numpy_array_equal(idx.blocs, exp)\n tm.assert_numpy_array_equal(idx.blengths, np.ones(len(exp), dtype=np.int32))\n\n def test_equals(self):\n index = BlockIndex(10, [0, 4], [2, 5])\n\n assert index.equals(index)\n assert not index.equals(BlockIndex(10, [0, 4], [2, 6]))\n\n def test_check_integrity(self):\n locs = []\n lengths = []\n\n # 0-length OK\n BlockIndex(0, locs, lengths)\n\n # also OK even though empty\n BlockIndex(1, locs, lengths)\n\n msg = "Block 0 extends beyond end"\n with pytest.raises(ValueError, match=msg):\n BlockIndex(10, [5], [10])\n\n msg = "Block 0 overlaps"\n with pytest.raises(ValueError, match=msg):\n BlockIndex(10, [2, 5], [5, 3])\n\n def test_to_int_index(self):\n locs = [0, 10]\n lengths = [4, 6]\n exp_inds = [0, 1, 2, 3, 10, 11, 12, 13, 14, 15]\n\n block = BlockIndex(20, locs, lengths)\n dense = block.to_int_index()\n\n tm.assert_numpy_array_equal(dense.indices, np.array(exp_inds, dtype=np.int32))\n\n def test_to_block_index(self):\n index = BlockIndex(10, [0, 5], [4, 5])\n assert index.to_block_index() is index\n\n\nclass TestIntIndex:\n def test_check_integrity(self):\n # Too many indices than specified in self.length\n msg = "Too many indices"\n\n with pytest.raises(ValueError, match=msg):\n IntIndex(length=1, indices=[1, 2, 3])\n\n # No index can be negative.\n msg = "No index can be less than zero"\n\n with pytest.raises(ValueError, match=msg):\n IntIndex(length=5, indices=[1, -2, 3])\n\n # No index can be negative.\n msg = "No index can be less than zero"\n\n with pytest.raises(ValueError, match=msg):\n IntIndex(length=5, indices=[1, -2, 3])\n\n # All indices must be less than the length.\n msg = "All indices must be less than the length"\n\n with pytest.raises(ValueError, match=msg):\n IntIndex(length=5, indices=[1, 2, 5])\n\n with pytest.raises(ValueError, match=msg):\n IntIndex(length=5, indices=[1, 2, 6])\n\n # Indices must be strictly ascending.\n msg = "Indices must be strictly increasing"\n\n with pytest.raises(ValueError, match=msg):\n IntIndex(length=5, indices=[1, 3, 2])\n\n with pytest.raises(ValueError, match=msg):\n IntIndex(length=5, indices=[1, 3, 3])\n\n def test_int_internal(self):\n idx = make_sparse_index(4, np.array([2, 3], dtype=np.int32), kind="integer")\n assert isinstance(idx, IntIndex)\n assert idx.npoints == 2\n tm.assert_numpy_array_equal(idx.indices, np.array([2, 3], dtype=np.int32))\n\n idx = make_sparse_index(4, np.array([], dtype=np.int32), kind="integer")\n assert isinstance(idx, IntIndex)\n assert idx.npoints == 0\n tm.assert_numpy_array_equal(idx.indices, np.array([], dtype=np.int32))\n\n idx = make_sparse_index(\n 4, np.array([0, 1, 2, 3], dtype=np.int32), kind="integer"\n )\n assert isinstance(idx, IntIndex)\n assert idx.npoints == 4\n tm.assert_numpy_array_equal(idx.indices, np.array([0, 1, 2, 3], dtype=np.int32))\n\n def test_equals(self):\n index = IntIndex(10, [0, 1, 2, 3, 4])\n assert index.equals(index)\n assert not index.equals(IntIndex(10, [0, 1, 2, 3]))\n\n def test_to_block_index(self, cases, test_length):\n xloc, xlen, yloc, ylen, _, _ = cases\n xindex = BlockIndex(test_length, xloc, xlen)\n yindex = BlockIndex(test_length, yloc, ylen)\n\n # see if survive the round trip\n xbindex = xindex.to_int_index().to_block_index()\n ybindex = yindex.to_int_index().to_block_index()\n assert isinstance(xbindex, BlockIndex)\n assert xbindex.equals(xindex)\n assert ybindex.equals(yindex)\n\n def test_to_int_index(self):\n index = IntIndex(10, [2, 3, 4, 5, 6])\n assert index.to_int_index() is index\n\n\nclass TestSparseOperators:\n @pytest.mark.parametrize("opname", ["add", "sub", "mul", "truediv", "floordiv"])\n def test_op(self, opname, cases, test_length):\n xloc, xlen, yloc, ylen, _, _ = cases\n sparse_op = getattr(splib, f"sparse_{opname}_float64")\n python_op = getattr(operator, opname)\n\n xindex = BlockIndex(test_length, xloc, xlen)\n yindex = BlockIndex(test_length, yloc, ylen)\n\n xdindex = xindex.to_int_index()\n ydindex = yindex.to_int_index()\n\n x = np.arange(xindex.npoints) * 10.0 + 1\n y = np.arange(yindex.npoints) * 100.0 + 1\n\n xfill = 0\n yfill = 2\n\n result_block_vals, rb_index, bfill = sparse_op(\n x, xindex, xfill, y, yindex, yfill\n )\n result_int_vals, ri_index, ifill = sparse_op(\n x, xdindex, xfill, y, ydindex, yfill\n )\n\n assert rb_index.to_int_index().equals(ri_index)\n tm.assert_numpy_array_equal(result_block_vals, result_int_vals)\n assert bfill == ifill\n\n # check versus Series...\n xseries = Series(x, xdindex.indices)\n xseries = xseries.reindex(np.arange(test_length)).fillna(xfill)\n\n yseries = Series(y, ydindex.indices)\n yseries = yseries.reindex(np.arange(test_length)).fillna(yfill)\n\n series_result = python_op(xseries, yseries)\n series_result = series_result.reindex(ri_index.indices)\n\n tm.assert_numpy_array_equal(result_block_vals, series_result.values)\n tm.assert_numpy_array_equal(result_int_vals, series_result.values)\n
.venv\Lib\site-packages\pandas\tests\arrays\sparse\test_libsparse.py
test_libsparse.py
Python
19,293
0.95
0.058076
0.09011
react-lib
410
2023-07-14T02:23:30.516104
GPL-3.0
true
5cb3c89886ff25ab689cd195859128ab
import numpy as np\nimport pytest\n\nfrom pandas import (\n NaT,\n SparseDtype,\n Timestamp,\n isna,\n)\nfrom pandas.core.arrays.sparse import SparseArray\n\n\nclass TestReductions:\n @pytest.mark.parametrize(\n "data,pos,neg",\n [\n ([True, True, True], True, False),\n ([1, 2, 1], 1, 0),\n ([1.0, 2.0, 1.0], 1.0, 0.0),\n ],\n )\n def test_all(self, data, pos, neg):\n # GH#17570\n out = SparseArray(data).all()\n assert out\n\n out = SparseArray(data, fill_value=pos).all()\n assert out\n\n data[1] = neg\n out = SparseArray(data).all()\n assert not out\n\n out = SparseArray(data, fill_value=pos).all()\n assert not out\n\n @pytest.mark.parametrize(\n "data,pos,neg",\n [\n ([True, True, True], True, False),\n ([1, 2, 1], 1, 0),\n ([1.0, 2.0, 1.0], 1.0, 0.0),\n ],\n )\n def test_numpy_all(self, data, pos, neg):\n # GH#17570\n out = np.all(SparseArray(data))\n assert out\n\n out = np.all(SparseArray(data, fill_value=pos))\n assert out\n\n data[1] = neg\n out = np.all(SparseArray(data))\n assert not out\n\n out = np.all(SparseArray(data, fill_value=pos))\n assert not out\n\n # raises with a different message on py2.\n msg = "the 'out' parameter is not supported"\n with pytest.raises(ValueError, match=msg):\n np.all(SparseArray(data), out=np.array([]))\n\n @pytest.mark.parametrize(\n "data,pos,neg",\n [\n ([False, True, False], True, False),\n ([0, 2, 0], 2, 0),\n ([0.0, 2.0, 0.0], 2.0, 0.0),\n ],\n )\n def test_any(self, data, pos, neg):\n # GH#17570\n out = SparseArray(data).any()\n assert out\n\n out = SparseArray(data, fill_value=pos).any()\n assert out\n\n data[1] = neg\n out = SparseArray(data).any()\n assert not out\n\n out = SparseArray(data, fill_value=pos).any()\n assert not out\n\n @pytest.mark.parametrize(\n "data,pos,neg",\n [\n ([False, True, False], True, False),\n ([0, 2, 0], 2, 0),\n ([0.0, 2.0, 0.0], 2.0, 0.0),\n ],\n )\n def test_numpy_any(self, data, pos, neg):\n # GH#17570\n out = np.any(SparseArray(data))\n assert out\n\n out = np.any(SparseArray(data, fill_value=pos))\n assert out\n\n data[1] = neg\n out = np.any(SparseArray(data))\n assert not out\n\n out = np.any(SparseArray(data, fill_value=pos))\n assert not out\n\n msg = "the 'out' parameter is not supported"\n with pytest.raises(ValueError, match=msg):\n np.any(SparseArray(data), out=out)\n\n def test_sum(self):\n data = np.arange(10).astype(float)\n out = SparseArray(data).sum()\n assert out == 45.0\n\n data[5] = np.nan\n out = SparseArray(data, fill_value=2).sum()\n assert out == 40.0\n\n out = SparseArray(data, fill_value=np.nan).sum()\n assert out == 40.0\n\n @pytest.mark.parametrize(\n "arr",\n [np.array([0, 1, np.nan, 1]), np.array([0, 1, 1])],\n )\n @pytest.mark.parametrize("fill_value", [0, 1, np.nan])\n @pytest.mark.parametrize("min_count, expected", [(3, 2), (4, np.nan)])\n def test_sum_min_count(self, arr, fill_value, min_count, expected):\n # GH#25777\n sparray = SparseArray(arr, fill_value=fill_value)\n result = sparray.sum(min_count=min_count)\n if np.isnan(expected):\n assert np.isnan(result)\n else:\n assert result == expected\n\n def test_bool_sum_min_count(self):\n spar_bool = SparseArray([False, True] * 5, dtype=np.bool_, fill_value=True)\n res = spar_bool.sum(min_count=1)\n assert res == 5\n res = spar_bool.sum(min_count=11)\n assert isna(res)\n\n def test_numpy_sum(self):\n data = np.arange(10).astype(float)\n out = np.sum(SparseArray(data))\n assert out == 45.0\n\n data[5] = np.nan\n out = np.sum(SparseArray(data, fill_value=2))\n assert out == 40.0\n\n out = np.sum(SparseArray(data, fill_value=np.nan))\n assert out == 40.0\n\n msg = "the 'dtype' parameter is not supported"\n with pytest.raises(ValueError, match=msg):\n np.sum(SparseArray(data), dtype=np.int64)\n\n msg = "the 'out' parameter is not supported"\n with pytest.raises(ValueError, match=msg):\n np.sum(SparseArray(data), out=out)\n\n def test_mean(self):\n data = np.arange(10).astype(float)\n out = SparseArray(data).mean()\n assert out == 4.5\n\n data[5] = np.nan\n out = SparseArray(data).mean()\n assert out == 40.0 / 9\n\n def test_numpy_mean(self):\n data = np.arange(10).astype(float)\n out = np.mean(SparseArray(data))\n assert out == 4.5\n\n data[5] = np.nan\n out = np.mean(SparseArray(data))\n assert out == 40.0 / 9\n\n msg = "the 'dtype' parameter is not supported"\n with pytest.raises(ValueError, match=msg):\n np.mean(SparseArray(data), dtype=np.int64)\n\n msg = "the 'out' parameter is not supported"\n with pytest.raises(ValueError, match=msg):\n np.mean(SparseArray(data), out=out)\n\n\nclass TestMinMax:\n @pytest.mark.parametrize(\n "raw_data,max_expected,min_expected",\n [\n (np.arange(5.0), [4], [0]),\n (-np.arange(5.0), [0], [-4]),\n (np.array([0, 1, 2, np.nan, 4]), [4], [0]),\n (np.array([np.nan] * 5), [np.nan], [np.nan]),\n (np.array([]), [np.nan], [np.nan]),\n ],\n )\n def test_nan_fill_value(self, raw_data, max_expected, min_expected):\n arr = SparseArray(raw_data)\n max_result = arr.max()\n min_result = arr.min()\n assert max_result in max_expected\n assert min_result in min_expected\n\n max_result = arr.max(skipna=False)\n min_result = arr.min(skipna=False)\n if np.isnan(raw_data).any():\n assert np.isnan(max_result)\n assert np.isnan(min_result)\n else:\n assert max_result in max_expected\n assert min_result in min_expected\n\n @pytest.mark.parametrize(\n "fill_value,max_expected,min_expected",\n [\n (100, 100, 0),\n (-100, 1, -100),\n ],\n )\n def test_fill_value(self, fill_value, max_expected, min_expected):\n arr = SparseArray(\n np.array([fill_value, 0, 1]), dtype=SparseDtype("int", fill_value)\n )\n max_result = arr.max()\n assert max_result == max_expected\n\n min_result = arr.min()\n assert min_result == min_expected\n\n def test_only_fill_value(self):\n fv = 100\n arr = SparseArray(np.array([fv, fv, fv]), dtype=SparseDtype("int", fv))\n assert len(arr._valid_sp_values) == 0\n\n assert arr.max() == fv\n assert arr.min() == fv\n assert arr.max(skipna=False) == fv\n assert arr.min(skipna=False) == fv\n\n @pytest.mark.parametrize("func", ["min", "max"])\n @pytest.mark.parametrize("data", [np.array([]), np.array([np.nan, np.nan])])\n @pytest.mark.parametrize(\n "dtype,expected",\n [\n (SparseDtype(np.float64, np.nan), np.nan),\n (SparseDtype(np.float64, 5.0), np.nan),\n (SparseDtype("datetime64[ns]", NaT), NaT),\n (SparseDtype("datetime64[ns]", Timestamp("2018-05-05")), NaT),\n ],\n )\n def test_na_value_if_no_valid_values(self, func, data, dtype, expected):\n arr = SparseArray(data, dtype=dtype)\n result = getattr(arr, func)()\n if expected is NaT:\n # TODO: pin down whether we wrap datetime64("NaT")\n assert result is NaT or np.isnat(result)\n else:\n assert np.isnan(result)\n\n\nclass TestArgmaxArgmin:\n @pytest.mark.parametrize(\n "arr,argmax_expected,argmin_expected",\n [\n (SparseArray([1, 2, 0, 1, 2]), 1, 2),\n (SparseArray([-1, -2, 0, -1, -2]), 2, 1),\n (SparseArray([np.nan, 1, 0, 0, np.nan, -1]), 1, 5),\n (SparseArray([np.nan, 1, 0, 0, np.nan, 2]), 5, 2),\n (SparseArray([np.nan, 1, 0, 0, np.nan, 2], fill_value=-1), 5, 2),\n (SparseArray([np.nan, 1, 0, 0, np.nan, 2], fill_value=0), 5, 2),\n (SparseArray([np.nan, 1, 0, 0, np.nan, 2], fill_value=1), 5, 2),\n (SparseArray([np.nan, 1, 0, 0, np.nan, 2], fill_value=2), 5, 2),\n (SparseArray([np.nan, 1, 0, 0, np.nan, 2], fill_value=3), 5, 2),\n (SparseArray([0] * 10 + [-1], fill_value=0), 0, 10),\n (SparseArray([0] * 10 + [-1], fill_value=-1), 0, 10),\n (SparseArray([0] * 10 + [-1], fill_value=1), 0, 10),\n (SparseArray([-1] + [0] * 10, fill_value=0), 1, 0),\n (SparseArray([1] + [0] * 10, fill_value=0), 0, 1),\n (SparseArray([-1] + [0] * 10, fill_value=-1), 1, 0),\n (SparseArray([1] + [0] * 10, fill_value=1), 0, 1),\n ],\n )\n def test_argmax_argmin(self, arr, argmax_expected, argmin_expected):\n argmax_result = arr.argmax()\n argmin_result = arr.argmin()\n assert argmax_result == argmax_expected\n assert argmin_result == argmin_expected\n\n @pytest.mark.parametrize(\n "arr,method",\n [(SparseArray([]), "argmax"), (SparseArray([]), "argmin")],\n )\n def test_empty_array(self, arr, method):\n msg = f"attempt to get {method} of an empty sequence"\n with pytest.raises(ValueError, match=msg):\n arr.argmax() if method == "argmax" else arr.argmin()\n
.venv\Lib\site-packages\pandas\tests\arrays\sparse\test_reductions.py
test_reductions.py
Python
9,721
0.95
0.075163
0.027027
awesome-app
219
2023-11-09T03:37:16.265319
MIT
true
cd7aa8ec7a9ed1e1d44574aca78d8e27
import operator\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.core.arrays import SparseArray\n\n\n@pytest.mark.filterwarnings("ignore:invalid value encountered in cast:RuntimeWarning")\n@pytest.mark.parametrize("fill_value", [0, np.nan])\n@pytest.mark.parametrize("op", [operator.pos, operator.neg])\ndef test_unary_op(op, fill_value):\n arr = np.array([0, 1, np.nan, 2])\n sparray = SparseArray(arr, fill_value=fill_value)\n result = op(sparray)\n expected = SparseArray(op(arr), fill_value=op(fill_value))\n tm.assert_sp_array_equal(result, expected)\n\n\n@pytest.mark.parametrize("fill_value", [True, False])\ndef test_invert(fill_value):\n arr = np.array([True, False, False, True])\n sparray = SparseArray(arr, fill_value=fill_value)\n result = ~sparray\n expected = SparseArray(~arr, fill_value=not fill_value)\n tm.assert_sp_array_equal(result, expected)\n\n result = ~pd.Series(sparray)\n expected = pd.Series(expected)\n tm.assert_series_equal(result, expected)\n\n result = ~pd.DataFrame({"A": sparray})\n expected = pd.DataFrame({"A": expected})\n tm.assert_frame_equal(result, expected)\n\n\nclass TestUnaryMethods:\n @pytest.mark.filterwarnings(\n "ignore:invalid value encountered in cast:RuntimeWarning"\n )\n def test_neg_operator(self):\n arr = SparseArray([-1, -2, np.nan, 3], fill_value=np.nan, dtype=np.int8)\n res = -arr\n exp = SparseArray([1, 2, np.nan, -3], fill_value=np.nan, dtype=np.int8)\n tm.assert_sp_array_equal(exp, res)\n\n arr = SparseArray([-1, -2, 1, 3], fill_value=-1, dtype=np.int8)\n res = -arr\n exp = SparseArray([1, 2, -1, -3], fill_value=1, dtype=np.int8)\n tm.assert_sp_array_equal(exp, res)\n\n @pytest.mark.filterwarnings(\n "ignore:invalid value encountered in cast:RuntimeWarning"\n )\n def test_abs_operator(self):\n arr = SparseArray([-1, -2, np.nan, 3], fill_value=np.nan, dtype=np.int8)\n res = abs(arr)\n exp = SparseArray([1, 2, np.nan, 3], fill_value=np.nan, dtype=np.int8)\n tm.assert_sp_array_equal(exp, res)\n\n arr = SparseArray([-1, -2, 1, 3], fill_value=-1, dtype=np.int8)\n res = abs(arr)\n exp = SparseArray([1, 2, 1, 3], fill_value=1, dtype=np.int8)\n tm.assert_sp_array_equal(exp, res)\n\n def test_invert_operator(self):\n arr = SparseArray([False, True, False, True], fill_value=False, dtype=np.bool_)\n exp = SparseArray(\n np.invert([False, True, False, True]), fill_value=True, dtype=np.bool_\n )\n res = ~arr\n tm.assert_sp_array_equal(exp, res)\n\n arr = SparseArray([0, 1, 0, 2, 3, 0], fill_value=0, dtype=np.int32)\n res = ~arr\n exp = SparseArray([-1, -2, -1, -3, -4, -1], fill_value=-1, dtype=np.int32)\n tm.assert_sp_array_equal(exp, res)\n
.venv\Lib\site-packages\pandas\tests\arrays\sparse\test_unary.py
test_unary.py
Python
2,864
0.85
0.075949
0
python-kit
306
2025-04-29T09:10:50.452135
Apache-2.0
true
3d2ca98d58bedeb651f6cc33d28cd719
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\sparse\__pycache__\test_accessor.cpython-313.pyc
test_accessor.cpython-313.pyc
Other
16,305
0.95
0
0
react-lib
383
2023-11-03T01:07:19.228291
BSD-3-Clause
true
067a405c66560994e51b3d9509e5ad24
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\sparse\__pycache__\test_arithmetics.cpython-313.pyc
test_arithmetics.cpython-313.pyc
Other
28,658
0.95
0
0.027778
python-kit
505
2024-03-28T04:06:27.934985
MIT
true
790e0f081ace0a307457ad69a3d799eb
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\sparse\__pycache__\test_array.cpython-313.pyc
test_array.cpython-313.pyc
Other
30,841
0.8
0
0.006494
python-kit
314
2023-12-05T08:44:23.186074
MIT
true
61abce394d99e5279c98331af2eac4ec
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\sparse\__pycache__\test_astype.cpython-313.pyc
test_astype.cpython-313.pyc
Other
7,059
0.8
0
0
node-utils
568
2024-10-24T14:03:54.897917
Apache-2.0
true
ea7c0385d09d23e610636703fbf0ec30
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\sparse\__pycache__\test_combine_concat.cpython-313.pyc
test_combine_concat.cpython-313.pyc
Other
3,979
0.8
0
0
awesome-app
359
2024-06-30T06:03:11.089559
GPL-3.0
true
4678e7bd4026c8de0ba275d6dc9c7db0
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\sparse\__pycache__\test_constructors.cpython-313.pyc
test_constructors.cpython-313.pyc
Other
20,002
0.95
0
0
node-utils
291
2025-03-14T15:29:38.736309
GPL-3.0
true
b56790908528958999cc97a3f7301fe1
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\sparse\__pycache__\test_dtype.cpython-313.pyc
test_dtype.cpython-313.pyc
Other
9,727
0.8
0.013158
0
vue-tools
748
2024-01-31T23:46:44.568841
BSD-3-Clause
true
a84fae5a2647c053abdd3f925b0a24c6
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\sparse\__pycache__\test_indexing.cpython-313.pyc
test_indexing.cpython-313.pyc
Other
20,854
0.8
0.004464
0
python-kit
16
2024-12-30T05:42:04.607192
MIT
true
89a7a7ea7094a3b61a5fcef8b8da26df
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\sparse\__pycache__\test_libsparse.cpython-313.pyc
test_libsparse.cpython-313.pyc
Other
32,391
0.8
0
0
react-lib
137
2023-10-18T20:04:15.702888
Apache-2.0
true
61371b9f9be4061801be072f4f96fc38
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\sparse\__pycache__\test_reductions.cpython-313.pyc
test_reductions.cpython-313.pyc
Other
16,639
0.8
0
0.004926
awesome-app
496
2025-01-19T07:27:20.163457
MIT
true
ba2839b058db946bde4085acdc240f0b
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\sparse\__pycache__\test_unary.cpython-313.pyc
test_unary.cpython-313.pyc
Other
5,231
0.8
0
0.021277
awesome-app
516
2024-07-28T19:53:19.643956
GPL-3.0
true
2142483c3bd4d5f11ee1246d58c5b0c8
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\sparse\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
201
0.7
0
0
awesome-app
394
2024-03-17T05:15:03.935098
MIT
true
648f6063bb6a0aa3c46f84540213535d
import numpy as np\nimport pytest\n\nfrom pandas.compat import HAS_PYARROW\n\nfrom pandas.core.dtypes.cast import find_common_type\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.util.version import Version\n\n\n@pytest.mark.parametrize(\n "to_concat_dtypes, result_dtype",\n [\n # same types\n ([("pyarrow", pd.NA), ("pyarrow", pd.NA)], ("pyarrow", pd.NA)),\n ([("pyarrow", np.nan), ("pyarrow", np.nan)], ("pyarrow", np.nan)),\n ([("python", pd.NA), ("python", pd.NA)], ("python", pd.NA)),\n ([("python", np.nan), ("python", np.nan)], ("python", np.nan)),\n # pyarrow preference\n ([("pyarrow", pd.NA), ("python", pd.NA)], ("pyarrow", pd.NA)),\n # NA preference\n ([("python", pd.NA), ("python", np.nan)], ("python", pd.NA)),\n ],\n)\ndef test_concat_series(request, to_concat_dtypes, result_dtype):\n if any(storage == "pyarrow" for storage, _ in to_concat_dtypes) and not HAS_PYARROW:\n pytest.skip("Could not import 'pyarrow'")\n\n ser_list = [\n pd.Series(["a", "b", None], dtype=pd.StringDtype(storage, na_value))\n for storage, na_value in to_concat_dtypes\n ]\n\n result = pd.concat(ser_list, ignore_index=True)\n expected = pd.Series(\n ["a", "b", None, "a", "b", None], dtype=pd.StringDtype(*result_dtype)\n )\n tm.assert_series_equal(result, expected)\n\n # order doesn't matter for result\n result = pd.concat(ser_list[::1], ignore_index=True)\n tm.assert_series_equal(result, expected)\n\n\ndef test_concat_with_object(string_dtype_arguments):\n # _get_common_dtype cannot inspect values, so object dtype with strings still\n # results in object dtype\n result = pd.concat(\n [\n pd.Series(["a", "b", None], dtype=pd.StringDtype(*string_dtype_arguments)),\n pd.Series(["a", "b", None], dtype=object),\n ]\n )\n assert result.dtype == np.dtype("object")\n\n\ndef test_concat_with_numpy(string_dtype_arguments):\n # common type with a numpy string dtype always preserves the pandas string dtype\n dtype = pd.StringDtype(*string_dtype_arguments)\n assert find_common_type([dtype, np.dtype("U")]) == dtype\n assert find_common_type([np.dtype("U"), dtype]) == dtype\n assert find_common_type([dtype, np.dtype("U10")]) == dtype\n assert find_common_type([np.dtype("U10"), dtype]) == dtype\n\n # with any other numpy dtype -> object\n assert find_common_type([dtype, np.dtype("S")]) == np.dtype("object")\n assert find_common_type([dtype, np.dtype("int64")]) == np.dtype("object")\n\n if Version(np.__version__) >= Version("2"):\n assert find_common_type([dtype, np.dtypes.StringDType()]) == dtype\n assert find_common_type([np.dtypes.StringDType(), dtype]) == dtype\n
.venv\Lib\site-packages\pandas\tests\arrays\string_\test_concat.py
test_concat.py
Python
2,744
0.95
0.109589
0.135593
vue-tools
353
2025-01-23T03:29:54.665165
BSD-3-Clause
true
0e0931a9d054fde08611928193c3bdd0
"""\nThis module tests the functionality of StringArray and ArrowStringArray.\nTests for the str accessors are in pandas/tests/strings/test_string_array.py\n"""\nimport operator\n\nimport numpy as np\nimport pytest\n\nfrom pandas._config import using_string_dtype\n\nfrom pandas.compat.pyarrow import (\n pa_version_under12p0,\n pa_version_under19p0,\n)\n\nfrom pandas.core.dtypes.common import is_dtype_equal\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.core.arrays.string_ import StringArrayNumpySemantics\nfrom pandas.core.arrays.string_arrow import (\n ArrowStringArray,\n ArrowStringArrayNumpySemantics,\n)\n\n\n@pytest.fixture\ndef dtype(string_dtype_arguments):\n """Fixture giving StringDtype from parametrized storage and na_value arguments"""\n storage, na_value = string_dtype_arguments\n return pd.StringDtype(storage=storage, na_value=na_value)\n\n\n@pytest.fixture\ndef dtype2(string_dtype_arguments2):\n storage, na_value = string_dtype_arguments2\n return pd.StringDtype(storage=storage, na_value=na_value)\n\n\n@pytest.fixture\ndef cls(dtype):\n """Fixture giving array type from parametrized 'dtype'"""\n return dtype.construct_array_type()\n\n\ndef test_dtype_constructor():\n pytest.importorskip("pyarrow")\n\n with tm.assert_produces_warning(FutureWarning):\n dtype = pd.StringDtype("pyarrow_numpy")\n assert dtype == pd.StringDtype("pyarrow", na_value=np.nan)\n\n\ndef test_dtype_equality():\n pytest.importorskip("pyarrow")\n\n dtype1 = pd.StringDtype("python")\n dtype2 = pd.StringDtype("pyarrow")\n dtype3 = pd.StringDtype("pyarrow", na_value=np.nan)\n\n assert dtype1 == pd.StringDtype("python", na_value=pd.NA)\n assert dtype1 != dtype2\n assert dtype1 != dtype3\n\n assert dtype2 == pd.StringDtype("pyarrow", na_value=pd.NA)\n assert dtype2 != dtype1\n assert dtype2 != dtype3\n\n assert dtype3 == pd.StringDtype("pyarrow", na_value=np.nan)\n assert dtype3 == pd.StringDtype("pyarrow", na_value=float("nan"))\n assert dtype3 != dtype1\n assert dtype3 != dtype2\n\n\ndef test_repr(dtype):\n df = pd.DataFrame({"A": pd.array(["a", pd.NA, "b"], dtype=dtype)})\n if dtype.na_value is np.nan:\n expected = " A\n0 a\n1 NaN\n2 b"\n else:\n expected = " A\n0 a\n1 <NA>\n2 b"\n assert repr(df) == expected\n\n if dtype.na_value is np.nan:\n expected = "0 a\n1 NaN\n2 b\nName: A, dtype: str"\n else:\n expected = "0 a\n1 <NA>\n2 b\nName: A, dtype: string"\n assert repr(df.A) == expected\n\n if dtype.storage == "pyarrow" and dtype.na_value is pd.NA:\n arr_name = "ArrowStringArray"\n expected = f"<{arr_name}>\n['a', <NA>, 'b']\nLength: 3, dtype: string"\n elif dtype.storage == "pyarrow" and dtype.na_value is np.nan:\n arr_name = "ArrowStringArrayNumpySemantics"\n expected = f"<{arr_name}>\n['a', nan, 'b']\nLength: 3, dtype: str"\n elif dtype.storage == "python" and dtype.na_value is np.nan:\n arr_name = "StringArrayNumpySemantics"\n expected = f"<{arr_name}>\n['a', nan, 'b']\nLength: 3, dtype: str"\n else:\n arr_name = "StringArray"\n expected = f"<{arr_name}>\n['a', <NA>, 'b']\nLength: 3, dtype: string"\n assert repr(df.A.array) == expected\n\n\ndef test_none_to_nan(cls, dtype):\n a = cls._from_sequence(["a", None, "b"], dtype=dtype)\n assert a[1] is not None\n assert a[1] is a.dtype.na_value\n\n\ndef test_setitem_validates(cls, dtype):\n arr = cls._from_sequence(["a", "b"], dtype=dtype)\n\n msg = "Invalid value '10' for dtype 'str"\n with pytest.raises(TypeError, match=msg):\n arr[0] = 10\n\n msg = "Invalid value for dtype 'str"\n with pytest.raises(TypeError, match=msg):\n arr[:] = np.array([1, 2])\n\n\ndef test_setitem_with_scalar_string(dtype):\n # is_float_dtype considers some strings, like 'd', to be floats\n # which can cause issues.\n arr = pd.array(["a", "c"], dtype=dtype)\n arr[0] = "d"\n expected = pd.array(["d", "c"], dtype=dtype)\n tm.assert_extension_array_equal(arr, expected)\n\n\ndef test_setitem_with_array_with_missing(dtype):\n # ensure that when setting with an array of values, we don't mutate the\n # array `value` in __setitem__(self, key, value)\n arr = pd.array(["a", "b", "c"], dtype=dtype)\n value = np.array(["A", None])\n value_orig = value.copy()\n arr[[0, 1]] = value\n\n expected = pd.array(["A", pd.NA, "c"], dtype=dtype)\n tm.assert_extension_array_equal(arr, expected)\n tm.assert_numpy_array_equal(value, value_orig)\n\n\ndef test_astype_roundtrip(dtype):\n ser = pd.Series(pd.date_range("2000", periods=12))\n ser[0] = None\n\n casted = ser.astype(dtype)\n assert is_dtype_equal(casted.dtype, dtype)\n\n result = casted.astype("datetime64[ns]")\n tm.assert_series_equal(result, ser)\n\n # GH#38509 same thing for timedelta64\n ser2 = ser - ser.iloc[-1]\n casted2 = ser2.astype(dtype)\n assert is_dtype_equal(casted2.dtype, dtype)\n\n result2 = casted2.astype(ser2.dtype)\n tm.assert_series_equal(result2, ser2)\n\n\ndef test_add(dtype):\n a = pd.Series(["a", "b", "c", None, None], dtype=dtype)\n b = pd.Series(["x", "y", None, "z", None], dtype=dtype)\n\n result = a + b\n expected = pd.Series(["ax", "by", None, None, None], dtype=dtype)\n tm.assert_series_equal(result, expected)\n\n result = a.add(b)\n tm.assert_series_equal(result, expected)\n\n result = a.radd(b)\n expected = pd.Series(["xa", "yb", None, None, None], dtype=dtype)\n tm.assert_series_equal(result, expected)\n\n result = a.add(b, fill_value="-")\n expected = pd.Series(["ax", "by", "c-", "-z", None], dtype=dtype)\n tm.assert_series_equal(result, expected)\n\n\ndef test_add_2d(dtype, request):\n if dtype.storage == "pyarrow":\n reason = "Failed: DID NOT RAISE <class 'ValueError'>"\n mark = pytest.mark.xfail(raises=None, reason=reason)\n request.applymarker(mark)\n\n a = pd.array(["a", "b", "c"], dtype=dtype)\n b = np.array([["a", "b", "c"]], dtype=object)\n with pytest.raises(ValueError, match="3 != 1"):\n a + b\n\n s = pd.Series(a)\n with pytest.raises(ValueError, match="3 != 1"):\n s + b\n\n\ndef test_add_sequence(dtype):\n a = pd.array(["a", "b", None, None], dtype=dtype)\n other = ["x", None, "y", None]\n\n result = a + other\n expected = pd.array(["ax", None, None, None], dtype=dtype)\n tm.assert_extension_array_equal(result, expected)\n\n result = other + a\n expected = pd.array(["xa", None, None, None], dtype=dtype)\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_mul(dtype):\n a = pd.array(["a", "b", None], dtype=dtype)\n result = a * 2\n expected = pd.array(["aa", "bb", None], dtype=dtype)\n tm.assert_extension_array_equal(result, expected)\n\n result = 2 * a\n tm.assert_extension_array_equal(result, expected)\n\n\n@pytest.mark.xfail(reason="GH-28527")\ndef test_add_strings(dtype):\n arr = pd.array(["a", "b", "c", "d"], dtype=dtype)\n df = pd.DataFrame([["t", "y", "v", "w"]], dtype=object)\n assert arr.__add__(df) is NotImplemented\n\n result = arr + df\n expected = pd.DataFrame([["at", "by", "cv", "dw"]]).astype(dtype)\n tm.assert_frame_equal(result, expected)\n\n result = df + arr\n expected = pd.DataFrame([["ta", "yb", "vc", "wd"]]).astype(dtype)\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.xfail(reason="GH-28527")\ndef test_add_frame(dtype):\n arr = pd.array(["a", "b", np.nan, np.nan], dtype=dtype)\n df = pd.DataFrame([["x", np.nan, "y", np.nan]])\n\n assert arr.__add__(df) is NotImplemented\n\n result = arr + df\n expected = pd.DataFrame([["ax", np.nan, np.nan, np.nan]]).astype(dtype)\n tm.assert_frame_equal(result, expected)\n\n result = df + arr\n expected = pd.DataFrame([["xa", np.nan, np.nan, np.nan]]).astype(dtype)\n tm.assert_frame_equal(result, expected)\n\n\ndef test_comparison_methods_scalar(comparison_op, dtype):\n op_name = f"__{comparison_op.__name__}__"\n a = pd.array(["a", None, "c"], dtype=dtype)\n other = "a"\n result = getattr(a, op_name)(other)\n if dtype.na_value is np.nan:\n expected = np.array([getattr(item, op_name)(other) for item in a])\n if comparison_op == operator.ne:\n expected[1] = True\n else:\n expected[1] = False\n tm.assert_numpy_array_equal(result, expected.astype(np.bool_))\n else:\n expected_dtype = "boolean[pyarrow]" if dtype.storage == "pyarrow" else "boolean"\n expected = np.array([getattr(item, op_name)(other) for item in a], dtype=object)\n expected = pd.array(expected, dtype=expected_dtype)\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_comparison_methods_scalar_pd_na(comparison_op, dtype):\n op_name = f"__{comparison_op.__name__}__"\n a = pd.array(["a", None, "c"], dtype=dtype)\n result = getattr(a, op_name)(pd.NA)\n\n if dtype.na_value is np.nan:\n if operator.ne == comparison_op:\n expected = np.array([True, True, True])\n else:\n expected = np.array([False, False, False])\n tm.assert_numpy_array_equal(result, expected)\n else:\n expected_dtype = "boolean[pyarrow]" if dtype.storage == "pyarrow" else "boolean"\n expected = pd.array([None, None, None], dtype=expected_dtype)\n tm.assert_extension_array_equal(result, expected)\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_comparison_methods_scalar_not_string(comparison_op, dtype):\n op_name = f"__{comparison_op.__name__}__"\n\n a = pd.array(["a", None, "c"], dtype=dtype)\n other = 42\n\n if op_name not in ["__eq__", "__ne__"]:\n with pytest.raises(TypeError, match="Invalid comparison|not supported between"):\n getattr(a, op_name)(other)\n\n return\n\n result = getattr(a, op_name)(other)\n\n if dtype.na_value is np.nan:\n expected_data = {\n "__eq__": [False, False, False],\n "__ne__": [True, True, True],\n }[op_name]\n expected = np.array(expected_data)\n tm.assert_numpy_array_equal(result, expected)\n else:\n expected_data = {"__eq__": [False, None, False], "__ne__": [True, None, True]}[\n op_name\n ]\n expected_dtype = "boolean[pyarrow]" if dtype.storage == "pyarrow" else "boolean"\n expected = pd.array(expected_data, dtype=expected_dtype)\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_comparison_methods_array(comparison_op, dtype):\n op_name = f"__{comparison_op.__name__}__"\n\n a = pd.array(["a", None, "c"], dtype=dtype)\n other = [None, None, "c"]\n result = getattr(a, op_name)(other)\n if dtype.na_value is np.nan:\n if operator.ne == comparison_op:\n expected = np.array([True, True, False])\n else:\n expected = np.array([False, False, False])\n expected[-1] = getattr(other[-1], op_name)(a[-1])\n tm.assert_numpy_array_equal(result, expected)\n\n result = getattr(a, op_name)(pd.NA)\n if operator.ne == comparison_op:\n expected = np.array([True, True, True])\n else:\n expected = np.array([False, False, False])\n tm.assert_numpy_array_equal(result, expected)\n\n else:\n expected_dtype = "boolean[pyarrow]" if dtype.storage == "pyarrow" else "boolean"\n expected = np.full(len(a), fill_value=None, dtype="object")\n expected[-1] = getattr(other[-1], op_name)(a[-1])\n expected = pd.array(expected, dtype=expected_dtype)\n tm.assert_extension_array_equal(result, expected)\n\n result = getattr(a, op_name)(pd.NA)\n expected = pd.array([None, None, None], dtype=expected_dtype)\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_constructor_raises(cls):\n if cls is pd.arrays.StringArray:\n msg = "StringArray requires a sequence of strings or pandas.NA"\n elif cls is StringArrayNumpySemantics:\n msg = "StringArrayNumpySemantics requires a sequence of strings or NaN"\n else:\n msg = "Unsupported type '<class 'numpy.ndarray'>' for ArrowExtensionArray"\n\n with pytest.raises(ValueError, match=msg):\n cls(np.array(["a", "b"], dtype="S1"))\n\n with pytest.raises(ValueError, match=msg):\n cls(np.array([]))\n\n if cls is pd.arrays.StringArray or cls is StringArrayNumpySemantics:\n # GH#45057 np.nan and None do NOT raise, as they are considered valid NAs\n # for string dtype\n cls(np.array(["a", np.nan], dtype=object))\n cls(np.array(["a", None], dtype=object))\n else:\n with pytest.raises(ValueError, match=msg):\n cls(np.array(["a", np.nan], dtype=object))\n with pytest.raises(ValueError, match=msg):\n cls(np.array(["a", None], dtype=object))\n\n with pytest.raises(ValueError, match=msg):\n cls(np.array(["a", pd.NaT], dtype=object))\n\n with pytest.raises(ValueError, match=msg):\n cls(np.array(["a", np.datetime64("NaT", "ns")], dtype=object))\n\n with pytest.raises(ValueError, match=msg):\n cls(np.array(["a", np.timedelta64("NaT", "ns")], dtype=object))\n\n\n@pytest.mark.parametrize("na", [np.nan, np.float64("nan"), float("nan"), None, pd.NA])\ndef test_constructor_nan_like(na):\n expected = pd.arrays.StringArray(np.array(["a", pd.NA]))\n tm.assert_extension_array_equal(\n pd.arrays.StringArray(np.array(["a", na], dtype="object")), expected\n )\n\n\n@pytest.mark.parametrize("copy", [True, False])\ndef test_from_sequence_no_mutate(copy, cls, dtype):\n nan_arr = np.array(["a", np.nan], dtype=object)\n expected_input = nan_arr.copy()\n na_arr = np.array(["a", pd.NA], dtype=object)\n\n result = cls._from_sequence(nan_arr, dtype=dtype, copy=copy)\n\n if cls in (ArrowStringArray, ArrowStringArrayNumpySemantics):\n import pyarrow as pa\n\n expected = cls(pa.array(na_arr, type=pa.string(), from_pandas=True))\n elif cls is StringArrayNumpySemantics:\n expected = cls(nan_arr)\n else:\n expected = cls(na_arr)\n\n tm.assert_extension_array_equal(result, expected)\n tm.assert_numpy_array_equal(nan_arr, expected_input)\n\n\ndef test_astype_int(dtype):\n arr = pd.array(["1", "2", "3"], dtype=dtype)\n result = arr.astype("int64")\n expected = np.array([1, 2, 3], dtype="int64")\n tm.assert_numpy_array_equal(result, expected)\n\n arr = pd.array(["1", pd.NA, "3"], dtype=dtype)\n if dtype.na_value is np.nan:\n err = ValueError\n msg = "cannot convert float NaN to integer"\n else:\n err = TypeError\n msg = (\n r"int\(\) argument must be a string, a bytes-like "\n r"object or a( real)? number"\n )\n with pytest.raises(err, match=msg):\n arr.astype("int64")\n\n\ndef test_astype_nullable_int(dtype):\n arr = pd.array(["1", pd.NA, "3"], dtype=dtype)\n\n result = arr.astype("Int64")\n expected = pd.array([1, pd.NA, 3], dtype="Int64")\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_astype_float(dtype, any_float_dtype):\n # Don't compare arrays (37974)\n ser = pd.Series(["1.1", pd.NA, "3.3"], dtype=dtype)\n result = ser.astype(any_float_dtype)\n expected = pd.Series([1.1, np.nan, 3.3], dtype=any_float_dtype)\n tm.assert_series_equal(result, expected)\n\n\n@pytest.mark.parametrize("skipna", [True, False])\ndef test_reduce(skipna, dtype):\n arr = pd.Series(["a", "b", "c"], dtype=dtype)\n result = arr.sum(skipna=skipna)\n assert result == "abc"\n\n\n@pytest.mark.parametrize("skipna", [True, False])\ndef test_reduce_missing(skipna, dtype):\n arr = pd.Series([None, "a", None, "b", "c", None], dtype=dtype)\n result = arr.sum(skipna=skipna)\n if skipna:\n assert result == "abc"\n else:\n assert pd.isna(result)\n\n\n@pytest.mark.parametrize("method", ["min", "max"])\n@pytest.mark.parametrize("skipna", [True, False])\ndef test_min_max(method, skipna, dtype):\n arr = pd.Series(["a", "b", "c", None], dtype=dtype)\n result = getattr(arr, method)(skipna=skipna)\n if skipna:\n expected = "a" if method == "min" else "c"\n assert result == expected\n else:\n assert result is arr.dtype.na_value\n\n\n@pytest.mark.parametrize("method", ["min", "max"])\n@pytest.mark.parametrize("box", [pd.Series, pd.array])\ndef test_min_max_numpy(method, box, dtype, request):\n if dtype.storage == "pyarrow" and box is pd.array:\n if box is pd.array:\n reason = "'<=' not supported between instances of 'str' and 'NoneType'"\n else:\n reason = "'ArrowStringArray' object has no attribute 'max'"\n mark = pytest.mark.xfail(raises=TypeError, reason=reason)\n request.applymarker(mark)\n\n arr = box(["a", "b", "c", None], dtype=dtype)\n result = getattr(np, method)(arr)\n expected = "a" if method == "min" else "c"\n assert result == expected\n\n\ndef test_fillna_args(dtype):\n # GH 37987\n\n arr = pd.array(["a", pd.NA], dtype=dtype)\n\n res = arr.fillna(value="b")\n expected = pd.array(["a", "b"], dtype=dtype)\n tm.assert_extension_array_equal(res, expected)\n\n res = arr.fillna(value=np.str_("b"))\n expected = pd.array(["a", "b"], dtype=dtype)\n tm.assert_extension_array_equal(res, expected)\n\n msg = "Invalid value '1' for dtype 'str"\n with pytest.raises(TypeError, match=msg):\n arr.fillna(value=1)\n\n\ndef test_arrow_array(dtype):\n # protocol added in 0.15.0\n pa = pytest.importorskip("pyarrow")\n import pyarrow.compute as pc\n\n data = pd.array(["a", "b", "c"], dtype=dtype)\n arr = pa.array(data)\n expected = pa.array(list(data), type=pa.large_string(), from_pandas=True)\n if dtype.storage == "pyarrow" and pa_version_under12p0:\n expected = pa.chunked_array(expected)\n if dtype.storage == "python":\n expected = pc.cast(expected, pa.string())\n assert arr.equals(expected)\n\n\n@pytest.mark.filterwarnings("ignore:Passing a BlockManager:DeprecationWarning")\ndef test_arrow_roundtrip(dtype, string_storage, using_infer_string):\n # roundtrip possible from arrow 1.0.0\n pa = pytest.importorskip("pyarrow")\n\n data = pd.array(["a", "b", None], dtype=dtype)\n df = pd.DataFrame({"a": data})\n table = pa.table(df)\n if dtype.storage == "python":\n assert table.field("a").type == "string"\n else:\n assert table.field("a").type == "large_string"\n with pd.option_context("string_storage", string_storage):\n result = table.to_pandas()\n if dtype.na_value is np.nan and not using_infer_string:\n assert result["a"].dtype == "object"\n else:\n assert isinstance(result["a"].dtype, pd.StringDtype)\n expected = df.astype(pd.StringDtype(string_storage, na_value=dtype.na_value))\n if using_infer_string:\n expected.columns = expected.columns.astype(\n pd.StringDtype(string_storage, na_value=np.nan)\n )\n tm.assert_frame_equal(result, expected)\n # ensure the missing value is represented by NA and not np.nan or None\n assert result.loc[2, "a"] is result["a"].dtype.na_value\n\n\n@pytest.mark.filterwarnings("ignore:Passing a BlockManager:DeprecationWarning")\ndef test_arrow_from_string(using_infer_string):\n # not roundtrip, but starting with pyarrow table without pandas metadata\n pa = pytest.importorskip("pyarrow")\n table = pa.table({"a": pa.array(["a", "b", None], type=pa.string())})\n\n result = table.to_pandas()\n\n if using_infer_string and not pa_version_under19p0:\n expected = pd.DataFrame({"a": ["a", "b", None]}, dtype="str")\n else:\n expected = pd.DataFrame({"a": ["a", "b", None]}, dtype="object")\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.filterwarnings("ignore:Passing a BlockManager:DeprecationWarning")\ndef test_arrow_load_from_zero_chunks(dtype, string_storage, using_infer_string):\n # GH-41040\n pa = pytest.importorskip("pyarrow")\n\n data = pd.array([], dtype=dtype)\n df = pd.DataFrame({"a": data})\n table = pa.table(df)\n if dtype.storage == "python":\n assert table.field("a").type == "string"\n else:\n assert table.field("a").type == "large_string"\n # Instantiate the same table with no chunks at all\n table = pa.table([pa.chunked_array([], type=pa.string())], schema=table.schema)\n with pd.option_context("string_storage", string_storage):\n result = table.to_pandas()\n\n if dtype.na_value is np.nan and not using_string_dtype():\n assert result["a"].dtype == "object"\n else:\n assert isinstance(result["a"].dtype, pd.StringDtype)\n expected = df.astype(pd.StringDtype(string_storage, na_value=dtype.na_value))\n if using_infer_string:\n expected.columns = expected.columns.astype(\n pd.StringDtype(string_storage, na_value=np.nan)\n )\n tm.assert_frame_equal(result, expected)\n\n\ndef test_value_counts_na(dtype):\n if dtype.na_value is np.nan:\n exp_dtype = "int64"\n elif dtype.storage == "pyarrow":\n exp_dtype = "int64[pyarrow]"\n else:\n exp_dtype = "Int64"\n arr = pd.array(["a", "b", "a", pd.NA], dtype=dtype)\n result = arr.value_counts(dropna=False)\n expected = pd.Series([2, 1, 1], index=arr[[0, 1, 3]], dtype=exp_dtype, name="count")\n tm.assert_series_equal(result, expected)\n\n result = arr.value_counts(dropna=True)\n expected = pd.Series([2, 1], index=arr[:2], dtype=exp_dtype, name="count")\n tm.assert_series_equal(result, expected)\n\n\ndef test_value_counts_with_normalize(dtype):\n if dtype.na_value is np.nan:\n exp_dtype = np.float64\n elif dtype.storage == "pyarrow":\n exp_dtype = "double[pyarrow]"\n else:\n exp_dtype = "Float64"\n ser = pd.Series(["a", "b", "a", pd.NA], dtype=dtype)\n result = ser.value_counts(normalize=True)\n expected = pd.Series([2, 1], index=ser[:2], dtype=exp_dtype, name="proportion") / 3\n tm.assert_series_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "values, expected",\n [\n (["a", "b", "c"], np.array([False, False, False])),\n (["a", "b", None], np.array([False, False, True])),\n ],\n)\ndef test_use_inf_as_na(values, expected, dtype):\n # https://github.com/pandas-dev/pandas/issues/33655\n values = pd.array(values, dtype=dtype)\n msg = "use_inf_as_na option is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n with pd.option_context("mode.use_inf_as_na", True):\n result = values.isna()\n tm.assert_numpy_array_equal(result, expected)\n\n result = pd.Series(values).isna()\n expected = pd.Series(expected)\n tm.assert_series_equal(result, expected)\n\n result = pd.DataFrame(values).isna()\n expected = pd.DataFrame(expected)\n tm.assert_frame_equal(result, expected)\n\n\ndef test_value_counts_sort_false(dtype):\n if dtype.na_value is np.nan:\n exp_dtype = "int64"\n elif dtype.storage == "pyarrow":\n exp_dtype = "int64[pyarrow]"\n else:\n exp_dtype = "Int64"\n ser = pd.Series(["a", "b", "c", "b"], dtype=dtype)\n result = ser.value_counts(sort=False)\n expected = pd.Series([1, 2, 1], index=ser[:3], dtype=exp_dtype, name="count")\n tm.assert_series_equal(result, expected)\n\n\ndef test_memory_usage(dtype):\n # GH 33963\n\n if dtype.storage == "pyarrow":\n pytest.skip(f"not applicable for {dtype.storage}")\n\n series = pd.Series(["a", "b", "c"], dtype=dtype)\n\n assert 0 < series.nbytes <= series.memory_usage() < series.memory_usage(deep=True)\n\n\n@pytest.mark.parametrize("float_dtype", [np.float16, np.float32, np.float64])\ndef test_astype_from_float_dtype(float_dtype, dtype):\n # https://github.com/pandas-dev/pandas/issues/36451\n ser = pd.Series([0.1], dtype=float_dtype)\n result = ser.astype(dtype)\n expected = pd.Series(["0.1"], dtype=dtype)\n tm.assert_series_equal(result, expected)\n\n\ndef test_to_numpy_returns_pdna_default(dtype):\n arr = pd.array(["a", pd.NA, "b"], dtype=dtype)\n result = np.array(arr)\n expected = np.array(["a", dtype.na_value, "b"], dtype=object)\n tm.assert_numpy_array_equal(result, expected)\n\n\ndef test_to_numpy_na_value(dtype, nulls_fixture):\n na_value = nulls_fixture\n arr = pd.array(["a", pd.NA, "b"], dtype=dtype)\n result = arr.to_numpy(na_value=na_value)\n expected = np.array(["a", na_value, "b"], dtype=object)\n tm.assert_numpy_array_equal(result, expected)\n\n\ndef test_isin(dtype, fixed_now_ts):\n s = pd.Series(["a", "b", None], dtype=dtype)\n\n result = s.isin(["a", "c"])\n expected = pd.Series([True, False, False])\n tm.assert_series_equal(result, expected)\n\n result = s.isin(["a", pd.NA])\n expected = pd.Series([True, False, True])\n tm.assert_series_equal(result, expected)\n\n result = s.isin([])\n expected = pd.Series([False, False, False])\n tm.assert_series_equal(result, expected)\n\n result = s.isin(["a", fixed_now_ts])\n expected = pd.Series([True, False, False])\n tm.assert_series_equal(result, expected)\n\n result = s.isin([fixed_now_ts])\n expected = pd.Series([False, False, False])\n tm.assert_series_equal(result, expected)\n\n\ndef test_isin_string_array(dtype, dtype2):\n s = pd.Series(["a", "b", None], dtype=dtype)\n\n result = s.isin(pd.array(["a", "c"], dtype=dtype2))\n expected = pd.Series([True, False, False])\n tm.assert_series_equal(result, expected)\n\n result = s.isin(pd.array(["a", None], dtype=dtype2))\n expected = pd.Series([True, False, True])\n tm.assert_series_equal(result, expected)\n\n\ndef test_isin_arrow_string_array(dtype):\n pa = pytest.importorskip("pyarrow")\n s = pd.Series(["a", "b", None], dtype=dtype)\n\n result = s.isin(pd.array(["a", "c"], dtype=pd.ArrowDtype(pa.string())))\n expected = pd.Series([True, False, False])\n tm.assert_series_equal(result, expected)\n\n result = s.isin(pd.array(["a", None], dtype=pd.ArrowDtype(pa.string())))\n expected = pd.Series([True, False, True])\n tm.assert_series_equal(result, expected)\n\n\ndef test_setitem_scalar_with_mask_validation(dtype):\n # https://github.com/pandas-dev/pandas/issues/47628\n # setting None with a boolean mask (through _putmaks) should still result\n # in pd.NA values in the underlying array\n ser = pd.Series(["a", "b", "c"], dtype=dtype)\n mask = np.array([False, True, False])\n\n ser[mask] = None\n assert ser.array[1] is ser.dtype.na_value\n\n # for other non-string we should also raise an error\n ser = pd.Series(["a", "b", "c"], dtype=dtype)\n msg = "Invalid value '1' for dtype 'str"\n with pytest.raises(TypeError, match=msg):\n ser[mask] = 1\n\n\ndef test_from_numpy_str(dtype):\n vals = ["a", "b", "c"]\n arr = np.array(vals, dtype=np.str_)\n result = pd.array(arr, dtype=dtype)\n expected = pd.array(vals, dtype=dtype)\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_tolist(dtype):\n vals = ["a", "b", "c"]\n arr = pd.array(vals, dtype=dtype)\n result = arr.tolist()\n expected = vals\n tm.assert_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\arrays\string_\test_string.py
test_string.py
Python
26,982
0.95
0.132147
0.036424
react-lib
539
2024-07-12T04:49:17.207155
GPL-3.0
true
6da73b82b8bf1503aed7713d4dd26767
import pickle\nimport re\n\nimport numpy as np\nimport pytest\n\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.core.arrays.string_ import (\n StringArray,\n StringDtype,\n)\nfrom pandas.core.arrays.string_arrow import (\n ArrowStringArray,\n ArrowStringArrayNumpySemantics,\n)\n\n\ndef test_eq_all_na():\n pytest.importorskip("pyarrow")\n a = pd.array([pd.NA, pd.NA], dtype=StringDtype("pyarrow"))\n result = a == a\n expected = pd.array([pd.NA, pd.NA], dtype="boolean[pyarrow]")\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_config(string_storage, using_infer_string):\n # with the default string_storage setting\n # always "python" at the moment\n assert StringDtype().storage == "python"\n\n with pd.option_context("string_storage", string_storage):\n assert StringDtype().storage == string_storage\n result = pd.array(["a", "b"])\n assert result.dtype.storage == string_storage\n\n # pd.array(..) by default always returns the NA-variant\n dtype = StringDtype(string_storage, na_value=pd.NA)\n expected = dtype.construct_array_type()._from_sequence(["a", "b"], dtype=dtype)\n tm.assert_equal(result, expected)\n\n\ndef test_config_bad_storage_raises():\n msg = re.escape("Value must be one of python|pyarrow")\n with pytest.raises(ValueError, match=msg):\n pd.options.mode.string_storage = "foo"\n\n\n@pytest.mark.parametrize("chunked", [True, False])\n@pytest.mark.parametrize("array_lib", ["numpy", "pyarrow"])\ndef test_constructor_not_string_type_raises(array_lib, chunked):\n pa = pytest.importorskip("pyarrow")\n\n array_lib = pa if array_lib == "pyarrow" else np\n\n arr = array_lib.array([1, 2, 3])\n if chunked:\n if array_lib is np:\n pytest.skip("chunked not applicable to numpy array")\n arr = pa.chunked_array(arr)\n if array_lib is np:\n msg = "Unsupported type '<class 'numpy.ndarray'>' for ArrowExtensionArray"\n else:\n msg = re.escape(\n "ArrowStringArray requires a PyArrow (chunked) array of large_string type"\n )\n with pytest.raises(ValueError, match=msg):\n ArrowStringArray(arr)\n\n\n@pytest.mark.parametrize("chunked", [True, False])\ndef test_constructor_not_string_type_value_dictionary_raises(chunked):\n pa = pytest.importorskip("pyarrow")\n\n arr = pa.array([1, 2, 3], pa.dictionary(pa.int32(), pa.int32()))\n if chunked:\n arr = pa.chunked_array(arr)\n\n msg = re.escape(\n "ArrowStringArray requires a PyArrow (chunked) array of large_string type"\n )\n with pytest.raises(ValueError, match=msg):\n ArrowStringArray(arr)\n\n\n@pytest.mark.parametrize("string_type", ["string", "large_string"])\n@pytest.mark.parametrize("chunked", [True, False])\ndef test_constructor_valid_string_type_value_dictionary(string_type, chunked):\n pa = pytest.importorskip("pyarrow")\n\n arr = pa.array(["1", "2", "3"], getattr(pa, string_type)()).dictionary_encode()\n if chunked:\n arr = pa.chunked_array(arr)\n\n arr = ArrowStringArray(arr)\n # dictionary type get converted to dense large string array\n assert pa.types.is_large_string(arr._pa_array.type)\n\n\n@pytest.mark.parametrize("chunked", [True, False])\ndef test_constructor_valid_string_view(chunked):\n # requires pyarrow>=18 for casting string_view to string\n pa = pytest.importorskip("pyarrow", minversion="18")\n\n arr = pa.array(["1", "2", "3"], pa.string_view())\n if chunked:\n arr = pa.chunked_array(arr)\n\n arr = ArrowStringArray(arr)\n # dictionary type get converted to dense large string array\n assert pa.types.is_large_string(arr._pa_array.type)\n\n\ndef test_constructor_from_list():\n # GH#27673\n pytest.importorskip("pyarrow")\n result = pd.Series(["E"], dtype=StringDtype(storage="pyarrow"))\n assert isinstance(result.dtype, StringDtype)\n assert result.dtype.storage == "pyarrow"\n\n\ndef test_from_sequence_wrong_dtype_raises(using_infer_string):\n pytest.importorskip("pyarrow")\n with pd.option_context("string_storage", "python"):\n ArrowStringArray._from_sequence(["a", None, "c"], dtype="string")\n\n with pd.option_context("string_storage", "pyarrow"):\n ArrowStringArray._from_sequence(["a", None, "c"], dtype="string")\n\n with pytest.raises(AssertionError, match=None):\n ArrowStringArray._from_sequence(["a", None, "c"], dtype="string[python]")\n\n ArrowStringArray._from_sequence(["a", None, "c"], dtype="string[pyarrow]")\n\n if not using_infer_string:\n with pytest.raises(AssertionError, match=None):\n with pd.option_context("string_storage", "python"):\n ArrowStringArray._from_sequence(["a", None, "c"], dtype=StringDtype())\n\n with pd.option_context("string_storage", "pyarrow"):\n ArrowStringArray._from_sequence(["a", None, "c"], dtype=StringDtype())\n\n if not using_infer_string:\n with pytest.raises(AssertionError, match=None):\n ArrowStringArray._from_sequence(\n ["a", None, "c"], dtype=StringDtype("python")\n )\n\n ArrowStringArray._from_sequence(["a", None, "c"], dtype=StringDtype("pyarrow"))\n\n with pd.option_context("string_storage", "python"):\n StringArray._from_sequence(["a", None, "c"], dtype="string")\n\n with pd.option_context("string_storage", "pyarrow"):\n StringArray._from_sequence(["a", None, "c"], dtype="string")\n\n StringArray._from_sequence(["a", None, "c"], dtype="string[python]")\n\n with pytest.raises(AssertionError, match=None):\n StringArray._from_sequence(["a", None, "c"], dtype="string[pyarrow]")\n\n if not using_infer_string:\n with pd.option_context("string_storage", "python"):\n StringArray._from_sequence(["a", None, "c"], dtype=StringDtype())\n\n if not using_infer_string:\n with pytest.raises(AssertionError, match=None):\n with pd.option_context("string_storage", "pyarrow"):\n StringArray._from_sequence(["a", None, "c"], dtype=StringDtype())\n\n StringArray._from_sequence(["a", None, "c"], dtype=StringDtype("python"))\n\n with pytest.raises(AssertionError, match=None):\n StringArray._from_sequence(["a", None, "c"], dtype=StringDtype("pyarrow"))\n\n\n@td.skip_if_installed("pyarrow")\ndef test_pyarrow_not_installed_raises():\n msg = re.escape("pyarrow>=10.0.1 is required for PyArrow backed")\n\n with pytest.raises(ImportError, match=msg):\n StringDtype(storage="pyarrow")\n\n with pytest.raises(ImportError, match=msg):\n ArrowStringArray([])\n\n with pytest.raises(ImportError, match=msg):\n ArrowStringArrayNumpySemantics([])\n\n with pytest.raises(ImportError, match=msg):\n ArrowStringArray._from_sequence(["a", None, "b"])\n\n\n@pytest.mark.parametrize("multiple_chunks", [False, True])\n@pytest.mark.parametrize(\n "key, value, expected",\n [\n (-1, "XX", ["a", "b", "c", "d", "XX"]),\n (1, "XX", ["a", "XX", "c", "d", "e"]),\n (1, None, ["a", None, "c", "d", "e"]),\n (1, pd.NA, ["a", None, "c", "d", "e"]),\n ([1, 3], "XX", ["a", "XX", "c", "XX", "e"]),\n ([1, 3], ["XX", "YY"], ["a", "XX", "c", "YY", "e"]),\n ([1, 3], ["XX", None], ["a", "XX", "c", None, "e"]),\n ([1, 3], ["XX", pd.NA], ["a", "XX", "c", None, "e"]),\n ([0, -1], ["XX", "YY"], ["XX", "b", "c", "d", "YY"]),\n ([-1, 0], ["XX", "YY"], ["YY", "b", "c", "d", "XX"]),\n (slice(3, None), "XX", ["a", "b", "c", "XX", "XX"]),\n (slice(2, 4), ["XX", "YY"], ["a", "b", "XX", "YY", "e"]),\n (slice(3, 1, -1), ["XX", "YY"], ["a", "b", "YY", "XX", "e"]),\n (slice(None), "XX", ["XX", "XX", "XX", "XX", "XX"]),\n ([False, True, False, True, False], ["XX", "YY"], ["a", "XX", "c", "YY", "e"]),\n ],\n)\ndef test_setitem(multiple_chunks, key, value, expected):\n pa = pytest.importorskip("pyarrow")\n\n result = pa.array(list("abcde"))\n expected = pa.array(expected)\n\n if multiple_chunks:\n result = pa.chunked_array([result[:3], result[3:]])\n expected = pa.chunked_array([expected[:3], expected[3:]])\n\n result = ArrowStringArray(result)\n expected = ArrowStringArray(expected)\n\n result[key] = value\n tm.assert_equal(result, expected)\n\n\ndef test_setitem_invalid_indexer_raises():\n pa = pytest.importorskip("pyarrow")\n\n arr = ArrowStringArray(pa.array(list("abcde")))\n\n with pytest.raises(IndexError, match=None):\n arr[5] = "foo"\n\n with pytest.raises(IndexError, match=None):\n arr[-6] = "foo"\n\n with pytest.raises(IndexError, match=None):\n arr[[0, 5]] = "foo"\n\n with pytest.raises(IndexError, match=None):\n arr[[0, -6]] = "foo"\n\n with pytest.raises(IndexError, match=None):\n arr[[True, True, False]] = "foo"\n\n with pytest.raises(ValueError, match=None):\n arr[[0, 1]] = ["foo", "bar", "baz"]\n\n\n@pytest.mark.parametrize("na_value", [pd.NA, np.nan])\ndef test_pickle_roundtrip(na_value):\n # GH 42600\n pytest.importorskip("pyarrow")\n dtype = StringDtype("pyarrow", na_value=na_value)\n expected = pd.Series(range(10), dtype=dtype)\n expected_sliced = expected.head(2)\n full_pickled = pickle.dumps(expected)\n sliced_pickled = pickle.dumps(expected_sliced)\n\n assert len(full_pickled) > len(sliced_pickled)\n\n result = pickle.loads(full_pickled)\n tm.assert_series_equal(result, expected)\n\n result_sliced = pickle.loads(sliced_pickled)\n tm.assert_series_equal(result_sliced, expected_sliced)\n\n\ndef test_string_dtype_error_message():\n # GH#55051\n pytest.importorskip("pyarrow")\n msg = "Storage must be 'python' or 'pyarrow'."\n with pytest.raises(ValueError, match=msg):\n StringDtype("bla")\n
.venv\Lib\site-packages\pandas\tests\arrays\string_\test_string_arrow.py
test_string_arrow.py
Python
9,712
0.95
0.106383
0.043269
awesome-app
320
2025-05-21T10:01:18.604049
MIT
true
b7f1030f15271a8b0f2220ce02065d46
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\string_\__pycache__\test_concat.cpython-313.pyc
test_concat.cpython-313.pyc
Other
4,620
0.95
0
0
vue-tools
700
2024-09-16T07:25:43.003807
Apache-2.0
true
b7b87f35dd72f1e5a758dbc56d4996cf
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\string_\__pycache__\test_string.cpython-313.pyc
test_string.cpython-313.pyc
Other
44,901
0.95
0.01626
0.017094
vue-tools
41
2024-10-27T05:44:28.507706
MIT
true
0dc258c36f89db8d9a12d92b90b8d100
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\string_\__pycache__\test_string_arrow.cpython-313.pyc
test_string_arrow.cpython-313.pyc
Other
16,643
0.95
0.012658
0
react-lib
609
2024-01-12T13:39:52.210320
Apache-2.0
true
d15a9ac7c8cbfad809701b85539d8d89
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\string_\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
202
0.7
0
0
node-utils
681
2024-05-16T19:58:22.768625
BSD-3-Clause
true
db8927eefac667f7fb0dc279e009c2ee
import numpy as np\nimport pytest\n\nimport pandas._testing as tm\nfrom pandas.core.arrays import TimedeltaArray\n\n\nclass TestTimedeltaArrayConstructor:\n def test_only_1dim_accepted(self):\n # GH#25282\n arr = np.array([0, 1, 2, 3], dtype="m8[h]").astype("m8[ns]")\n\n depr_msg = "TimedeltaArray.__init__ is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n with pytest.raises(ValueError, match="Only 1-dimensional"):\n # 3-dim, we allow 2D to sneak in for ops purposes GH#29853\n TimedeltaArray(arr.reshape(2, 2, 1))\n\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n with pytest.raises(ValueError, match="Only 1-dimensional"):\n # 0-dim\n TimedeltaArray(arr[[0]].squeeze())\n\n def test_freq_validation(self):\n # ensure that the public constructor cannot create an invalid instance\n arr = np.array([0, 0, 1], dtype=np.int64) * 3600 * 10**9\n\n msg = (\n "Inferred frequency None from passed values does not "\n "conform to passed frequency D"\n )\n depr_msg = "TimedeltaArray.__init__ is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n with pytest.raises(ValueError, match=msg):\n TimedeltaArray(arr.view("timedelta64[ns]"), freq="D")\n\n def test_non_array_raises(self):\n depr_msg = "TimedeltaArray.__init__ is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n with pytest.raises(ValueError, match="list"):\n TimedeltaArray([1, 2, 3])\n\n def test_other_type_raises(self):\n msg = r"dtype bool cannot be converted to timedelta64\[ns\]"\n with pytest.raises(TypeError, match=msg):\n TimedeltaArray._from_sequence(np.array([1, 2, 3], dtype="bool"))\n\n def test_incorrect_dtype_raises(self):\n msg = "dtype 'category' is invalid, should be np.timedelta64 dtype"\n with pytest.raises(ValueError, match=msg):\n TimedeltaArray._from_sequence(\n np.array([1, 2, 3], dtype="i8"), dtype="category"\n )\n\n msg = "dtype 'int64' is invalid, should be np.timedelta64 dtype"\n with pytest.raises(ValueError, match=msg):\n TimedeltaArray._from_sequence(\n np.array([1, 2, 3], dtype="i8"), dtype=np.dtype("int64")\n )\n\n msg = r"dtype 'datetime64\[ns\]' is invalid, should be np.timedelta64 dtype"\n with pytest.raises(ValueError, match=msg):\n TimedeltaArray._from_sequence(\n np.array([1, 2, 3], dtype="i8"), dtype=np.dtype("M8[ns]")\n )\n\n msg = (\n r"dtype 'datetime64\[us, UTC\]' is invalid, should be np.timedelta64 dtype"\n )\n with pytest.raises(ValueError, match=msg):\n TimedeltaArray._from_sequence(\n np.array([1, 2, 3], dtype="i8"), dtype="M8[us, UTC]"\n )\n\n msg = "Supported timedelta64 resolutions are 's', 'ms', 'us', 'ns'"\n with pytest.raises(ValueError, match=msg):\n TimedeltaArray._from_sequence(\n np.array([1, 2, 3], dtype="i8"), dtype=np.dtype("m8[Y]")\n )\n\n def test_mismatched_values_dtype_units(self):\n arr = np.array([1, 2, 3], dtype="m8[s]")\n dtype = np.dtype("m8[ns]")\n msg = r"Values resolution does not match dtype"\n depr_msg = "TimedeltaArray.__init__ is deprecated"\n\n with tm.assert_produces_warning(FutureWarning, match=depr_msg):\n with pytest.raises(ValueError, match=msg):\n TimedeltaArray(arr, dtype=dtype)\n\n def test_copy(self):\n data = np.array([1, 2, 3], dtype="m8[ns]")\n arr = TimedeltaArray._from_sequence(data, copy=False)\n assert arr._ndarray is data\n\n arr = TimedeltaArray._from_sequence(data, copy=True)\n assert arr._ndarray is not data\n assert arr._ndarray.base is not data\n\n def test_from_sequence_dtype(self):\n msg = "dtype 'object' is invalid, should be np.timedelta64 dtype"\n with pytest.raises(ValueError, match=msg):\n TimedeltaArray._from_sequence([], dtype=object)\n
.venv\Lib\site-packages\pandas\tests\arrays\timedeltas\test_constructors.py
test_constructors.py
Python
4,248
0.95
0.097087
0.047619
vue-tools
969
2024-06-20T22:01:42.048047
MIT
true
0e91216b154768221806ddd3c1e9a4e9
import pytest\n\nimport pandas._testing as tm\nfrom pandas.core.arrays import TimedeltaArray\n\n\nclass TestAccumulator:\n def test_accumulators_disallowed(self):\n # GH#50297\n arr = TimedeltaArray._from_sequence(["1D", "2D"], dtype="m8[ns]")\n with pytest.raises(TypeError, match="cumprod not supported"):\n arr._accumulate("cumprod")\n\n def test_cumsum(self, unit):\n # GH#50297\n dtype = f"m8[{unit}]"\n arr = TimedeltaArray._from_sequence(["1D", "2D"], dtype=dtype)\n result = arr._accumulate("cumsum")\n expected = TimedeltaArray._from_sequence(["1D", "3D"], dtype=dtype)\n tm.assert_timedelta_array_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\arrays\timedeltas\test_cumulative.py
test_cumulative.py
Python
692
0.95
0.15
0.125
python-kit
808
2023-08-12T09:59:25.548246
MIT
true
da510833bd7152f6b5fc551162606d37
import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import Timedelta\nimport pandas._testing as tm\nfrom pandas.core import nanops\nfrom pandas.core.arrays import TimedeltaArray\n\n\nclass TestReductions:\n @pytest.mark.parametrize("name", ["std", "min", "max", "median", "mean"])\n @pytest.mark.parametrize("skipna", [True, False])\n def test_reductions_empty(self, name, skipna):\n tdi = pd.TimedeltaIndex([])\n arr = tdi.array\n\n result = getattr(tdi, name)(skipna=skipna)\n assert result is pd.NaT\n\n result = getattr(arr, name)(skipna=skipna)\n assert result is pd.NaT\n\n @pytest.mark.parametrize("skipna", [True, False])\n def test_sum_empty(self, skipna):\n tdi = pd.TimedeltaIndex([])\n arr = tdi.array\n\n result = tdi.sum(skipna=skipna)\n assert isinstance(result, Timedelta)\n assert result == Timedelta(0)\n\n result = arr.sum(skipna=skipna)\n assert isinstance(result, Timedelta)\n assert result == Timedelta(0)\n\n def test_min_max(self, unit):\n dtype = f"m8[{unit}]"\n arr = TimedeltaArray._from_sequence(\n ["3h", "3h", "NaT", "2h", "5h", "4h"], dtype=dtype\n )\n\n result = arr.min()\n expected = Timedelta("2h")\n assert result == expected\n\n result = arr.max()\n expected = Timedelta("5h")\n assert result == expected\n\n result = arr.min(skipna=False)\n assert result is pd.NaT\n\n result = arr.max(skipna=False)\n assert result is pd.NaT\n\n def test_sum(self):\n tdi = pd.TimedeltaIndex(["3h", "3h", "NaT", "2h", "5h", "4h"])\n arr = tdi.array\n\n result = arr.sum(skipna=True)\n expected = Timedelta(hours=17)\n assert isinstance(result, Timedelta)\n assert result == expected\n\n result = tdi.sum(skipna=True)\n assert isinstance(result, Timedelta)\n assert result == expected\n\n result = arr.sum(skipna=False)\n assert result is pd.NaT\n\n result = tdi.sum(skipna=False)\n assert result is pd.NaT\n\n result = arr.sum(min_count=9)\n assert result is pd.NaT\n\n result = tdi.sum(min_count=9)\n assert result is pd.NaT\n\n result = arr.sum(min_count=1)\n assert isinstance(result, Timedelta)\n assert result == expected\n\n result = tdi.sum(min_count=1)\n assert isinstance(result, Timedelta)\n assert result == expected\n\n def test_npsum(self):\n # GH#25282, GH#25335 np.sum should return a Timedelta, not timedelta64\n tdi = pd.TimedeltaIndex(["3h", "3h", "2h", "5h", "4h"])\n arr = tdi.array\n\n result = np.sum(tdi)\n expected = Timedelta(hours=17)\n assert isinstance(result, Timedelta)\n assert result == expected\n\n result = np.sum(arr)\n assert isinstance(result, Timedelta)\n assert result == expected\n\n def test_sum_2d_skipna_false(self):\n arr = np.arange(8).astype(np.int64).view("m8[s]").astype("m8[ns]").reshape(4, 2)\n arr[-1, -1] = "Nat"\n\n tda = TimedeltaArray._from_sequence(arr)\n\n result = tda.sum(skipna=False)\n assert result is pd.NaT\n\n result = tda.sum(axis=0, skipna=False)\n expected = pd.TimedeltaIndex([Timedelta(seconds=12), pd.NaT])._values\n tm.assert_timedelta_array_equal(result, expected)\n\n result = tda.sum(axis=1, skipna=False)\n expected = pd.TimedeltaIndex(\n [\n Timedelta(seconds=1),\n Timedelta(seconds=5),\n Timedelta(seconds=9),\n pd.NaT,\n ]\n )._values\n tm.assert_timedelta_array_equal(result, expected)\n\n # Adding a Timestamp makes this a test for DatetimeArray.std\n @pytest.mark.parametrize(\n "add",\n [\n Timedelta(0),\n pd.Timestamp("2021-01-01"),\n pd.Timestamp("2021-01-01", tz="UTC"),\n pd.Timestamp("2021-01-01", tz="Asia/Tokyo"),\n ],\n )\n def test_std(self, add):\n tdi = pd.TimedeltaIndex(["0h", "4h", "NaT", "4h", "0h", "2h"]) + add\n arr = tdi.array\n\n result = arr.std(skipna=True)\n expected = Timedelta(hours=2)\n assert isinstance(result, Timedelta)\n assert result == expected\n\n result = tdi.std(skipna=True)\n assert isinstance(result, Timedelta)\n assert result == expected\n\n if getattr(arr, "tz", None) is None:\n result = nanops.nanstd(np.asarray(arr), skipna=True)\n assert isinstance(result, np.timedelta64)\n assert result == expected\n\n result = arr.std(skipna=False)\n assert result is pd.NaT\n\n result = tdi.std(skipna=False)\n assert result is pd.NaT\n\n if getattr(arr, "tz", None) is None:\n result = nanops.nanstd(np.asarray(arr), skipna=False)\n assert isinstance(result, np.timedelta64)\n assert np.isnat(result)\n\n def test_median(self):\n tdi = pd.TimedeltaIndex(["0h", "3h", "NaT", "5h06m", "0h", "2h"])\n arr = tdi.array\n\n result = arr.median(skipna=True)\n expected = Timedelta(hours=2)\n assert isinstance(result, Timedelta)\n assert result == expected\n\n result = tdi.median(skipna=True)\n assert isinstance(result, Timedelta)\n assert result == expected\n\n result = arr.median(skipna=False)\n assert result is pd.NaT\n\n result = tdi.median(skipna=False)\n assert result is pd.NaT\n\n def test_mean(self):\n tdi = pd.TimedeltaIndex(["0h", "3h", "NaT", "5h06m", "0h", "2h"])\n arr = tdi._data\n\n # manually verified result\n expected = Timedelta(arr.dropna()._ndarray.mean())\n\n result = arr.mean()\n assert result == expected\n result = arr.mean(skipna=False)\n assert result is pd.NaT\n\n result = arr.dropna().mean(skipna=False)\n assert result == expected\n\n result = arr.mean(axis=0)\n assert result == expected\n\n def test_mean_2d(self):\n tdi = pd.timedelta_range("14 days", periods=6)\n tda = tdi._data.reshape(3, 2)\n\n result = tda.mean(axis=0)\n expected = tda[1]\n tm.assert_timedelta_array_equal(result, expected)\n\n result = tda.mean(axis=1)\n expected = tda[:, 0] + Timedelta(hours=12)\n tm.assert_timedelta_array_equal(result, expected)\n\n result = tda.mean(axis=None)\n expected = tdi.mean()\n assert result == expected\n
.venv\Lib\site-packages\pandas\tests\arrays\timedeltas\test_reductions.py
test_reductions.py
Python
6,520
0.95
0.06422
0.017964
vue-tools
970
2024-05-28T11:13:08.307959
BSD-3-Clause
true
592accb7944a108d0dc760ca35bc31b6
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\timedeltas\__pycache__\test_constructors.cpython-313.pyc
test_constructors.cpython-313.pyc
Other
7,897
0.8
0
0
node-utils
793
2023-07-11T03:16:49.822010
Apache-2.0
true
e8ecc326b29108df723b1854fcc592bb
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\timedeltas\__pycache__\test_cumulative.cpython-313.pyc
test_cumulative.cpython-313.pyc
Other
1,637
0.8
0
0
vue-tools
997
2025-06-29T04:37:29.549943
GPL-3.0
true
9555c38434db31ae3a94973ea4217a64
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\timedeltas\__pycache__\test_reductions.cpython-313.pyc
test_reductions.cpython-313.pyc
Other
10,615
0.8
0
0
vue-tools
970
2025-03-01T21:30:03.588082
MIT
true
0db34de9f7e337cc92bfa23f658d3b1e
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\timedeltas\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
205
0.7
0
0
vue-tools
192
2024-11-13T03:17:48.250041
GPL-3.0
true
2ce1753ed7983d4f7645885c89105fba
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\__pycache__\masked_shared.cpython-313.pyc
masked_shared.cpython-313.pyc
Other
8,028
0.8
0.013333
0
python-kit
480
2023-08-10T00:21:58.456862
GPL-3.0
true
b1bdc22eb0cfcc5b8911818df8903ef8
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\__pycache__\test_array.cpython-313.pyc
test_array.cpython-313.pyc
Other
21,706
0.8
0
0.034913
node-utils
723
2023-08-16T10:50:44.081274
GPL-3.0
true
33a9e5269acbf36f354a72200f630790
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\__pycache__\test_datetimelike.cpython-313.pyc
test_datetimelike.cpython-313.pyc
Other
69,202
0.6
0
0.004959
vue-tools
548
2024-11-28T04:55:29.031032
BSD-3-Clause
true
e9ac9e80dcaba2bb63c79822ab9c0c7a
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\__pycache__\test_datetimes.cpython-313.pyc
test_datetimes.cpython-313.pyc
Other
46,604
0.95
0.002494
0
python-kit
195
2023-12-20T19:06:36.864568
GPL-3.0
true
636baf805b5b481d10b8a769b232b646
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\__pycache__\test_ndarray_backed.cpython-313.pyc
test_ndarray_backed.cpython-313.pyc
Other
4,035
0.8
0.038462
0
react-lib
275
2024-07-14T18:09:12.200235
Apache-2.0
true
b0f275f1c8b5499c651cabe00b882e0a
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\__pycache__\test_period.cpython-313.pyc
test_period.cpython-313.pyc
Other
9,241
0.8
0
0.006803
react-lib
526
2024-04-25T11:15:48.584348
BSD-3-Clause
true
0445cfdcb2aea5d5deaa68012a7022e3
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\__pycache__\test_timedeltas.cpython-313.pyc
test_timedeltas.cpython-313.pyc
Other
19,099
0.95
0
0
awesome-app
944
2024-08-28T22:35:20.282770
BSD-3-Clause
true
d2a3cfded11c237bd92a0a9bd977a808
\n\n
.venv\Lib\site-packages\pandas\tests\arrays\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
194
0.7
0
0
react-lib
417
2024-05-22T22:08:54.799878
Apache-2.0
true
9e3a3fe711d61b981f1f5fd8c583a5e3
from typing import Any\n\nfrom pandas import Index\n\n\ndef allow_na_ops(obj: Any) -> bool:\n """Whether to skip test cases including NaN"""\n is_bool_index = isinstance(obj, Index) and obj.inferred_type == "boolean"\n return not is_bool_index and obj._can_hold_na\n
.venv\Lib\site-packages\pandas\tests\base\common.py
common.py
Python
266
0.85
0.111111
0
node-utils
421
2023-12-07T12:51:41.386468
BSD-3-Clause
true
715719fbd95cea38cd4007ff34475070
from datetime import datetime\nimport sys\n\nimport numpy as np\nimport pytest\n\nfrom pandas.compat import PYPY\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n Index,\n Series,\n)\nimport pandas._testing as tm\nfrom pandas.core.accessor import PandasDelegate\nfrom pandas.core.base import (\n NoNewAttributesMixin,\n PandasObject,\n)\n\n\ndef series_via_frame_from_dict(x, **kwargs):\n return DataFrame({"a": x}, **kwargs)["a"]\n\n\ndef series_via_frame_from_scalar(x, **kwargs):\n return DataFrame(x, **kwargs)[0]\n\n\n@pytest.fixture(\n params=[\n Series,\n series_via_frame_from_dict,\n series_via_frame_from_scalar,\n Index,\n ],\n ids=["Series", "DataFrame-dict", "DataFrame-array", "Index"],\n)\ndef constructor(request):\n return request.param\n\n\nclass TestPandasDelegate:\n class Delegator:\n _properties = ["prop"]\n _methods = ["test_method"]\n\n def _set_prop(self, value):\n self.prop = value\n\n def _get_prop(self):\n return self.prop\n\n prop = property(_get_prop, _set_prop, doc="foo property")\n\n def test_method(self, *args, **kwargs):\n """a test method"""\n\n class Delegate(PandasDelegate, PandasObject):\n def __init__(self, obj) -> None:\n self.obj = obj\n\n def test_invalid_delegation(self):\n # these show that in order for the delegation to work\n # the _delegate_* methods need to be overridden to not raise\n # a TypeError\n\n self.Delegate._add_delegate_accessors(\n delegate=self.Delegator,\n accessors=self.Delegator._properties,\n typ="property",\n )\n self.Delegate._add_delegate_accessors(\n delegate=self.Delegator, accessors=self.Delegator._methods, typ="method"\n )\n\n delegate = self.Delegate(self.Delegator())\n\n msg = "You cannot access the property prop"\n with pytest.raises(TypeError, match=msg):\n delegate.prop\n\n msg = "The property prop cannot be set"\n with pytest.raises(TypeError, match=msg):\n delegate.prop = 5\n\n msg = "You cannot access the property prop"\n with pytest.raises(TypeError, match=msg):\n delegate.prop\n\n @pytest.mark.skipif(PYPY, reason="not relevant for PyPy")\n def test_memory_usage(self):\n # Delegate does not implement memory_usage.\n # Check that we fall back to in-built `__sizeof__`\n # GH 12924\n delegate = self.Delegate(self.Delegator())\n sys.getsizeof(delegate)\n\n\nclass TestNoNewAttributesMixin:\n def test_mixin(self):\n class T(NoNewAttributesMixin):\n pass\n\n t = T()\n assert not hasattr(t, "__frozen")\n\n t.a = "test"\n assert t.a == "test"\n\n t._freeze()\n assert "__frozen" in dir(t)\n assert getattr(t, "__frozen")\n msg = "You cannot add any new attribute"\n with pytest.raises(AttributeError, match=msg):\n t.b = "test"\n\n assert not hasattr(t, "b")\n\n\nclass TestConstruction:\n # test certain constructor behaviours on dtype inference across Series,\n # Index and DataFrame\n\n @pytest.mark.parametrize(\n "a",\n [\n np.array(["2263-01-01"], dtype="datetime64[D]"),\n np.array([datetime(2263, 1, 1)], dtype=object),\n np.array([np.datetime64("2263-01-01", "D")], dtype=object),\n np.array(["2263-01-01"], dtype=object),\n ],\n ids=[\n "datetime64[D]",\n "object-datetime.datetime",\n "object-numpy-scalar",\n "object-string",\n ],\n )\n def test_constructor_datetime_outofbound(\n self, a, constructor, request, using_infer_string\n ):\n # GH-26853 (+ bug GH-26206 out of bound non-ns unit)\n\n # No dtype specified (dtype inference)\n # datetime64[non-ns] raise error, other cases result in object dtype\n # and preserve original data\n if a.dtype.kind == "M":\n # Can't fit in nanosecond bounds -> get the nearest supported unit\n result = constructor(a)\n assert result.dtype == "M8[s]"\n else:\n result = constructor(a)\n if using_infer_string and "object-string" in request.node.callspec.id:\n assert result.dtype == "string"\n else:\n assert result.dtype == "object"\n tm.assert_numpy_array_equal(result.to_numpy(), a)\n\n # Explicit dtype specified\n # Forced conversion fails for all -> all cases raise error\n msg = "Out of bounds|Out of bounds .* present at position 0"\n with pytest.raises(pd.errors.OutOfBoundsDatetime, match=msg):\n constructor(a, dtype="datetime64[ns]")\n\n def test_constructor_datetime_nonns(self, constructor):\n arr = np.array(["2020-01-01T00:00:00.000000"], dtype="datetime64[us]")\n dta = pd.core.arrays.DatetimeArray._simple_new(arr, dtype=arr.dtype)\n expected = constructor(dta)\n assert expected.dtype == arr.dtype\n\n result = constructor(arr)\n tm.assert_equal(result, expected)\n\n # https://github.com/pandas-dev/pandas/issues/34843\n arr.flags.writeable = False\n result = constructor(arr)\n tm.assert_equal(result, expected)\n\n def test_constructor_from_dict_keys(self, constructor, using_infer_string):\n # https://github.com/pandas-dev/pandas/issues/60343\n d = {"a": 1, "b": 2}\n result = constructor(d.keys(), dtype="str")\n if using_infer_string:\n assert result.dtype == "str"\n else:\n assert result.dtype == "object"\n expected = constructor(list(d.keys()), dtype="str")\n tm.assert_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\base\test_constructors.py
test_constructors.py
Python
5,763
0.95
0.131579
0.111842
vue-tools
21
2024-11-24T02:33:58.399945
GPL-3.0
true
54e1a3aa0a8e68fda6b033243f532ed3
import numpy as np\nimport pytest\n\nfrom pandas.compat import HAS_PYARROW\nfrom pandas.compat.numpy import np_version_gt2\n\nfrom pandas.core.dtypes.dtypes import DatetimeTZDtype\n\nimport pandas as pd\nfrom pandas import (\n CategoricalIndex,\n Series,\n Timedelta,\n Timestamp,\n date_range,\n)\nimport pandas._testing as tm\nfrom pandas.core.arrays import (\n DatetimeArray,\n IntervalArray,\n NumpyExtensionArray,\n PeriodArray,\n SparseArray,\n TimedeltaArray,\n)\nfrom pandas.core.arrays.string_ import StringArrayNumpySemantics\nfrom pandas.core.arrays.string_arrow import ArrowStringArrayNumpySemantics\n\n\nclass TestToIterable:\n # test that we convert an iterable to python types\n\n dtypes = [\n ("int8", int),\n ("int16", int),\n ("int32", int),\n ("int64", int),\n ("uint8", int),\n ("uint16", int),\n ("uint32", int),\n ("uint64", int),\n ("float16", float),\n ("float32", float),\n ("float64", float),\n ("datetime64[ns]", Timestamp),\n ("datetime64[ns, US/Eastern]", Timestamp),\n ("timedelta64[ns]", Timedelta),\n ]\n\n @pytest.mark.parametrize("dtype, rdtype", dtypes)\n @pytest.mark.parametrize(\n "method",\n [\n lambda x: x.tolist(),\n lambda x: x.to_list(),\n lambda x: list(x),\n lambda x: list(x.__iter__()),\n ],\n ids=["tolist", "to_list", "list", "iter"],\n )\n def test_iterable(self, index_or_series, method, dtype, rdtype):\n # gh-10904\n # gh-13258\n # coerce iteration to underlying python / pandas types\n typ = index_or_series\n if dtype == "float16" and issubclass(typ, pd.Index):\n with pytest.raises(NotImplementedError, match="float16 indexes are not "):\n typ([1], dtype=dtype)\n return\n s = typ([1], dtype=dtype)\n result = method(s)[0]\n assert isinstance(result, rdtype)\n\n @pytest.mark.parametrize(\n "dtype, rdtype, obj",\n [\n ("object", object, "a"),\n ("object", int, 1),\n ("category", object, "a"),\n ("category", int, 1),\n ],\n )\n @pytest.mark.parametrize(\n "method",\n [\n lambda x: x.tolist(),\n lambda x: x.to_list(),\n lambda x: list(x),\n lambda x: list(x.__iter__()),\n ],\n ids=["tolist", "to_list", "list", "iter"],\n )\n def test_iterable_object_and_category(\n self, index_or_series, method, dtype, rdtype, obj\n ):\n # gh-10904\n # gh-13258\n # coerce iteration to underlying python / pandas types\n typ = index_or_series\n s = typ([obj], dtype=dtype)\n result = method(s)[0]\n assert isinstance(result, rdtype)\n\n @pytest.mark.parametrize("dtype, rdtype", dtypes)\n def test_iterable_items(self, dtype, rdtype):\n # gh-13258\n # test if items yields the correct boxed scalars\n # this only applies to series\n s = Series([1], dtype=dtype)\n _, result = next(iter(s.items()))\n assert isinstance(result, rdtype)\n\n _, result = next(iter(s.items()))\n assert isinstance(result, rdtype)\n\n @pytest.mark.parametrize(\n "dtype, rdtype", dtypes + [("object", int), ("category", int)]\n )\n def test_iterable_map(self, index_or_series, dtype, rdtype):\n # gh-13236\n # coerce iteration to underlying python / pandas types\n typ = index_or_series\n if dtype == "float16" and issubclass(typ, pd.Index):\n with pytest.raises(NotImplementedError, match="float16 indexes are not "):\n typ([1], dtype=dtype)\n return\n s = typ([1], dtype=dtype)\n result = s.map(type)[0]\n if not isinstance(rdtype, tuple):\n rdtype = (rdtype,)\n assert result in rdtype\n\n @pytest.mark.parametrize(\n "method",\n [\n lambda x: x.tolist(),\n lambda x: x.to_list(),\n lambda x: list(x),\n lambda x: list(x.__iter__()),\n ],\n ids=["tolist", "to_list", "list", "iter"],\n )\n def test_categorial_datetimelike(self, method):\n i = CategoricalIndex([Timestamp("1999-12-31"), Timestamp("2000-12-31")])\n\n result = method(i)[0]\n assert isinstance(result, Timestamp)\n\n def test_iter_box_dt64(self, unit):\n vals = [Timestamp("2011-01-01"), Timestamp("2011-01-02")]\n ser = Series(vals).dt.as_unit(unit)\n assert ser.dtype == f"datetime64[{unit}]"\n for res, exp in zip(ser, vals):\n assert isinstance(res, Timestamp)\n assert res.tz is None\n assert res == exp\n assert res.unit == unit\n\n def test_iter_box_dt64tz(self, unit):\n vals = [\n Timestamp("2011-01-01", tz="US/Eastern"),\n Timestamp("2011-01-02", tz="US/Eastern"),\n ]\n ser = Series(vals).dt.as_unit(unit)\n\n assert ser.dtype == f"datetime64[{unit}, US/Eastern]"\n for res, exp in zip(ser, vals):\n assert isinstance(res, Timestamp)\n assert res.tz == exp.tz\n assert res == exp\n assert res.unit == unit\n\n def test_iter_box_timedelta64(self, unit):\n # timedelta\n vals = [Timedelta("1 days"), Timedelta("2 days")]\n ser = Series(vals).dt.as_unit(unit)\n assert ser.dtype == f"timedelta64[{unit}]"\n for res, exp in zip(ser, vals):\n assert isinstance(res, Timedelta)\n assert res == exp\n assert res.unit == unit\n\n def test_iter_box_period(self):\n # period\n vals = [pd.Period("2011-01-01", freq="M"), pd.Period("2011-01-02", freq="M")]\n s = Series(vals)\n assert s.dtype == "Period[M]"\n for res, exp in zip(s, vals):\n assert isinstance(res, pd.Period)\n assert res.freq == "ME"\n assert res == exp\n\n\n@pytest.mark.parametrize(\n "arr, expected_type, dtype",\n [\n (np.array([0, 1], dtype=np.int64), np.ndarray, "int64"),\n (np.array(["a", "b"]), np.ndarray, "object"),\n (pd.Categorical(["a", "b"]), pd.Categorical, "category"),\n (\n pd.DatetimeIndex(["2017", "2018"], tz="US/Central"),\n DatetimeArray,\n "datetime64[ns, US/Central]",\n ),\n (\n pd.PeriodIndex([2018, 2019], freq="Y"),\n PeriodArray,\n pd.core.dtypes.dtypes.PeriodDtype("Y-DEC"),\n ),\n (pd.IntervalIndex.from_breaks([0, 1, 2]), IntervalArray, "interval"),\n (\n pd.DatetimeIndex(["2017", "2018"]),\n DatetimeArray,\n "datetime64[ns]",\n ),\n (\n pd.TimedeltaIndex([10**10]),\n TimedeltaArray,\n "m8[ns]",\n ),\n ],\n)\ndef test_values_consistent(arr, expected_type, dtype, using_infer_string):\n if using_infer_string and dtype == "object":\n expected_type = (\n ArrowStringArrayNumpySemantics if HAS_PYARROW else StringArrayNumpySemantics\n )\n l_values = Series(arr)._values\n r_values = pd.Index(arr)._values\n assert type(l_values) is expected_type\n assert type(l_values) is type(r_values)\n\n tm.assert_equal(l_values, r_values)\n\n\n@pytest.mark.parametrize("arr", [np.array([1, 2, 3])])\ndef test_numpy_array(arr):\n ser = Series(arr)\n result = ser.array\n expected = NumpyExtensionArray(arr)\n tm.assert_extension_array_equal(result, expected)\n\n\ndef test_numpy_array_all_dtypes(any_numpy_dtype):\n ser = Series(dtype=any_numpy_dtype)\n result = ser.array\n if np.dtype(any_numpy_dtype).kind == "M":\n assert isinstance(result, DatetimeArray)\n elif np.dtype(any_numpy_dtype).kind == "m":\n assert isinstance(result, TimedeltaArray)\n else:\n assert isinstance(result, NumpyExtensionArray)\n\n\n@pytest.mark.parametrize(\n "arr, attr",\n [\n (pd.Categorical(["a", "b"]), "_codes"),\n (PeriodArray._from_sequence(["2000", "2001"], dtype="period[D]"), "_ndarray"),\n (pd.array([0, np.nan], dtype="Int64"), "_data"),\n (IntervalArray.from_breaks([0, 1]), "_left"),\n (SparseArray([0, 1]), "_sparse_values"),\n (\n DatetimeArray._from_sequence(np.array([1, 2], dtype="datetime64[ns]")),\n "_ndarray",\n ),\n # tz-aware Datetime\n (\n DatetimeArray._from_sequence(\n np.array(\n ["2000-01-01T12:00:00", "2000-01-02T12:00:00"], dtype="M8[ns]"\n ),\n dtype=DatetimeTZDtype(tz="US/Central"),\n ),\n "_ndarray",\n ),\n ],\n)\ndef test_array(arr, attr, index_or_series, request):\n box = index_or_series\n\n result = box(arr, copy=False).array\n\n if attr:\n arr = getattr(arr, attr)\n result = getattr(result, attr)\n\n assert result is arr\n\n\ndef test_array_multiindex_raises():\n idx = pd.MultiIndex.from_product([["A"], ["a", "b"]])\n msg = "MultiIndex has no single backing array"\n with pytest.raises(ValueError, match=msg):\n idx.array\n\n\n@pytest.mark.parametrize(\n "arr, expected, zero_copy",\n [\n (np.array([1, 2], dtype=np.int64), np.array([1, 2], dtype=np.int64), True),\n (pd.Categorical(["a", "b"]), np.array(["a", "b"], dtype=object), False),\n (\n pd.core.arrays.period_array(["2000", "2001"], freq="D"),\n np.array([pd.Period("2000", freq="D"), pd.Period("2001", freq="D")]),\n False,\n ),\n (pd.array([0, np.nan], dtype="Int64"), np.array([0, np.nan]), False),\n (\n IntervalArray.from_breaks([0, 1, 2]),\n np.array([pd.Interval(0, 1), pd.Interval(1, 2)], dtype=object),\n False,\n ),\n (SparseArray([0, 1]), np.array([0, 1], dtype=np.int64), False),\n # tz-naive datetime\n (\n DatetimeArray._from_sequence(np.array(["2000", "2001"], dtype="M8[ns]")),\n np.array(["2000", "2001"], dtype="M8[ns]"),\n True,\n ),\n # tz-aware stays tz`-aware\n (\n DatetimeArray._from_sequence(\n np.array(["2000-01-01T06:00:00", "2000-01-02T06:00:00"], dtype="M8[ns]")\n )\n .tz_localize("UTC")\n .tz_convert("US/Central"),\n np.array(\n [\n Timestamp("2000-01-01", tz="US/Central"),\n Timestamp("2000-01-02", tz="US/Central"),\n ]\n ),\n False,\n ),\n # Timedelta\n (\n TimedeltaArray._from_sequence(\n np.array([0, 3600000000000], dtype="i8").view("m8[ns]")\n ),\n np.array([0, 3600000000000], dtype="m8[ns]"),\n True,\n ),\n # GH#26406 tz is preserved in Categorical[dt64tz]\n (\n pd.Categorical(date_range("2016-01-01", periods=2, tz="US/Pacific")),\n np.array(\n [\n Timestamp("2016-01-01", tz="US/Pacific"),\n Timestamp("2016-01-02", tz="US/Pacific"),\n ]\n ),\n False,\n ),\n ],\n)\ndef test_to_numpy(arr, expected, zero_copy, index_or_series_or_array):\n box = index_or_series_or_array\n\n with tm.assert_produces_warning(None):\n thing = box(arr)\n\n result = thing.to_numpy()\n tm.assert_numpy_array_equal(result, expected)\n\n result = np.asarray(thing)\n tm.assert_numpy_array_equal(result, expected)\n\n # Additionally, we check the `copy=` semantics for array/asarray\n # (these are implemented by us via `__array__`).\n result_cp1 = np.array(thing, copy=True)\n result_cp2 = np.array(thing, copy=True)\n # When called with `copy=True` NumPy/we should ensure a copy was made\n assert not np.may_share_memory(result_cp1, result_cp2)\n\n if not np_version_gt2:\n # copy=False semantics are only supported in NumPy>=2.\n return\n\n if not zero_copy:\n msg = "Starting with NumPy 2.0, the behavior of the 'copy' keyword has changed"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n np.array(thing, copy=False)\n\n else:\n result_nocopy1 = np.array(thing, copy=False)\n result_nocopy2 = np.array(thing, copy=False)\n # If copy=False was given, these must share the same data\n assert np.may_share_memory(result_nocopy1, result_nocopy2)\n\n\n@pytest.mark.parametrize("as_series", [True, False])\n@pytest.mark.parametrize(\n "arr", [np.array([1, 2, 3], dtype="int64"), np.array(["a", "b", "c"], dtype=object)]\n)\ndef test_to_numpy_copy(arr, as_series, using_infer_string):\n obj = pd.Index(arr, copy=False)\n if as_series:\n obj = Series(obj.values, copy=False)\n\n # no copy by default\n result = obj.to_numpy()\n if using_infer_string and arr.dtype == object and obj.dtype.storage == "pyarrow":\n assert np.shares_memory(arr, result) is False\n else:\n assert np.shares_memory(arr, result) is True\n\n result = obj.to_numpy(copy=False)\n if using_infer_string and arr.dtype == object and obj.dtype.storage == "pyarrow":\n assert np.shares_memory(arr, result) is False\n else:\n assert np.shares_memory(arr, result) is True\n\n # copy=True\n result = obj.to_numpy(copy=True)\n assert np.shares_memory(arr, result) is False\n\n\n@pytest.mark.parametrize("as_series", [True, False])\ndef test_to_numpy_dtype(as_series, unit):\n tz = "US/Eastern"\n obj = pd.DatetimeIndex(["2000", "2001"], tz=tz)\n if as_series:\n obj = Series(obj)\n\n # preserve tz by default\n result = obj.to_numpy()\n expected = np.array(\n [Timestamp("2000", tz=tz), Timestamp("2001", tz=tz)], dtype=object\n )\n tm.assert_numpy_array_equal(result, expected)\n\n result = obj.to_numpy(dtype="object")\n tm.assert_numpy_array_equal(result, expected)\n\n result = obj.to_numpy(dtype="M8[ns]")\n expected = np.array(["2000-01-01T05", "2001-01-01T05"], dtype="M8[ns]")\n tm.assert_numpy_array_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "values, dtype, na_value, expected",\n [\n ([1, 2, None], "float64", 0, [1.0, 2.0, 0.0]),\n (\n [Timestamp("2000"), Timestamp("2000"), pd.NaT],\n None,\n Timestamp("2000"),\n [np.datetime64("2000-01-01T00:00:00.000000000")] * 3,\n ),\n ],\n)\ndef test_to_numpy_na_value_numpy_dtype(\n index_or_series, values, dtype, na_value, expected\n):\n obj = index_or_series(values)\n result = obj.to_numpy(dtype=dtype, na_value=na_value)\n expected = np.array(expected)\n tm.assert_numpy_array_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "data, multiindex, dtype, na_value, expected",\n [\n (\n [1, 2, None, 4],\n [(0, "a"), (0, "b"), (1, "b"), (1, "c")],\n float,\n None,\n [1.0, 2.0, np.nan, 4.0],\n ),\n (\n [1, 2, None, 4],\n [(0, "a"), (0, "b"), (1, "b"), (1, "c")],\n float,\n np.nan,\n [1.0, 2.0, np.nan, 4.0],\n ),\n (\n [1.0, 2.0, np.nan, 4.0],\n [("a", 0), ("a", 1), ("a", 2), ("b", 0)],\n int,\n 0,\n [1, 2, 0, 4],\n ),\n (\n [Timestamp("2000"), Timestamp("2000"), pd.NaT],\n [(0, Timestamp("2021")), (0, Timestamp("2022")), (1, Timestamp("2000"))],\n None,\n Timestamp("2000"),\n [np.datetime64("2000-01-01T00:00:00.000000000")] * 3,\n ),\n ],\n)\ndef test_to_numpy_multiindex_series_na_value(\n data, multiindex, dtype, na_value, expected\n):\n index = pd.MultiIndex.from_tuples(multiindex)\n series = Series(data, index=index)\n result = series.to_numpy(dtype=dtype, na_value=na_value)\n expected = np.array(expected)\n tm.assert_numpy_array_equal(result, expected)\n\n\ndef test_to_numpy_kwargs_raises():\n # numpy\n s = Series([1, 2, 3])\n msg = r"to_numpy\(\) got an unexpected keyword argument 'foo'"\n with pytest.raises(TypeError, match=msg):\n s.to_numpy(foo=True)\n\n # extension\n s = Series([1, 2, 3], dtype="Int64")\n with pytest.raises(TypeError, match=msg):\n s.to_numpy(foo=True)\n\n\n@pytest.mark.parametrize(\n "data",\n [\n {"a": [1, 2, 3], "b": [1, 2, None]},\n {"a": np.array([1, 2, 3]), "b": np.array([1, 2, np.nan])},\n {"a": pd.array([1, 2, 3]), "b": pd.array([1, 2, None])},\n ],\n)\n@pytest.mark.parametrize("dtype, na_value", [(float, np.nan), (object, None)])\ndef test_to_numpy_dataframe_na_value(data, dtype, na_value):\n # https://github.com/pandas-dev/pandas/issues/33820\n df = pd.DataFrame(data)\n result = df.to_numpy(dtype=dtype, na_value=na_value)\n expected = np.array([[1, 1], [2, 2], [3, na_value]], dtype=dtype)\n tm.assert_numpy_array_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "data, expected",\n [\n (\n {"a": pd.array([1, 2, None])},\n np.array([[1.0], [2.0], [np.nan]], dtype=float),\n ),\n (\n {"a": [1, 2, 3], "b": [1, 2, 3]},\n np.array([[1, 1], [2, 2], [3, 3]], dtype=float),\n ),\n ],\n)\ndef test_to_numpy_dataframe_single_block(data, expected):\n # https://github.com/pandas-dev/pandas/issues/33820\n df = pd.DataFrame(data)\n result = df.to_numpy(dtype=float, na_value=np.nan)\n tm.assert_numpy_array_equal(result, expected)\n\n\ndef test_to_numpy_dataframe_single_block_no_mutate():\n # https://github.com/pandas-dev/pandas/issues/33820\n result = pd.DataFrame(np.array([1.0, 2.0, np.nan]))\n expected = pd.DataFrame(np.array([1.0, 2.0, np.nan]))\n result.to_numpy(na_value=0.0)\n tm.assert_frame_equal(result, expected)\n\n\nclass TestAsArray:\n @pytest.mark.parametrize("tz", [None, "US/Central"])\n def test_asarray_object_dt64(self, tz):\n ser = Series(date_range("2000", periods=2, tz=tz))\n\n with tm.assert_produces_warning(None):\n # Future behavior (for tzaware case) with no warning\n result = np.asarray(ser, dtype=object)\n\n expected = np.array(\n [Timestamp("2000-01-01", tz=tz), Timestamp("2000-01-02", tz=tz)]\n )\n tm.assert_numpy_array_equal(result, expected)\n\n def test_asarray_tz_naive(self):\n # This shouldn't produce a warning.\n ser = Series(date_range("2000", periods=2))\n expected = np.array(["2000-01-01", "2000-01-02"], dtype="M8[ns]")\n result = np.asarray(ser)\n\n tm.assert_numpy_array_equal(result, expected)\n\n def test_asarray_tz_aware(self):\n tz = "US/Central"\n ser = Series(date_range("2000", periods=2, tz=tz))\n expected = np.array(["2000-01-01T06", "2000-01-02T06"], dtype="M8[ns]")\n result = np.asarray(ser, dtype="datetime64[ns]")\n\n tm.assert_numpy_array_equal(result, expected)\n\n # Old behavior with no warning\n result = np.asarray(ser, dtype="M8[ns]")\n\n tm.assert_numpy_array_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\base\test_conversion.py
test_conversion.py
Python
19,046
0.95
0.080537
0.06705
awesome-app
605
2024-11-01T11:16:26.068674
MIT
true
bf22ec8025fa164f3369e82054db104d
"""\nThough Index.fillna and Series.fillna has separate impl,\ntest here to confirm these works as the same\n"""\n\nimport numpy as np\nimport pytest\n\nfrom pandas import MultiIndex\nimport pandas._testing as tm\nfrom pandas.tests.base.common import allow_na_ops\n\n\ndef test_fillna(index_or_series_obj):\n # GH 11343\n obj = index_or_series_obj\n\n if isinstance(obj, MultiIndex):\n msg = "isna is not defined for MultiIndex"\n with pytest.raises(NotImplementedError, match=msg):\n obj.fillna(0)\n return\n\n # values will not be changed\n fill_value = obj.values[0] if len(obj) > 0 else 0\n result = obj.fillna(fill_value)\n\n tm.assert_equal(obj, result)\n\n # check shallow_copied\n assert obj is not result\n\n\n@pytest.mark.parametrize("null_obj", [np.nan, None])\ndef test_fillna_null(null_obj, index_or_series_obj):\n # GH 11343\n obj = index_or_series_obj\n klass = type(obj)\n\n if not allow_na_ops(obj):\n pytest.skip(f"{klass} doesn't allow for NA operations")\n elif len(obj) < 1:\n pytest.skip("Test doesn't make sense on empty data")\n elif isinstance(obj, MultiIndex):\n pytest.skip(f"MultiIndex can't hold '{null_obj}'")\n\n values = obj._values\n fill_value = values[0]\n expected = values.copy()\n values[0:2] = null_obj\n expected[0:2] = fill_value\n\n expected = klass(expected)\n obj = klass(values)\n\n result = obj.fillna(fill_value)\n tm.assert_equal(result, expected)\n\n # check shallow_copied\n assert obj is not result\n
.venv\Lib\site-packages\pandas\tests\base\test_fillna.py
test_fillna.py
Python
1,522
0.95
0.116667
0.111111
node-utils
849
2024-09-08T16:51:48.545352
Apache-2.0
true
7d326b99e1be6de802c8f30bda34f591
import sys\n\nimport numpy as np\nimport pytest\n\nfrom pandas._config import using_string_dtype\n\nfrom pandas.compat import PYPY\n\nfrom pandas.core.dtypes.common import (\n is_dtype_equal,\n is_object_dtype,\n)\n\nimport pandas as pd\nfrom pandas import (\n Index,\n Series,\n)\nimport pandas._testing as tm\n\n\ndef test_isnull_notnull_docstrings():\n # GH#41855 make sure its clear these are aliases\n doc = pd.DataFrame.notnull.__doc__\n assert doc.startswith("\nDataFrame.notnull is an alias for DataFrame.notna.\n")\n doc = pd.DataFrame.isnull.__doc__\n assert doc.startswith("\nDataFrame.isnull is an alias for DataFrame.isna.\n")\n\n doc = Series.notnull.__doc__\n assert doc.startswith("\nSeries.notnull is an alias for Series.notna.\n")\n doc = Series.isnull.__doc__\n assert doc.startswith("\nSeries.isnull is an alias for Series.isna.\n")\n\n\n@pytest.mark.parametrize(\n "op_name, op",\n [\n ("add", "+"),\n ("sub", "-"),\n ("mul", "*"),\n ("mod", "%"),\n ("pow", "**"),\n ("truediv", "/"),\n ("floordiv", "//"),\n ],\n)\ndef test_binary_ops_docstring(frame_or_series, op_name, op):\n # not using the all_arithmetic_functions fixture with _get_opstr\n # as _get_opstr is used internally in the dynamic implementation of the docstring\n klass = frame_or_series\n\n operand1 = klass.__name__.lower()\n operand2 = "other"\n expected_str = " ".join([operand1, op, operand2])\n assert expected_str in getattr(klass, op_name).__doc__\n\n # reverse version of the binary ops\n expected_str = " ".join([operand2, op, operand1])\n assert expected_str in getattr(klass, "r" + op_name).__doc__\n\n\ndef test_ndarray_compat_properties(index_or_series_obj):\n obj = index_or_series_obj\n\n # Check that we work.\n for p in ["shape", "dtype", "T", "nbytes"]:\n assert getattr(obj, p, None) is not None\n\n # deprecated properties\n for p in ["strides", "itemsize", "base", "data"]:\n assert not hasattr(obj, p)\n\n msg = "can only convert an array of size 1 to a Python scalar"\n with pytest.raises(ValueError, match=msg):\n obj.item() # len > 1\n\n assert obj.ndim == 1\n assert obj.size == len(obj)\n\n assert Index([1]).item() == 1\n assert Series([1]).item() == 1\n\n\n@pytest.mark.skipif(\n PYPY or using_string_dtype(),\n reason="not relevant for PyPy doesn't work properly for arrow strings",\n)\ndef test_memory_usage(index_or_series_memory_obj):\n obj = index_or_series_memory_obj\n # Clear index caches so that len(obj) == 0 report 0 memory usage\n if isinstance(obj, Series):\n is_ser = True\n obj.index._engine.clear_mapping()\n else:\n is_ser = False\n obj._engine.clear_mapping()\n\n res = obj.memory_usage()\n res_deep = obj.memory_usage(deep=True)\n\n is_object = is_object_dtype(obj) or (is_ser and is_object_dtype(obj.index))\n is_categorical = isinstance(obj.dtype, pd.CategoricalDtype) or (\n is_ser and isinstance(obj.index.dtype, pd.CategoricalDtype)\n )\n is_object_string = is_dtype_equal(obj, "string[python]") or (\n is_ser and is_dtype_equal(obj.index.dtype, "string[python]")\n )\n\n if len(obj) == 0:\n expected = 0\n assert res_deep == res == expected\n elif is_object or is_categorical or is_object_string:\n # only deep will pick them up\n assert res_deep > res\n else:\n assert res == res_deep\n\n # sys.getsizeof will call the .memory_usage with\n # deep=True, and add on some GC overhead\n diff = res_deep - sys.getsizeof(obj)\n assert abs(diff) < 100\n\n\ndef test_memory_usage_components_series(series_with_simple_index):\n series = series_with_simple_index\n total_usage = series.memory_usage(index=True)\n non_index_usage = series.memory_usage(index=False)\n index_usage = series.index.memory_usage()\n assert total_usage == non_index_usage + index_usage\n\n\n@pytest.mark.parametrize("dtype", tm.NARROW_NP_DTYPES)\ndef test_memory_usage_components_narrow_series(dtype):\n series = Series(range(5), dtype=dtype, index=[f"i-{i}" for i in range(5)], name="a")\n total_usage = series.memory_usage(index=True)\n non_index_usage = series.memory_usage(index=False)\n index_usage = series.index.memory_usage()\n assert total_usage == non_index_usage + index_usage\n\n\ndef test_searchsorted(request, index_or_series_obj):\n # numpy.searchsorted calls obj.searchsorted under the hood.\n # See gh-12238\n obj = index_or_series_obj\n\n if isinstance(obj, pd.MultiIndex):\n # See gh-14833\n request.applymarker(\n pytest.mark.xfail(\n reason="np.searchsorted doesn't work on pd.MultiIndex: GH 14833"\n )\n )\n elif obj.dtype.kind == "c" and isinstance(obj, Index):\n # TODO: Should Series cases also raise? Looks like they use numpy\n # comparison semantics https://github.com/numpy/numpy/issues/15981\n mark = pytest.mark.xfail(reason="complex objects are not comparable")\n request.applymarker(mark)\n\n max_obj = max(obj, default=0)\n index = np.searchsorted(obj, max_obj)\n assert 0 <= index <= len(obj)\n\n index = np.searchsorted(obj, max_obj, sorter=range(len(obj)))\n assert 0 <= index <= len(obj)\n\n\n@pytest.mark.filterwarnings(r"ignore:Dtype inference:FutureWarning")\ndef test_access_by_position(index_flat):\n index = index_flat\n\n if len(index) == 0:\n pytest.skip("Test doesn't make sense on empty data")\n\n series = Series(index)\n assert index[0] == series.iloc[0]\n assert index[5] == series.iloc[5]\n assert index[-1] == series.iloc[-1]\n\n size = len(index)\n assert index[-1] == index[size - 1]\n\n msg = f"index {size} is out of bounds for axis 0 with size {size}"\n if isinstance(index.dtype, pd.StringDtype) and index.dtype.storage == "pyarrow":\n msg = "index out of bounds"\n with pytest.raises(IndexError, match=msg):\n index[size]\n msg = "single positional indexer is out-of-bounds"\n with pytest.raises(IndexError, match=msg):\n series.iloc[size]\n
.venv\Lib\site-packages\pandas\tests\base\test_misc.py
test_misc.py
Python
6,053
0.95
0.121053
0.1
react-lib
230
2024-09-10T21:34:10.254636
Apache-2.0
true
09e744aa1d02253e6cd01f91ad67e967
import numpy as np\nimport pytest\n\nfrom pandas import (\n CategoricalDtype,\n DataFrame,\n)\nimport pandas._testing as tm\n\n\ndef test_transpose(index_or_series_obj):\n obj = index_or_series_obj\n tm.assert_equal(obj.transpose(), obj)\n\n\ndef test_transpose_non_default_axes(index_or_series_obj):\n msg = "the 'axes' parameter is not supported"\n obj = index_or_series_obj\n with pytest.raises(ValueError, match=msg):\n obj.transpose(1)\n with pytest.raises(ValueError, match=msg):\n obj.transpose(axes=1)\n\n\ndef test_numpy_transpose(index_or_series_obj):\n msg = "the 'axes' parameter is not supported"\n obj = index_or_series_obj\n tm.assert_equal(np.transpose(obj), obj)\n\n with pytest.raises(ValueError, match=msg):\n np.transpose(obj, axes=1)\n\n\n@pytest.mark.parametrize(\n "data, transposed_data, index, columns, dtype",\n [\n ([[1], [2]], [[1, 2]], ["a", "a"], ["b"], int),\n ([[1], [2]], [[1, 2]], ["a", "a"], ["b"], CategoricalDtype([1, 2])),\n ([[1, 2]], [[1], [2]], ["b"], ["a", "a"], int),\n ([[1, 2]], [[1], [2]], ["b"], ["a", "a"], CategoricalDtype([1, 2])),\n ([[1, 2], [3, 4]], [[1, 3], [2, 4]], ["a", "a"], ["b", "b"], int),\n (\n [[1, 2], [3, 4]],\n [[1, 3], [2, 4]],\n ["a", "a"],\n ["b", "b"],\n CategoricalDtype([1, 2, 3, 4]),\n ),\n ],\n)\ndef test_duplicate_labels(data, transposed_data, index, columns, dtype):\n # GH 42380\n df = DataFrame(data, index=index, columns=columns, dtype=dtype)\n result = df.T\n expected = DataFrame(transposed_data, index=columns, columns=index, dtype=dtype)\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\base\test_transpose.py
test_transpose.py
Python
1,694
0.95
0.071429
0.021739
python-kit
292
2024-12-29T13:37:53.048271
Apache-2.0
true
38c64294ad8b6ef582bd4e460651eca7
import numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.tests.base.common import allow_na_ops\n\n\n@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")\ndef test_unique(index_or_series_obj):\n obj = index_or_series_obj\n obj = np.repeat(obj, range(1, len(obj) + 1))\n result = obj.unique()\n\n # dict.fromkeys preserves the order\n unique_values = list(dict.fromkeys(obj.values))\n if isinstance(obj, pd.MultiIndex):\n expected = pd.MultiIndex.from_tuples(unique_values)\n expected.names = obj.names\n tm.assert_index_equal(result, expected, exact=True)\n elif isinstance(obj, pd.Index):\n expected = pd.Index(unique_values, dtype=obj.dtype)\n if isinstance(obj.dtype, pd.DatetimeTZDtype):\n expected = expected.normalize()\n tm.assert_index_equal(result, expected, exact=True)\n else:\n expected = np.array(unique_values)\n tm.assert_numpy_array_equal(result, expected)\n\n\n@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")\n@pytest.mark.parametrize("null_obj", [np.nan, None])\ndef test_unique_null(null_obj, index_or_series_obj):\n obj = index_or_series_obj\n\n if not allow_na_ops(obj):\n pytest.skip("type doesn't allow for NA operations")\n elif len(obj) < 1:\n pytest.skip("Test doesn't make sense on empty data")\n elif isinstance(obj, pd.MultiIndex):\n pytest.skip(f"MultiIndex can't hold '{null_obj}'")\n\n values = obj._values\n values[0:2] = null_obj\n\n klass = type(obj)\n repeated_values = np.repeat(values, range(1, len(values) + 1))\n obj = klass(repeated_values, dtype=obj.dtype)\n result = obj.unique()\n\n unique_values_raw = dict.fromkeys(obj.values)\n # because np.nan == np.nan is False, but None == None is True\n # np.nan would be duplicated, whereas None wouldn't\n unique_values_not_null = [val for val in unique_values_raw if not pd.isnull(val)]\n unique_values = [null_obj] + unique_values_not_null\n\n if isinstance(obj, pd.Index):\n expected = pd.Index(unique_values, dtype=obj.dtype)\n if isinstance(obj.dtype, pd.DatetimeTZDtype):\n result = result.normalize()\n expected = expected.normalize()\n tm.assert_index_equal(result, expected, exact=True)\n else:\n expected = np.array(unique_values, dtype=obj.dtype)\n tm.assert_numpy_array_equal(result, expected)\n\n\ndef test_nunique(index_or_series_obj):\n obj = index_or_series_obj\n obj = np.repeat(obj, range(1, len(obj) + 1))\n expected = len(obj.unique())\n assert obj.nunique(dropna=False) == expected\n\n\n@pytest.mark.parametrize("null_obj", [np.nan, None])\ndef test_nunique_null(null_obj, index_or_series_obj):\n obj = index_or_series_obj\n\n if not allow_na_ops(obj):\n pytest.skip("type doesn't allow for NA operations")\n elif isinstance(obj, pd.MultiIndex):\n pytest.skip(f"MultiIndex can't hold '{null_obj}'")\n\n values = obj._values\n values[0:2] = null_obj\n\n klass = type(obj)\n repeated_values = np.repeat(values, range(1, len(values) + 1))\n obj = klass(repeated_values, dtype=obj.dtype)\n\n if isinstance(obj, pd.CategoricalIndex):\n assert obj.nunique() == len(obj.categories)\n assert obj.nunique(dropna=False) == len(obj.categories) + 1\n else:\n num_unique_values = len(obj.unique())\n assert obj.nunique() == max(0, num_unique_values - 1)\n assert obj.nunique(dropna=False) == max(0, num_unique_values)\n\n\n@pytest.mark.single_cpu\ndef test_unique_bad_unicode(index_or_series):\n # regression test for #34550\n uval = "\ud83d" # smiley emoji\n\n obj = index_or_series([uval] * 2, dtype=object)\n result = obj.unique()\n\n if isinstance(obj, pd.Index):\n expected = pd.Index(["\ud83d"], dtype=object)\n tm.assert_index_equal(result, expected, exact=True)\n else:\n expected = np.array(["\ud83d"], dtype=object)\n tm.assert_numpy_array_equal(result, expected)\n\n\n@pytest.mark.parametrize("dropna", [True, False])\ndef test_nunique_dropna(dropna):\n # GH37566\n ser = pd.Series(["yes", "yes", pd.NA, np.nan, None, pd.NaT])\n res = ser.nunique(dropna)\n assert res == 1 if dropna else 5\n
.venv\Lib\site-packages\pandas\tests\base\test_unique.py
test_unique.py
Python
4,255
0.95
0.165289
0.052083
node-utils
249
2024-12-08T08:51:49.274612
Apache-2.0
true
b6916d503e663fe7472a77d600849eb0
import collections\nfrom datetime import timedelta\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n DatetimeIndex,\n Index,\n Interval,\n IntervalIndex,\n MultiIndex,\n Series,\n Timedelta,\n TimedeltaIndex,\n array,\n)\nimport pandas._testing as tm\nfrom pandas.tests.base.common import allow_na_ops\n\n\n@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")\ndef test_value_counts(index_or_series_obj):\n obj = index_or_series_obj\n obj = np.repeat(obj, range(1, len(obj) + 1))\n result = obj.value_counts()\n\n counter = collections.Counter(obj)\n expected = Series(dict(counter.most_common()), dtype=np.int64, name="count")\n\n if obj.dtype != np.float16:\n expected.index = expected.index.astype(obj.dtype)\n else:\n with pytest.raises(NotImplementedError, match="float16 indexes are not "):\n expected.index.astype(obj.dtype)\n return\n if isinstance(expected.index, MultiIndex):\n expected.index.names = obj.names\n else:\n expected.index.name = obj.name\n\n if not isinstance(result.dtype, np.dtype):\n if getattr(obj.dtype, "storage", "") == "pyarrow":\n expected = expected.astype("int64[pyarrow]")\n else:\n # i.e IntegerDtype\n expected = expected.astype("Int64")\n\n # TODO(GH#32514): Order of entries with the same count is inconsistent\n # on CI (gh-32449)\n if obj.duplicated().any():\n result = result.sort_index()\n expected = expected.sort_index()\n tm.assert_series_equal(result, expected)\n\n\n@pytest.mark.parametrize("null_obj", [np.nan, None])\n@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")\ndef test_value_counts_null(null_obj, index_or_series_obj):\n orig = index_or_series_obj\n obj = orig.copy()\n\n if not allow_na_ops(obj):\n pytest.skip("type doesn't allow for NA operations")\n elif len(obj) < 1:\n pytest.skip("Test doesn't make sense on empty data")\n elif isinstance(orig, MultiIndex):\n pytest.skip(f"MultiIndex can't hold '{null_obj}'")\n\n values = obj._values\n values[0:2] = null_obj\n\n klass = type(obj)\n repeated_values = np.repeat(values, range(1, len(values) + 1))\n obj = klass(repeated_values, dtype=obj.dtype)\n\n # because np.nan == np.nan is False, but None == None is True\n # np.nan would be duplicated, whereas None wouldn't\n counter = collections.Counter(obj.dropna())\n expected = Series(dict(counter.most_common()), dtype=np.int64, name="count")\n\n if obj.dtype != np.float16:\n expected.index = expected.index.astype(obj.dtype)\n else:\n with pytest.raises(NotImplementedError, match="float16 indexes are not "):\n expected.index.astype(obj.dtype)\n return\n expected.index.name = obj.name\n\n result = obj.value_counts()\n if obj.duplicated().any():\n # TODO(GH#32514):\n # Order of entries with the same count is inconsistent on CI (gh-32449)\n expected = expected.sort_index()\n result = result.sort_index()\n\n if not isinstance(result.dtype, np.dtype):\n if getattr(obj.dtype, "storage", "") == "pyarrow":\n expected = expected.astype("int64[pyarrow]")\n else:\n # i.e IntegerDtype\n expected = expected.astype("Int64")\n tm.assert_series_equal(result, expected)\n\n expected[null_obj] = 3\n\n result = obj.value_counts(dropna=False)\n if obj.duplicated().any():\n # TODO(GH#32514):\n # Order of entries with the same count is inconsistent on CI (gh-32449)\n expected = expected.sort_index()\n result = result.sort_index()\n tm.assert_series_equal(result, expected)\n\n\ndef test_value_counts_inferred(index_or_series, using_infer_string):\n klass = index_or_series\n s_values = ["a", "b", "b", "b", "b", "c", "d", "d", "a", "a"]\n s = klass(s_values)\n expected = Series([4, 3, 2, 1], index=["b", "a", "d", "c"], name="count")\n tm.assert_series_equal(s.value_counts(), expected)\n\n if isinstance(s, Index):\n exp = Index(np.unique(np.array(s_values, dtype=np.object_)))\n tm.assert_index_equal(s.unique(), exp)\n else:\n exp = np.unique(np.array(s_values, dtype=np.object_))\n if using_infer_string:\n exp = array(exp, dtype="str")\n tm.assert_equal(s.unique(), exp)\n\n assert s.nunique() == 4\n # don't sort, have to sort after the fact as not sorting is\n # platform-dep\n hist = s.value_counts(sort=False).sort_values()\n expected = Series([3, 1, 4, 2], index=list("acbd"), name="count").sort_values()\n tm.assert_series_equal(hist, expected)\n\n # sort ascending\n hist = s.value_counts(ascending=True)\n expected = Series([1, 2, 3, 4], index=list("cdab"), name="count")\n tm.assert_series_equal(hist, expected)\n\n # relative histogram.\n hist = s.value_counts(normalize=True)\n expected = Series(\n [0.4, 0.3, 0.2, 0.1], index=["b", "a", "d", "c"], name="proportion"\n )\n tm.assert_series_equal(hist, expected)\n\n\ndef test_value_counts_bins(index_or_series, using_infer_string):\n klass = index_or_series\n s_values = ["a", "b", "b", "b", "b", "c", "d", "d", "a", "a"]\n s = klass(s_values)\n\n # bins\n msg = "bins argument only works with numeric data"\n with pytest.raises(TypeError, match=msg):\n s.value_counts(bins=1)\n\n s1 = Series([1, 1, 2, 3])\n res1 = s1.value_counts(bins=1)\n exp1 = Series({Interval(0.997, 3.0): 4}, name="count")\n tm.assert_series_equal(res1, exp1)\n res1n = s1.value_counts(bins=1, normalize=True)\n exp1n = Series({Interval(0.997, 3.0): 1.0}, name="proportion")\n tm.assert_series_equal(res1n, exp1n)\n\n if isinstance(s1, Index):\n tm.assert_index_equal(s1.unique(), Index([1, 2, 3]))\n else:\n exp = np.array([1, 2, 3], dtype=np.int64)\n tm.assert_numpy_array_equal(s1.unique(), exp)\n\n assert s1.nunique() == 3\n\n # these return the same\n res4 = s1.value_counts(bins=4, dropna=True)\n intervals = IntervalIndex.from_breaks([0.997, 1.5, 2.0, 2.5, 3.0])\n exp4 = Series([2, 1, 1, 0], index=intervals.take([0, 1, 3, 2]), name="count")\n tm.assert_series_equal(res4, exp4)\n\n res4 = s1.value_counts(bins=4, dropna=False)\n intervals = IntervalIndex.from_breaks([0.997, 1.5, 2.0, 2.5, 3.0])\n exp4 = Series([2, 1, 1, 0], index=intervals.take([0, 1, 3, 2]), name="count")\n tm.assert_series_equal(res4, exp4)\n\n res4n = s1.value_counts(bins=4, normalize=True)\n exp4n = Series(\n [0.5, 0.25, 0.25, 0], index=intervals.take([0, 1, 3, 2]), name="proportion"\n )\n tm.assert_series_equal(res4n, exp4n)\n\n # handle NA's properly\n s_values = ["a", "b", "b", "b", np.nan, np.nan, "d", "d", "a", "a", "b"]\n s = klass(s_values)\n expected = Series([4, 3, 2], index=["b", "a", "d"], name="count")\n tm.assert_series_equal(s.value_counts(), expected)\n\n if isinstance(s, Index):\n exp = Index(["a", "b", np.nan, "d"])\n tm.assert_index_equal(s.unique(), exp)\n else:\n exp = np.array(["a", "b", np.nan, "d"], dtype=object)\n if using_infer_string:\n exp = array(exp, dtype="str")\n tm.assert_equal(s.unique(), exp)\n assert s.nunique() == 3\n\n s = klass({}) if klass is dict else klass({}, dtype=object)\n expected = Series([], dtype=np.int64, name="count")\n tm.assert_series_equal(s.value_counts(), expected, check_index_type=False)\n # returned dtype differs depending on original\n if isinstance(s, Index):\n tm.assert_index_equal(s.unique(), Index([]), exact=False)\n else:\n tm.assert_numpy_array_equal(s.unique(), np.array([]), check_dtype=False)\n\n assert s.nunique() == 0\n\n\ndef test_value_counts_datetime64(index_or_series, unit):\n klass = index_or_series\n\n # GH 3002, datetime64[ns]\n # don't test names though\n df = pd.DataFrame(\n {\n "person_id": ["xxyyzz", "xxyyzz", "xxyyzz", "xxyyww", "foofoo", "foofoo"],\n "dt": pd.to_datetime(\n [\n "2010-01-01",\n "2010-01-01",\n "2010-01-01",\n "2009-01-01",\n "2008-09-09",\n "2008-09-09",\n ]\n ).as_unit(unit),\n "food": ["PIE", "GUM", "EGG", "EGG", "PIE", "GUM"],\n }\n )\n\n s = klass(df["dt"].copy())\n s.name = None\n idx = pd.to_datetime(\n ["2010-01-01 00:00:00", "2008-09-09 00:00:00", "2009-01-01 00:00:00"]\n ).as_unit(unit)\n expected_s = Series([3, 2, 1], index=idx, name="count")\n tm.assert_series_equal(s.value_counts(), expected_s)\n\n expected = array(\n np.array(\n ["2010-01-01 00:00:00", "2009-01-01 00:00:00", "2008-09-09 00:00:00"],\n dtype=f"datetime64[{unit}]",\n )\n )\n result = s.unique()\n if isinstance(s, Index):\n tm.assert_index_equal(result, DatetimeIndex(expected))\n else:\n tm.assert_extension_array_equal(result, expected)\n\n assert s.nunique() == 3\n\n # with NaT\n s = df["dt"].copy()\n s = klass(list(s.values) + [pd.NaT] * 4)\n if klass is Series:\n s = s.dt.as_unit(unit)\n else:\n s = s.as_unit(unit)\n\n result = s.value_counts()\n assert result.index.dtype == f"datetime64[{unit}]"\n tm.assert_series_equal(result, expected_s)\n\n result = s.value_counts(dropna=False)\n expected_s = pd.concat(\n [\n Series([4], index=DatetimeIndex([pd.NaT]).as_unit(unit), name="count"),\n expected_s,\n ]\n )\n tm.assert_series_equal(result, expected_s)\n\n assert s.dtype == f"datetime64[{unit}]"\n unique = s.unique()\n assert unique.dtype == f"datetime64[{unit}]"\n\n # numpy_array_equal cannot compare pd.NaT\n if isinstance(s, Index):\n exp_idx = DatetimeIndex(expected.tolist() + [pd.NaT]).as_unit(unit)\n tm.assert_index_equal(unique, exp_idx)\n else:\n tm.assert_extension_array_equal(unique[:3], expected)\n assert pd.isna(unique[3])\n\n assert s.nunique() == 3\n assert s.nunique(dropna=False) == 4\n\n\ndef test_value_counts_timedelta64(index_or_series, unit):\n # timedelta64[ns]\n klass = index_or_series\n\n day = Timedelta(timedelta(1)).as_unit(unit)\n tdi = TimedeltaIndex([day], name="dt").as_unit(unit)\n\n tdvals = np.zeros(6, dtype=f"m8[{unit}]") + day\n td = klass(tdvals, name="dt")\n\n result = td.value_counts()\n expected_s = Series([6], index=tdi, name="count")\n tm.assert_series_equal(result, expected_s)\n\n expected = tdi\n result = td.unique()\n if isinstance(td, Index):\n tm.assert_index_equal(result, expected)\n else:\n tm.assert_extension_array_equal(result, expected._values)\n\n td2 = day + np.zeros(6, dtype=f"m8[{unit}]")\n td2 = klass(td2, name="dt")\n result2 = td2.value_counts()\n tm.assert_series_equal(result2, expected_s)\n\n\n@pytest.mark.parametrize("dropna", [True, False])\ndef test_value_counts_with_nan(dropna, index_or_series):\n # GH31944\n klass = index_or_series\n values = [True, pd.NA, np.nan]\n obj = klass(values)\n res = obj.value_counts(dropna=dropna)\n if dropna is True:\n expected = Series([1], index=Index([True], dtype=obj.dtype), name="count")\n else:\n expected = Series([1, 1, 1], index=[True, pd.NA, np.nan], name="count")\n tm.assert_series_equal(res, expected)\n\n\ndef test_value_counts_object_inference_deprecated():\n # GH#56161\n dti = pd.date_range("2016-01-01", periods=3, tz="UTC")\n\n idx = dti.astype(object)\n msg = "The behavior of value_counts with object-dtype is deprecated"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n res = idx.value_counts()\n\n exp = dti.value_counts()\n tm.assert_series_equal(res, exp)\n
.venv\Lib\site-packages\pandas\tests\base\test_value_counts.py
test_value_counts.py
Python
11,804
0.95
0.089888
0.085324
node-utils
741
2024-04-11T18:03:29.124698
MIT
true
303e4020245431d4abe29e3be90683be
\n\n
.venv\Lib\site-packages\pandas\tests\base\__pycache__\common.cpython-313.pyc
common.cpython-313.pyc
Other
699
0.7
0
0
awesome-app
115
2023-10-19T00:15:18.622883
BSD-3-Clause
true
9b47d859dfb8fe6f0b4c54d5823d88ff
\n\n
.venv\Lib\site-packages\pandas\tests\base\__pycache__\test_constructors.cpython-313.pyc
test_constructors.cpython-313.pyc
Other
9,236
0.8
0.010989
0
python-kit
142
2025-04-22T12:25:58.466717
Apache-2.0
true
0369a35cdf27735671f16c7595de7915
\n\n
.venv\Lib\site-packages\pandas\tests\base\__pycache__\test_conversion.cpython-313.pyc
test_conversion.cpython-313.pyc
Other
27,950
0.8
0
0.022364
node-utils
36
2024-05-22T08:15:38.672306
BSD-3-Clause
true
ee3d8d6450fe42254f78726b3b960602
\n\n
.venv\Lib\site-packages\pandas\tests\base\__pycache__\test_fillna.cpython-313.pyc
test_fillna.cpython-313.pyc
Other
2,491
0.8
0.071429
0.083333
react-lib
248
2024-06-18T23:07:23.027565
GPL-3.0
true
985d8ca083dc59b67518cceb929fcfc2
\n\n
.venv\Lib\site-packages\pandas\tests\base\__pycache__\test_misc.cpython-313.pyc
test_misc.cpython-313.pyc
Other
9,209
0.8
0.073684
0
python-kit
199
2025-05-08T03:10:20.312921
Apache-2.0
true
2472187dbcb7ea1345ed6bd9010b5c30
\n\n
.venv\Lib\site-packages\pandas\tests\base\__pycache__\test_transpose.cpython-313.pyc
test_transpose.cpython-313.pyc
Other
2,845
0.8
0
0
node-utils
631
2024-10-19T20:48:14.459193
Apache-2.0
true
4db6ab065dbf6bd25e12322ef1c8e911
\n\n
.venv\Lib\site-packages\pandas\tests\base\__pycache__\test_unique.cpython-313.pyc
test_unique.cpython-313.pyc
Other
7,433
0.8
0.014493
0
awesome-app
418
2025-06-12T09:59:31.145271
Apache-2.0
true
a56efa9a7c0d12cd37f12c955ed42a8e
\n\n
.venv\Lib\site-packages\pandas\tests\base\__pycache__\test_value_counts.cpython-313.pyc
test_value_counts.cpython-313.pyc
Other
17,983
0.8
0.004926
0.010471
python-kit
408
2024-12-20T03:09:36.761031
GPL-3.0
true
ed1ca82c758b0effde80c3c1ae97e577
\n\n
.venv\Lib\site-packages\pandas\tests\base\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
192
0.7
0
0
awesome-app
27
2025-07-08T00:39:37.342193
Apache-2.0
true
4908b28ada882f71e9523b617a971750
import pytest\n\nfrom pandas.compat._optional import VERSIONS\n\nimport pandas as pd\nfrom pandas.core.computation import expr\nfrom pandas.core.computation.engines import ENGINES\nfrom pandas.util.version import Version\n\n\ndef test_compat():\n # test we have compat with our version of numexpr\n\n from pandas.core.computation.check import NUMEXPR_INSTALLED\n\n ne = pytest.importorskip("numexpr")\n\n ver = ne.__version__\n if Version(ver) < Version(VERSIONS["numexpr"]):\n assert not NUMEXPR_INSTALLED\n else:\n assert NUMEXPR_INSTALLED\n\n\n@pytest.mark.parametrize("engine", ENGINES)\n@pytest.mark.parametrize("parser", expr.PARSERS)\ndef test_invalid_numexpr_version(engine, parser):\n if engine == "numexpr":\n pytest.importorskip("numexpr")\n a, b = 1, 2 # noqa: F841\n res = pd.eval("a + b", engine=engine, parser=parser)\n assert res == 3\n
.venv\Lib\site-packages\pandas\tests\computation\test_compat.py
test_compat.py
Python
872
0.95
0.125
0.043478
react-lib
739
2024-03-19T01:27:17.560749
GPL-3.0
true
1b74832e8f66961eb0d50389e6da6789
from __future__ import annotations\n\nfrom functools import reduce\nfrom itertools import product\nimport operator\n\nimport numpy as np\nimport pytest\n\nfrom pandas.compat import PY312\nfrom pandas.errors import (\n NumExprClobberingError,\n PerformanceWarning,\n UndefinedVariableError,\n)\nimport pandas.util._test_decorators as td\n\nfrom pandas.core.dtypes.common import (\n is_bool,\n is_float,\n is_list_like,\n is_scalar,\n)\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n Index,\n Series,\n date_range,\n period_range,\n timedelta_range,\n)\nimport pandas._testing as tm\nfrom pandas.core.computation import (\n expr,\n pytables,\n)\nfrom pandas.core.computation.engines import ENGINES\nfrom pandas.core.computation.expr import (\n BaseExprVisitor,\n PandasExprVisitor,\n PythonExprVisitor,\n)\nfrom pandas.core.computation.expressions import (\n NUMEXPR_INSTALLED,\n USE_NUMEXPR,\n)\nfrom pandas.core.computation.ops import (\n ARITH_OPS_SYMS,\n SPECIAL_CASE_ARITH_OPS_SYMS,\n _binary_math_ops,\n _binary_ops_dict,\n _unary_math_ops,\n)\nfrom pandas.core.computation.scope import DEFAULT_GLOBALS\n\n\n@pytest.fixture(\n params=(\n pytest.param(\n engine,\n marks=[\n pytest.mark.skipif(\n engine == "numexpr" and not USE_NUMEXPR,\n reason=f"numexpr enabled->{USE_NUMEXPR}, "\n f"installed->{NUMEXPR_INSTALLED}",\n ),\n td.skip_if_no("numexpr"),\n ],\n )\n for engine in ENGINES\n )\n)\ndef engine(request):\n return request.param\n\n\n@pytest.fixture(params=expr.PARSERS)\ndef parser(request):\n return request.param\n\n\ndef _eval_single_bin(lhs, cmp1, rhs, engine):\n c = _binary_ops_dict[cmp1]\n if ENGINES[engine].has_neg_frac:\n try:\n return c(lhs, rhs)\n except ValueError as e:\n if str(e).startswith(\n "negative number cannot be raised to a fractional power"\n ):\n return np.nan\n raise\n return c(lhs, rhs)\n\n\n# TODO: using range(5) here is a kludge\n@pytest.fixture(\n params=list(range(5)),\n ids=["DataFrame", "Series", "SeriesNaN", "DataFrameNaN", "float"],\n)\ndef lhs(request):\n nan_df1 = DataFrame(np.random.default_rng(2).standard_normal((10, 5)))\n nan_df1[nan_df1 > 0.5] = np.nan\n\n opts = (\n DataFrame(np.random.default_rng(2).standard_normal((10, 5))),\n Series(np.random.default_rng(2).standard_normal(5)),\n Series([1, 2, np.nan, np.nan, 5]),\n nan_df1,\n np.random.default_rng(2).standard_normal(),\n )\n return opts[request.param]\n\n\nrhs = lhs\nmidhs = lhs\n\n\n@pytest.fixture\ndef idx_func_dict():\n return {\n "i": lambda n: Index(np.arange(n), dtype=np.int64),\n "f": lambda n: Index(np.arange(n), dtype=np.float64),\n "s": lambda n: Index([f"{i}_{chr(i)}" for i in range(97, 97 + n)]),\n "dt": lambda n: date_range("2020-01-01", periods=n),\n "td": lambda n: timedelta_range("1 day", periods=n),\n "p": lambda n: period_range("2020-01-01", periods=n, freq="D"),\n }\n\n\nclass TestEval:\n @pytest.mark.parametrize(\n "cmp1",\n ["!=", "==", "<=", ">=", "<", ">"],\n ids=["ne", "eq", "le", "ge", "lt", "gt"],\n )\n @pytest.mark.parametrize("cmp2", [">", "<"], ids=["gt", "lt"])\n @pytest.mark.parametrize("binop", expr.BOOL_OPS_SYMS)\n def test_complex_cmp_ops(self, cmp1, cmp2, binop, lhs, rhs, engine, parser):\n if parser == "python" and binop in ["and", "or"]:\n msg = "'BoolOp' nodes are not implemented"\n with pytest.raises(NotImplementedError, match=msg):\n ex = f"(lhs {cmp1} rhs) {binop} (lhs {cmp2} rhs)"\n pd.eval(ex, engine=engine, parser=parser)\n return\n\n lhs_new = _eval_single_bin(lhs, cmp1, rhs, engine)\n rhs_new = _eval_single_bin(lhs, cmp2, rhs, engine)\n expected = _eval_single_bin(lhs_new, binop, rhs_new, engine)\n\n ex = f"(lhs {cmp1} rhs) {binop} (lhs {cmp2} rhs)"\n result = pd.eval(ex, engine=engine, parser=parser)\n tm.assert_equal(result, expected)\n\n @pytest.mark.parametrize("cmp_op", expr.CMP_OPS_SYMS)\n def test_simple_cmp_ops(self, cmp_op, lhs, rhs, engine, parser):\n lhs = lhs < 0\n rhs = rhs < 0\n\n if parser == "python" and cmp_op in ["in", "not in"]:\n msg = "'(In|NotIn)' nodes are not implemented"\n\n with pytest.raises(NotImplementedError, match=msg):\n ex = f"lhs {cmp_op} rhs"\n pd.eval(ex, engine=engine, parser=parser)\n return\n\n ex = f"lhs {cmp_op} rhs"\n msg = "|".join(\n [\n r"only list-like( or dict-like)? objects are allowed to be "\n r"passed to (DataFrame\.)?isin\(\), you passed a "\n r"(`|')bool(`|')",\n "argument of type 'bool' is not iterable",\n ]\n )\n if cmp_op in ("in", "not in") and not is_list_like(rhs):\n with pytest.raises(TypeError, match=msg):\n pd.eval(\n ex,\n engine=engine,\n parser=parser,\n local_dict={"lhs": lhs, "rhs": rhs},\n )\n else:\n expected = _eval_single_bin(lhs, cmp_op, rhs, engine)\n result = pd.eval(ex, engine=engine, parser=parser)\n tm.assert_equal(result, expected)\n\n @pytest.mark.parametrize("op", expr.CMP_OPS_SYMS)\n def test_compound_invert_op(self, op, lhs, rhs, request, engine, parser):\n if parser == "python" and op in ["in", "not in"]:\n msg = "'(In|NotIn)' nodes are not implemented"\n with pytest.raises(NotImplementedError, match=msg):\n ex = f"~(lhs {op} rhs)"\n pd.eval(ex, engine=engine, parser=parser)\n return\n\n if (\n is_float(lhs)\n and not is_float(rhs)\n and op in ["in", "not in"]\n and engine == "python"\n and parser == "pandas"\n ):\n mark = pytest.mark.xfail(\n reason="Looks like expected is negative, unclear whether "\n "expected is incorrect or result is incorrect"\n )\n request.applymarker(mark)\n skip_these = ["in", "not in"]\n ex = f"~(lhs {op} rhs)"\n\n msg = "|".join(\n [\n r"only list-like( or dict-like)? objects are allowed to be "\n r"passed to (DataFrame\.)?isin\(\), you passed a "\n r"(`|')float(`|')",\n "argument of type 'float' is not iterable",\n ]\n )\n if is_scalar(rhs) and op in skip_these:\n with pytest.raises(TypeError, match=msg):\n pd.eval(\n ex,\n engine=engine,\n parser=parser,\n local_dict={"lhs": lhs, "rhs": rhs},\n )\n else:\n # compound\n if is_scalar(lhs) and is_scalar(rhs):\n lhs, rhs = (np.array([x]) for x in (lhs, rhs))\n expected = _eval_single_bin(lhs, op, rhs, engine)\n if is_scalar(expected):\n expected = not expected\n else:\n expected = ~expected\n result = pd.eval(ex, engine=engine, parser=parser)\n tm.assert_almost_equal(expected, result)\n\n @pytest.mark.parametrize("cmp1", ["<", ">"])\n @pytest.mark.parametrize("cmp2", ["<", ">"])\n def test_chained_cmp_op(self, cmp1, cmp2, lhs, midhs, rhs, engine, parser):\n mid = midhs\n if parser == "python":\n ex1 = f"lhs {cmp1} mid {cmp2} rhs"\n msg = "'BoolOp' nodes are not implemented"\n with pytest.raises(NotImplementedError, match=msg):\n pd.eval(ex1, engine=engine, parser=parser)\n return\n\n lhs_new = _eval_single_bin(lhs, cmp1, mid, engine)\n rhs_new = _eval_single_bin(mid, cmp2, rhs, engine)\n\n if lhs_new is not None and rhs_new is not None:\n ex1 = f"lhs {cmp1} mid {cmp2} rhs"\n ex2 = f"lhs {cmp1} mid and mid {cmp2} rhs"\n ex3 = f"(lhs {cmp1} mid) & (mid {cmp2} rhs)"\n expected = _eval_single_bin(lhs_new, "&", rhs_new, engine)\n\n for ex in (ex1, ex2, ex3):\n result = pd.eval(ex, engine=engine, parser=parser)\n\n tm.assert_almost_equal(result, expected)\n\n @pytest.mark.parametrize(\n "arith1", sorted(set(ARITH_OPS_SYMS).difference(SPECIAL_CASE_ARITH_OPS_SYMS))\n )\n def test_binary_arith_ops(self, arith1, lhs, rhs, engine, parser):\n ex = f"lhs {arith1} rhs"\n result = pd.eval(ex, engine=engine, parser=parser)\n expected = _eval_single_bin(lhs, arith1, rhs, engine)\n\n tm.assert_almost_equal(result, expected)\n ex = f"lhs {arith1} rhs {arith1} rhs"\n result = pd.eval(ex, engine=engine, parser=parser)\n nlhs = _eval_single_bin(lhs, arith1, rhs, engine)\n try:\n nlhs, ghs = nlhs.align(rhs)\n except (ValueError, TypeError, AttributeError):\n # ValueError: series frame or frame series align\n # TypeError, AttributeError: series or frame with scalar align\n return\n else:\n if engine == "numexpr":\n import numexpr as ne\n\n # direct numpy comparison\n expected = ne.evaluate(f"nlhs {arith1} ghs")\n # Update assert statement due to unreliable numerical\n # precision component (GH37328)\n # TODO: update testing code so that assert_almost_equal statement\n # can be replaced again by the assert_numpy_array_equal statement\n tm.assert_almost_equal(result.values, expected)\n else:\n expected = eval(f"nlhs {arith1} ghs")\n tm.assert_almost_equal(result, expected)\n\n # modulus, pow, and floor division require special casing\n\n def test_modulus(self, lhs, rhs, engine, parser):\n ex = r"lhs % rhs"\n result = pd.eval(ex, engine=engine, parser=parser)\n expected = lhs % rhs\n tm.assert_almost_equal(result, expected)\n\n if engine == "numexpr":\n import numexpr as ne\n\n expected = ne.evaluate(r"expected % rhs")\n if isinstance(result, (DataFrame, Series)):\n tm.assert_almost_equal(result.values, expected)\n else:\n tm.assert_almost_equal(result, expected.item())\n else:\n expected = _eval_single_bin(expected, "%", rhs, engine)\n tm.assert_almost_equal(result, expected)\n\n def test_floor_division(self, lhs, rhs, engine, parser):\n ex = "lhs // rhs"\n\n if engine == "python":\n res = pd.eval(ex, engine=engine, parser=parser)\n expected = lhs // rhs\n tm.assert_equal(res, expected)\n else:\n msg = (\n r"unsupported operand type\(s\) for //: 'VariableNode' and "\n "'VariableNode'"\n )\n with pytest.raises(TypeError, match=msg):\n pd.eval(\n ex,\n local_dict={"lhs": lhs, "rhs": rhs},\n engine=engine,\n parser=parser,\n )\n\n @td.skip_if_windows\n def test_pow(self, lhs, rhs, engine, parser):\n # odd failure on win32 platform, so skip\n ex = "lhs ** rhs"\n expected = _eval_single_bin(lhs, "**", rhs, engine)\n result = pd.eval(ex, engine=engine, parser=parser)\n\n if (\n is_scalar(lhs)\n and is_scalar(rhs)\n and isinstance(expected, (complex, np.complexfloating))\n and np.isnan(result)\n ):\n msg = "(DataFrame.columns|numpy array) are different"\n with pytest.raises(AssertionError, match=msg):\n tm.assert_numpy_array_equal(result, expected)\n else:\n tm.assert_almost_equal(result, expected)\n\n ex = "(lhs ** rhs) ** rhs"\n result = pd.eval(ex, engine=engine, parser=parser)\n\n middle = _eval_single_bin(lhs, "**", rhs, engine)\n expected = _eval_single_bin(middle, "**", rhs, engine)\n tm.assert_almost_equal(result, expected)\n\n def test_check_single_invert_op(self, lhs, engine, parser):\n # simple\n try:\n elb = lhs.astype(bool)\n except AttributeError:\n elb = np.array([bool(lhs)])\n expected = ~elb\n result = pd.eval("~elb", engine=engine, parser=parser)\n tm.assert_almost_equal(expected, result)\n\n def test_frame_invert(self, engine, parser):\n expr = "~lhs"\n\n # ~ ##\n # frame\n # float always raises\n lhs = DataFrame(np.random.default_rng(2).standard_normal((5, 2)))\n if engine == "numexpr":\n msg = "couldn't find matching opcode for 'invert_dd'"\n with pytest.raises(NotImplementedError, match=msg):\n pd.eval(expr, engine=engine, parser=parser)\n else:\n msg = "ufunc 'invert' not supported for the input types"\n with pytest.raises(TypeError, match=msg):\n pd.eval(expr, engine=engine, parser=parser)\n\n # int raises on numexpr\n lhs = DataFrame(np.random.default_rng(2).integers(5, size=(5, 2)))\n if engine == "numexpr":\n msg = "couldn't find matching opcode for 'invert"\n with pytest.raises(NotImplementedError, match=msg):\n pd.eval(expr, engine=engine, parser=parser)\n else:\n expect = ~lhs\n result = pd.eval(expr, engine=engine, parser=parser)\n tm.assert_frame_equal(expect, result)\n\n # bool always works\n lhs = DataFrame(np.random.default_rng(2).standard_normal((5, 2)) > 0.5)\n expect = ~lhs\n result = pd.eval(expr, engine=engine, parser=parser)\n tm.assert_frame_equal(expect, result)\n\n # object raises\n lhs = DataFrame(\n {"b": ["a", 1, 2.0], "c": np.random.default_rng(2).standard_normal(3) > 0.5}\n )\n if engine == "numexpr":\n with pytest.raises(ValueError, match="unknown type object"):\n pd.eval(expr, engine=engine, parser=parser)\n else:\n msg = "bad operand type for unary ~: 'str'"\n with pytest.raises(TypeError, match=msg):\n pd.eval(expr, engine=engine, parser=parser)\n\n def test_series_invert(self, engine, parser):\n # ~ ####\n expr = "~lhs"\n\n # series\n # float raises\n lhs = Series(np.random.default_rng(2).standard_normal(5))\n if engine == "numexpr":\n msg = "couldn't find matching opcode for 'invert_dd'"\n with pytest.raises(NotImplementedError, match=msg):\n result = pd.eval(expr, engine=engine, parser=parser)\n else:\n msg = "ufunc 'invert' not supported for the input types"\n with pytest.raises(TypeError, match=msg):\n pd.eval(expr, engine=engine, parser=parser)\n\n # int raises on numexpr\n lhs = Series(np.random.default_rng(2).integers(5, size=5))\n if engine == "numexpr":\n msg = "couldn't find matching opcode for 'invert"\n with pytest.raises(NotImplementedError, match=msg):\n pd.eval(expr, engine=engine, parser=parser)\n else:\n expect = ~lhs\n result = pd.eval(expr, engine=engine, parser=parser)\n tm.assert_series_equal(expect, result)\n\n # bool\n lhs = Series(np.random.default_rng(2).standard_normal(5) > 0.5)\n expect = ~lhs\n result = pd.eval(expr, engine=engine, parser=parser)\n tm.assert_series_equal(expect, result)\n\n # float\n # int\n # bool\n\n # object\n lhs = Series(["a", 1, 2.0])\n if engine == "numexpr":\n with pytest.raises(ValueError, match="unknown type object"):\n pd.eval(expr, engine=engine, parser=parser)\n else:\n msg = "bad operand type for unary ~: 'str'"\n with pytest.raises(TypeError, match=msg):\n pd.eval(expr, engine=engine, parser=parser)\n\n def test_frame_negate(self, engine, parser):\n expr = "-lhs"\n\n # float\n lhs = DataFrame(np.random.default_rng(2).standard_normal((5, 2)))\n expect = -lhs\n result = pd.eval(expr, engine=engine, parser=parser)\n tm.assert_frame_equal(expect, result)\n\n # int\n lhs = DataFrame(np.random.default_rng(2).integers(5, size=(5, 2)))\n expect = -lhs\n result = pd.eval(expr, engine=engine, parser=parser)\n tm.assert_frame_equal(expect, result)\n\n # bool doesn't work with numexpr but works elsewhere\n lhs = DataFrame(np.random.default_rng(2).standard_normal((5, 2)) > 0.5)\n if engine == "numexpr":\n msg = "couldn't find matching opcode for 'neg_bb'"\n with pytest.raises(NotImplementedError, match=msg):\n pd.eval(expr, engine=engine, parser=parser)\n else:\n expect = -lhs\n result = pd.eval(expr, engine=engine, parser=parser)\n tm.assert_frame_equal(expect, result)\n\n def test_series_negate(self, engine, parser):\n expr = "-lhs"\n\n # float\n lhs = Series(np.random.default_rng(2).standard_normal(5))\n expect = -lhs\n result = pd.eval(expr, engine=engine, parser=parser)\n tm.assert_series_equal(expect, result)\n\n # int\n lhs = Series(np.random.default_rng(2).integers(5, size=5))\n expect = -lhs\n result = pd.eval(expr, engine=engine, parser=parser)\n tm.assert_series_equal(expect, result)\n\n # bool doesn't work with numexpr but works elsewhere\n lhs = Series(np.random.default_rng(2).standard_normal(5) > 0.5)\n if engine == "numexpr":\n msg = "couldn't find matching opcode for 'neg_bb'"\n with pytest.raises(NotImplementedError, match=msg):\n pd.eval(expr, engine=engine, parser=parser)\n else:\n expect = -lhs\n result = pd.eval(expr, engine=engine, parser=parser)\n tm.assert_series_equal(expect, result)\n\n @pytest.mark.parametrize(\n "lhs",\n [\n # Float\n DataFrame(np.random.default_rng(2).standard_normal((5, 2))),\n # Int\n DataFrame(np.random.default_rng(2).integers(5, size=(5, 2))),\n # bool doesn't work with numexpr but works elsewhere\n DataFrame(np.random.default_rng(2).standard_normal((5, 2)) > 0.5),\n ],\n )\n def test_frame_pos(self, lhs, engine, parser):\n expr = "+lhs"\n expect = lhs\n\n result = pd.eval(expr, engine=engine, parser=parser)\n tm.assert_frame_equal(expect, result)\n\n @pytest.mark.parametrize(\n "lhs",\n [\n # Float\n Series(np.random.default_rng(2).standard_normal(5)),\n # Int\n Series(np.random.default_rng(2).integers(5, size=5)),\n # bool doesn't work with numexpr but works elsewhere\n Series(np.random.default_rng(2).standard_normal(5) > 0.5),\n ],\n )\n def test_series_pos(self, lhs, engine, parser):\n expr = "+lhs"\n expect = lhs\n\n result = pd.eval(expr, engine=engine, parser=parser)\n tm.assert_series_equal(expect, result)\n\n def test_scalar_unary(self, engine, parser):\n msg = "bad operand type for unary ~: 'float'"\n warn = None\n if PY312 and not (engine == "numexpr" and parser == "pandas"):\n warn = DeprecationWarning\n with pytest.raises(TypeError, match=msg):\n pd.eval("~1.0", engine=engine, parser=parser)\n\n assert pd.eval("-1.0", parser=parser, engine=engine) == -1.0\n assert pd.eval("+1.0", parser=parser, engine=engine) == +1.0\n assert pd.eval("~1", parser=parser, engine=engine) == ~1\n assert pd.eval("-1", parser=parser, engine=engine) == -1\n assert pd.eval("+1", parser=parser, engine=engine) == +1\n with tm.assert_produces_warning(\n warn, match="Bitwise inversion", check_stacklevel=False\n ):\n assert pd.eval("~True", parser=parser, engine=engine) == ~True\n with tm.assert_produces_warning(\n warn, match="Bitwise inversion", check_stacklevel=False\n ):\n assert pd.eval("~False", parser=parser, engine=engine) == ~False\n assert pd.eval("-True", parser=parser, engine=engine) == -True\n assert pd.eval("-False", parser=parser, engine=engine) == -False\n assert pd.eval("+True", parser=parser, engine=engine) == +True\n assert pd.eval("+False", parser=parser, engine=engine) == +False\n\n def test_unary_in_array(self):\n # GH 11235\n # TODO: 2022-01-29: result return list with numexpr 2.7.3 in CI\n # but cannot reproduce locally\n result = np.array(\n pd.eval("[-True, True, +True, -False, False, +False, -37, 37, ~37, +37]"),\n dtype=np.object_,\n )\n expected = np.array(\n [\n -True,\n True,\n +True,\n -False,\n False,\n +False,\n -37,\n 37,\n ~37,\n +37,\n ],\n dtype=np.object_,\n )\n tm.assert_numpy_array_equal(result, expected)\n\n @pytest.mark.parametrize("expr", ["x < -0.1", "-5 > x"])\n def test_float_comparison_bin_op(self, float_numpy_dtype, expr):\n # GH 16363\n df = DataFrame({"x": np.array([0], dtype=float_numpy_dtype)})\n res = df.eval(expr)\n assert res.values == np.array([False])\n\n def test_unary_in_function(self):\n # GH 46471\n df = DataFrame({"x": [0, 1, np.nan]})\n\n result = df.eval("x.fillna(-1)")\n expected = df.x.fillna(-1)\n # column name becomes None if using numexpr\n # only check names when the engine is not numexpr\n tm.assert_series_equal(result, expected, check_names=not USE_NUMEXPR)\n\n result = df.eval("x.shift(1, fill_value=-1)")\n expected = df.x.shift(1, fill_value=-1)\n tm.assert_series_equal(result, expected, check_names=not USE_NUMEXPR)\n\n @pytest.mark.parametrize(\n "ex",\n (\n "1 or 2",\n "1 and 2",\n "a and b",\n "a or b",\n "1 or 2 and (3 + 2) > 3",\n "2 * x > 2 or 1 and 2",\n "2 * df > 3 and 1 or a",\n ),\n )\n def test_disallow_scalar_bool_ops(self, ex, engine, parser):\n x, a, b = np.random.default_rng(2).standard_normal(3), 1, 2 # noqa: F841\n df = DataFrame(np.random.default_rng(2).standard_normal((3, 2))) # noqa: F841\n\n msg = "cannot evaluate scalar only bool ops|'BoolOp' nodes are not"\n with pytest.raises(NotImplementedError, match=msg):\n pd.eval(ex, engine=engine, parser=parser)\n\n def test_identical(self, engine, parser):\n # see gh-10546\n x = 1\n result = pd.eval("x", engine=engine, parser=parser)\n assert result == 1\n assert is_scalar(result)\n\n x = 1.5\n result = pd.eval("x", engine=engine, parser=parser)\n assert result == 1.5\n assert is_scalar(result)\n\n x = False\n result = pd.eval("x", engine=engine, parser=parser)\n assert not result\n assert is_bool(result)\n assert is_scalar(result)\n\n x = np.array([1])\n result = pd.eval("x", engine=engine, parser=parser)\n tm.assert_numpy_array_equal(result, np.array([1]))\n assert result.shape == (1,)\n\n x = np.array([1.5])\n result = pd.eval("x", engine=engine, parser=parser)\n tm.assert_numpy_array_equal(result, np.array([1.5]))\n assert result.shape == (1,)\n\n x = np.array([False]) # noqa: F841\n result = pd.eval("x", engine=engine, parser=parser)\n tm.assert_numpy_array_equal(result, np.array([False]))\n assert result.shape == (1,)\n\n def test_line_continuation(self, engine, parser):\n # GH 11149\n exp = """1 + 2 * \\n 5 - 1 + 2 """\n result = pd.eval(exp, engine=engine, parser=parser)\n assert result == 12\n\n def test_float_truncation(self, engine, parser):\n # GH 14241\n exp = "1000000000.006"\n result = pd.eval(exp, engine=engine, parser=parser)\n expected = np.float64(exp)\n assert result == expected\n\n df = DataFrame({"A": [1000000000.0009, 1000000000.0011, 1000000000.0015]})\n cutoff = 1000000000.0006\n result = df.query(f"A < {cutoff:.4f}")\n assert result.empty\n\n cutoff = 1000000000.0010\n result = df.query(f"A > {cutoff:.4f}")\n expected = df.loc[[1, 2], :]\n tm.assert_frame_equal(expected, result)\n\n exact = 1000000000.0011\n result = df.query(f"A == {exact:.4f}")\n expected = df.loc[[1], :]\n tm.assert_frame_equal(expected, result)\n\n def test_disallow_python_keywords(self):\n # GH 18221\n df = DataFrame([[0, 0, 0]], columns=["foo", "bar", "class"])\n msg = "Python keyword not valid identifier in numexpr query"\n with pytest.raises(SyntaxError, match=msg):\n df.query("class == 0")\n\n df = DataFrame()\n df.index.name = "lambda"\n with pytest.raises(SyntaxError, match=msg):\n df.query("lambda == 0")\n\n def test_true_false_logic(self):\n # GH 25823\n # This behavior is deprecated in Python 3.12\n with tm.maybe_produces_warning(\n DeprecationWarning, PY312, check_stacklevel=False\n ):\n assert pd.eval("not True") == -2\n assert pd.eval("not False") == -1\n assert pd.eval("True and not True") == 0\n\n def test_and_logic_string_match(self):\n # GH 25823\n event = Series({"a": "hello"})\n assert pd.eval(f"{event.str.match('hello').a}")\n assert pd.eval(f"{event.str.match('hello').a and event.str.match('hello').a}")\n\n\n# -------------------------------------\n# gh-12388: Typecasting rules consistency with python\n\n\nclass TestTypeCasting:\n @pytest.mark.parametrize("op", ["+", "-", "*", "**", "/"])\n # maybe someday... numexpr has too many upcasting rules now\n # chain(*(np.core.sctypes[x] for x in ['uint', 'int', 'float']))\n @pytest.mark.parametrize("left_right", [("df", "3"), ("3", "df")])\n def test_binop_typecasting(\n self, engine, parser, op, complex_or_float_dtype, left_right, request\n ):\n # GH#21374\n dtype = complex_or_float_dtype\n df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)), dtype=dtype)\n left, right = left_right\n s = f"{left} {op} {right}"\n res = pd.eval(s, engine=engine, parser=parser)\n if dtype == "complex64" and engine == "numexpr":\n mark = pytest.mark.xfail(\n reason="numexpr issue with complex that are upcast "\n "to complex 128 "\n "https://github.com/pydata/numexpr/issues/492"\n )\n request.applymarker(mark)\n assert df.values.dtype == dtype\n assert res.values.dtype == dtype\n tm.assert_frame_equal(res, eval(s), check_exact=False)\n\n\n# -------------------------------------\n# Basic and complex alignment\n\n\ndef should_warn(*args):\n not_mono = not any(map(operator.attrgetter("is_monotonic_increasing"), args))\n only_one_dt = reduce(\n operator.xor, (issubclass(x.dtype.type, np.datetime64) for x in args)\n )\n return not_mono and only_one_dt\n\n\nclass TestAlignment:\n index_types = ["i", "s", "dt"]\n lhs_index_types = index_types + ["s"] # 'p'\n\n def test_align_nested_unary_op(self, engine, parser):\n s = "df * ~2"\n df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))\n res = pd.eval(s, engine=engine, parser=parser)\n tm.assert_frame_equal(res, df * ~2)\n\n @pytest.mark.filterwarnings("always::RuntimeWarning")\n @pytest.mark.parametrize("lr_idx_type", lhs_index_types)\n @pytest.mark.parametrize("rr_idx_type", index_types)\n @pytest.mark.parametrize("c_idx_type", index_types)\n def test_basic_frame_alignment(\n self, engine, parser, lr_idx_type, rr_idx_type, c_idx_type, idx_func_dict\n ):\n df = DataFrame(\n np.random.default_rng(2).standard_normal((10, 10)),\n index=idx_func_dict[lr_idx_type](10),\n columns=idx_func_dict[c_idx_type](10),\n )\n df2 = DataFrame(\n np.random.default_rng(2).standard_normal((20, 10)),\n index=idx_func_dict[rr_idx_type](20),\n columns=idx_func_dict[c_idx_type](10),\n )\n # only warns if not monotonic and not sortable\n if should_warn(df.index, df2.index):\n with tm.assert_produces_warning(RuntimeWarning):\n res = pd.eval("df + df2", engine=engine, parser=parser)\n else:\n res = pd.eval("df + df2", engine=engine, parser=parser)\n tm.assert_frame_equal(res, df + df2)\n\n @pytest.mark.parametrize("r_idx_type", lhs_index_types)\n @pytest.mark.parametrize("c_idx_type", lhs_index_types)\n def test_frame_comparison(\n self, engine, parser, r_idx_type, c_idx_type, idx_func_dict\n ):\n df = DataFrame(\n np.random.default_rng(2).standard_normal((10, 10)),\n index=idx_func_dict[r_idx_type](10),\n columns=idx_func_dict[c_idx_type](10),\n )\n res = pd.eval("df < 2", engine=engine, parser=parser)\n tm.assert_frame_equal(res, df < 2)\n\n df3 = DataFrame(\n np.random.default_rng(2).standard_normal(df.shape),\n index=df.index,\n columns=df.columns,\n )\n res = pd.eval("df < df3", engine=engine, parser=parser)\n tm.assert_frame_equal(res, df < df3)\n\n @pytest.mark.filterwarnings("ignore::RuntimeWarning")\n @pytest.mark.parametrize("r1", lhs_index_types)\n @pytest.mark.parametrize("c1", index_types)\n @pytest.mark.parametrize("r2", index_types)\n @pytest.mark.parametrize("c2", index_types)\n def test_medium_complex_frame_alignment(\n self, engine, parser, r1, c1, r2, c2, idx_func_dict\n ):\n df = DataFrame(\n np.random.default_rng(2).standard_normal((3, 2)),\n index=idx_func_dict[r1](3),\n columns=idx_func_dict[c1](2),\n )\n df2 = DataFrame(\n np.random.default_rng(2).standard_normal((4, 2)),\n index=idx_func_dict[r2](4),\n columns=idx_func_dict[c2](2),\n )\n df3 = DataFrame(\n np.random.default_rng(2).standard_normal((5, 2)),\n index=idx_func_dict[r2](5),\n columns=idx_func_dict[c2](2),\n )\n if should_warn(df.index, df2.index, df3.index):\n with tm.assert_produces_warning(RuntimeWarning):\n res = pd.eval("df + df2 + df3", engine=engine, parser=parser)\n else:\n res = pd.eval("df + df2 + df3", engine=engine, parser=parser)\n tm.assert_frame_equal(res, df + df2 + df3)\n\n @pytest.mark.filterwarnings("ignore::RuntimeWarning")\n @pytest.mark.parametrize("index_name", ["index", "columns"])\n @pytest.mark.parametrize("c_idx_type", index_types)\n @pytest.mark.parametrize("r_idx_type", lhs_index_types)\n def test_basic_frame_series_alignment(\n self, engine, parser, index_name, r_idx_type, c_idx_type, idx_func_dict\n ):\n df = DataFrame(\n np.random.default_rng(2).standard_normal((10, 10)),\n index=idx_func_dict[r_idx_type](10),\n columns=idx_func_dict[c_idx_type](10),\n )\n index = getattr(df, index_name)\n s = Series(np.random.default_rng(2).standard_normal(5), index[:5])\n\n if should_warn(df.index, s.index):\n with tm.assert_produces_warning(RuntimeWarning):\n res = pd.eval("df + s", engine=engine, parser=parser)\n else:\n res = pd.eval("df + s", engine=engine, parser=parser)\n\n if r_idx_type == "dt" or c_idx_type == "dt":\n expected = df.add(s) if engine == "numexpr" else df + s\n else:\n expected = df + s\n tm.assert_frame_equal(res, expected)\n\n @pytest.mark.parametrize("index_name", ["index", "columns"])\n @pytest.mark.parametrize(\n "r_idx_type, c_idx_type",\n list(product(["i", "s"], ["i", "s"])) + [("dt", "dt")],\n )\n @pytest.mark.filterwarnings("ignore::RuntimeWarning")\n def test_basic_series_frame_alignment(\n self, request, engine, parser, index_name, r_idx_type, c_idx_type, idx_func_dict\n ):\n if (\n engine == "numexpr"\n and parser in ("pandas", "python")\n and index_name == "index"\n and r_idx_type == "i"\n and c_idx_type == "s"\n ):\n reason = (\n f"Flaky column ordering when engine={engine}, "\n f"parser={parser}, index_name={index_name}, "\n f"r_idx_type={r_idx_type}, c_idx_type={c_idx_type}"\n )\n request.applymarker(pytest.mark.xfail(reason=reason, strict=False))\n df = DataFrame(\n np.random.default_rng(2).standard_normal((10, 7)),\n index=idx_func_dict[r_idx_type](10),\n columns=idx_func_dict[c_idx_type](7),\n )\n index = getattr(df, index_name)\n s = Series(np.random.default_rng(2).standard_normal(5), index[:5])\n if should_warn(s.index, df.index):\n with tm.assert_produces_warning(RuntimeWarning):\n res = pd.eval("s + df", engine=engine, parser=parser)\n else:\n res = pd.eval("s + df", engine=engine, parser=parser)\n\n if r_idx_type == "dt" or c_idx_type == "dt":\n expected = df.add(s) if engine == "numexpr" else s + df\n else:\n expected = s + df\n tm.assert_frame_equal(res, expected)\n\n @pytest.mark.filterwarnings("ignore::RuntimeWarning")\n @pytest.mark.parametrize("c_idx_type", index_types)\n @pytest.mark.parametrize("r_idx_type", lhs_index_types)\n @pytest.mark.parametrize("index_name", ["index", "columns"])\n @pytest.mark.parametrize("op", ["+", "*"])\n def test_series_frame_commutativity(\n self, engine, parser, index_name, op, r_idx_type, c_idx_type, idx_func_dict\n ):\n df = DataFrame(\n np.random.default_rng(2).standard_normal((10, 10)),\n index=idx_func_dict[r_idx_type](10),\n columns=idx_func_dict[c_idx_type](10),\n )\n index = getattr(df, index_name)\n s = Series(np.random.default_rng(2).standard_normal(5), index[:5])\n\n lhs = f"s {op} df"\n rhs = f"df {op} s"\n if should_warn(df.index, s.index):\n with tm.assert_produces_warning(RuntimeWarning):\n a = pd.eval(lhs, engine=engine, parser=parser)\n with tm.assert_produces_warning(RuntimeWarning):\n b = pd.eval(rhs, engine=engine, parser=parser)\n else:\n a = pd.eval(lhs, engine=engine, parser=parser)\n b = pd.eval(rhs, engine=engine, parser=parser)\n\n if r_idx_type != "dt" and c_idx_type != "dt":\n if engine == "numexpr":\n tm.assert_frame_equal(a, b)\n\n @pytest.mark.filterwarnings("always::RuntimeWarning")\n @pytest.mark.parametrize("r1", lhs_index_types)\n @pytest.mark.parametrize("c1", index_types)\n @pytest.mark.parametrize("r2", index_types)\n @pytest.mark.parametrize("c2", index_types)\n def test_complex_series_frame_alignment(\n self, engine, parser, r1, c1, r2, c2, idx_func_dict\n ):\n n = 3\n m1 = 5\n m2 = 2 * m1\n df = DataFrame(\n np.random.default_rng(2).standard_normal((m1, n)),\n index=idx_func_dict[r1](m1),\n columns=idx_func_dict[c1](n),\n )\n df2 = DataFrame(\n np.random.default_rng(2).standard_normal((m2, n)),\n index=idx_func_dict[r2](m2),\n columns=idx_func_dict[c2](n),\n )\n index = df2.columns\n ser = Series(np.random.default_rng(2).standard_normal(n), index[:n])\n\n if r2 == "dt" or c2 == "dt":\n if engine == "numexpr":\n expected2 = df2.add(ser)\n else:\n expected2 = df2 + ser\n else:\n expected2 = df2 + ser\n\n if r1 == "dt" or c1 == "dt":\n if engine == "numexpr":\n expected = expected2.add(df)\n else:\n expected = expected2 + df\n else:\n expected = expected2 + df\n\n if should_warn(df2.index, ser.index, df.index):\n with tm.assert_produces_warning(RuntimeWarning):\n res = pd.eval("df2 + ser + df", engine=engine, parser=parser)\n else:\n res = pd.eval("df2 + ser + df", engine=engine, parser=parser)\n assert res.shape == expected.shape\n tm.assert_frame_equal(res, expected)\n\n def test_performance_warning_for_poor_alignment(self, engine, parser):\n df = DataFrame(np.random.default_rng(2).standard_normal((1000, 10)))\n s = Series(np.random.default_rng(2).standard_normal(10000))\n if engine == "numexpr":\n seen = PerformanceWarning\n else:\n seen = False\n\n with tm.assert_produces_warning(seen):\n pd.eval("df + s", engine=engine, parser=parser)\n\n s = Series(np.random.default_rng(2).standard_normal(1000))\n with tm.assert_produces_warning(False):\n pd.eval("df + s", engine=engine, parser=parser)\n\n df = DataFrame(np.random.default_rng(2).standard_normal((10, 10000)))\n s = Series(np.random.default_rng(2).standard_normal(10000))\n with tm.assert_produces_warning(False):\n pd.eval("df + s", engine=engine, parser=parser)\n\n df = DataFrame(np.random.default_rng(2).standard_normal((10, 10)))\n s = Series(np.random.default_rng(2).standard_normal(10000))\n\n is_python_engine = engine == "python"\n\n if not is_python_engine:\n wrn = PerformanceWarning\n else:\n wrn = False\n\n with tm.assert_produces_warning(wrn) as w:\n pd.eval("df + s", engine=engine, parser=parser)\n\n if not is_python_engine:\n assert len(w) == 1\n msg = str(w[0].message)\n logged = np.log10(s.size - df.shape[1])\n expected = (\n f"Alignment difference on axis 1 is larger "\n f"than an order of magnitude on term 'df', "\n f"by more than {logged:.4g}; performance may suffer."\n )\n assert msg == expected\n\n\n# ------------------------------------\n# Slightly more complex ops\n\n\nclass TestOperations:\n def eval(self, *args, **kwargs):\n kwargs["level"] = kwargs.pop("level", 0) + 1\n return pd.eval(*args, **kwargs)\n\n def test_simple_arith_ops(self, engine, parser):\n exclude_arith = []\n if parser == "python":\n exclude_arith = ["in", "not in"]\n\n arith_ops = [\n op\n for op in expr.ARITH_OPS_SYMS + expr.CMP_OPS_SYMS\n if op not in exclude_arith\n ]\n\n ops = (op for op in arith_ops if op != "//")\n\n for op in ops:\n ex = f"1 {op} 1"\n ex2 = f"x {op} 1"\n ex3 = f"1 {op} (x + 1)"\n\n if op in ("in", "not in"):\n msg = "argument of type 'int' is not iterable"\n with pytest.raises(TypeError, match=msg):\n pd.eval(ex, engine=engine, parser=parser)\n else:\n expec = _eval_single_bin(1, op, 1, engine)\n x = self.eval(ex, engine=engine, parser=parser)\n assert x == expec\n\n expec = _eval_single_bin(x, op, 1, engine)\n y = self.eval(ex2, local_dict={"x": x}, engine=engine, parser=parser)\n assert y == expec\n\n expec = _eval_single_bin(1, op, x + 1, engine)\n y = self.eval(ex3, local_dict={"x": x}, engine=engine, parser=parser)\n assert y == expec\n\n @pytest.mark.parametrize("rhs", [True, False])\n @pytest.mark.parametrize("lhs", [True, False])\n @pytest.mark.parametrize("op", expr.BOOL_OPS_SYMS)\n def test_simple_bool_ops(self, rhs, lhs, op):\n ex = f"{lhs} {op} {rhs}"\n\n if parser == "python" and op in ["and", "or"]:\n msg = "'BoolOp' nodes are not implemented"\n with pytest.raises(NotImplementedError, match=msg):\n self.eval(ex)\n return\n\n res = self.eval(ex)\n exp = eval(ex)\n assert res == exp\n\n @pytest.mark.parametrize("rhs", [True, False])\n @pytest.mark.parametrize("lhs", [True, False])\n @pytest.mark.parametrize("op", expr.BOOL_OPS_SYMS)\n def test_bool_ops_with_constants(self, rhs, lhs, op):\n ex = f"{lhs} {op} {rhs}"\n\n if parser == "python" and op in ["and", "or"]:\n msg = "'BoolOp' nodes are not implemented"\n with pytest.raises(NotImplementedError, match=msg):\n self.eval(ex)\n return\n\n res = self.eval(ex)\n exp = eval(ex)\n assert res == exp\n\n def test_4d_ndarray_fails(self):\n x = np.random.default_rng(2).standard_normal((3, 4, 5, 6))\n y = Series(np.random.default_rng(2).standard_normal(10))\n msg = "N-dimensional objects, where N > 2, are not supported with eval"\n with pytest.raises(NotImplementedError, match=msg):\n self.eval("x + y", local_dict={"x": x, "y": y})\n\n def test_constant(self):\n x = self.eval("1")\n assert x == 1\n\n def test_single_variable(self):\n df = DataFrame(np.random.default_rng(2).standard_normal((10, 2)))\n df2 = self.eval("df", local_dict={"df": df})\n tm.assert_frame_equal(df, df2)\n\n def test_failing_subscript_with_name_error(self):\n df = DataFrame(np.random.default_rng(2).standard_normal((5, 3))) # noqa: F841\n with pytest.raises(NameError, match="name 'x' is not defined"):\n self.eval("df[x > 2] > 2")\n\n def test_lhs_expression_subscript(self):\n df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))\n result = self.eval("(df + 1)[df > 2]", local_dict={"df": df})\n expected = (df + 1)[df > 2]\n tm.assert_frame_equal(result, expected)\n\n def test_attr_expression(self):\n df = DataFrame(\n np.random.default_rng(2).standard_normal((5, 3)), columns=list("abc")\n )\n expr1 = "df.a < df.b"\n expec1 = df.a < df.b\n expr2 = "df.a + df.b + df.c"\n expec2 = df.a + df.b + df.c\n expr3 = "df.a + df.b + df.c[df.b < 0]"\n expec3 = df.a + df.b + df.c[df.b < 0]\n exprs = expr1, expr2, expr3\n expecs = expec1, expec2, expec3\n for e, expec in zip(exprs, expecs):\n tm.assert_series_equal(expec, self.eval(e, local_dict={"df": df}))\n\n def test_assignment_fails(self):\n df = DataFrame(\n np.random.default_rng(2).standard_normal((5, 3)), columns=list("abc")\n )\n df2 = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))\n expr1 = "df = df2"\n msg = "cannot assign without a target object"\n with pytest.raises(ValueError, match=msg):\n self.eval(expr1, local_dict={"df": df, "df2": df2})\n\n def test_assignment_column_multiple_raise(self):\n df = DataFrame(\n np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")\n )\n # multiple assignees\n with pytest.raises(SyntaxError, match="invalid syntax"):\n df.eval("d c = a + b")\n\n def test_assignment_column_invalid_assign(self):\n df = DataFrame(\n np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")\n )\n # invalid assignees\n msg = "left hand side of an assignment must be a single name"\n with pytest.raises(SyntaxError, match=msg):\n df.eval("d,c = a + b")\n\n def test_assignment_column_invalid_assign_function_call(self):\n df = DataFrame(\n np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")\n )\n msg = "cannot assign to function call"\n with pytest.raises(SyntaxError, match=msg):\n df.eval('Timestamp("20131001") = a + b')\n\n def test_assignment_single_assign_existing(self):\n df = DataFrame(\n np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")\n )\n # single assignment - existing variable\n expected = df.copy()\n expected["a"] = expected["a"] + expected["b"]\n df.eval("a = a + b", inplace=True)\n tm.assert_frame_equal(df, expected)\n\n def test_assignment_single_assign_new(self):\n df = DataFrame(\n np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")\n )\n # single assignment - new variable\n expected = df.copy()\n expected["c"] = expected["a"] + expected["b"]\n df.eval("c = a + b", inplace=True)\n tm.assert_frame_equal(df, expected)\n\n def test_assignment_single_assign_local_overlap(self):\n df = DataFrame(\n np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")\n )\n df = df.copy()\n a = 1 # noqa: F841\n df.eval("a = 1 + b", inplace=True)\n\n expected = df.copy()\n expected["a"] = 1 + expected["b"]\n tm.assert_frame_equal(df, expected)\n\n def test_assignment_single_assign_name(self):\n df = DataFrame(\n np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")\n )\n\n a = 1 # noqa: F841\n old_a = df.a.copy()\n df.eval("a = a + b", inplace=True)\n result = old_a + df.b\n tm.assert_series_equal(result, df.a, check_names=False)\n assert result.name is None\n\n def test_assignment_multiple_raises(self):\n df = DataFrame(\n np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")\n )\n # multiple assignment\n df.eval("c = a + b", inplace=True)\n msg = "can only assign a single expression"\n with pytest.raises(SyntaxError, match=msg):\n df.eval("c = a = b")\n\n def test_assignment_explicit(self):\n df = DataFrame(\n np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")\n )\n # explicit targets\n self.eval("c = df.a + df.b", local_dict={"df": df}, target=df, inplace=True)\n expected = df.copy()\n expected["c"] = expected["a"] + expected["b"]\n tm.assert_frame_equal(df, expected)\n\n def test_column_in(self):\n # GH 11235\n df = DataFrame({"a": [11], "b": [-32]})\n result = df.eval("a in [11, -32]")\n expected = Series([True])\n # TODO: 2022-01-29: Name check failed with numexpr 2.7.3 in CI\n # but cannot reproduce locally\n tm.assert_series_equal(result, expected, check_names=False)\n\n @pytest.mark.xfail(reason="Unknown: Omitted test_ in name prior.")\n def test_assignment_not_inplace(self):\n # see gh-9297\n df = DataFrame(\n np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab")\n )\n\n actual = df.eval("c = a + b", inplace=False)\n assert actual is not None\n\n expected = df.copy()\n expected["c"] = expected["a"] + expected["b"]\n tm.assert_frame_equal(df, expected)\n\n def test_multi_line_expression(self, warn_copy_on_write):\n # GH 11149\n df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})\n expected = df.copy()\n\n expected["c"] = expected["a"] + expected["b"]\n expected["d"] = expected["c"] + expected["b"]\n answer = df.eval(\n """\n c = a + b\n d = c + b""",\n inplace=True,\n )\n tm.assert_frame_equal(expected, df)\n assert answer is None\n\n expected["a"] = expected["a"] - 1\n expected["e"] = expected["a"] + 2\n answer = df.eval(\n """\n a = a - 1\n e = a + 2""",\n inplace=True,\n )\n tm.assert_frame_equal(expected, df)\n assert answer is None\n\n # multi-line not valid if not all assignments\n msg = "Multi-line expressions are only valid if all expressions contain"\n with pytest.raises(ValueError, match=msg):\n df.eval(\n """\n a = b + 2\n b - 2""",\n inplace=False,\n )\n\n def test_multi_line_expression_not_inplace(self):\n # GH 11149\n df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})\n expected = df.copy()\n\n expected["c"] = expected["a"] + expected["b"]\n expected["d"] = expected["c"] + expected["b"]\n df = df.eval(\n """\n c = a + b\n d = c + b""",\n inplace=False,\n )\n tm.assert_frame_equal(expected, df)\n\n expected["a"] = expected["a"] - 1\n expected["e"] = expected["a"] + 2\n df = df.eval(\n """\n a = a - 1\n e = a + 2""",\n inplace=False,\n )\n tm.assert_frame_equal(expected, df)\n\n def test_multi_line_expression_local_variable(self):\n # GH 15342\n df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})\n expected = df.copy()\n\n local_var = 7\n expected["c"] = expected["a"] * local_var\n expected["d"] = expected["c"] + local_var\n answer = df.eval(\n """\n c = a * @local_var\n d = c + @local_var\n """,\n inplace=True,\n )\n tm.assert_frame_equal(expected, df)\n assert answer is None\n\n def test_multi_line_expression_callable_local_variable(self):\n # 26426\n df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})\n\n def local_func(a, b):\n return b\n\n expected = df.copy()\n expected["c"] = expected["a"] * local_func(1, 7)\n expected["d"] = expected["c"] + local_func(1, 7)\n answer = df.eval(\n """\n c = a * @local_func(1, 7)\n d = c + @local_func(1, 7)\n """,\n inplace=True,\n )\n tm.assert_frame_equal(expected, df)\n assert answer is None\n\n def test_multi_line_expression_callable_local_variable_with_kwargs(self):\n # 26426\n df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})\n\n def local_func(a, b):\n return b\n\n expected = df.copy()\n expected["c"] = expected["a"] * local_func(b=7, a=1)\n expected["d"] = expected["c"] + local_func(b=7, a=1)\n answer = df.eval(\n """\n c = a * @local_func(b=7, a=1)\n d = c + @local_func(b=7, a=1)\n """,\n inplace=True,\n )\n tm.assert_frame_equal(expected, df)\n assert answer is None\n\n def test_assignment_in_query(self):\n # GH 8664\n df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})\n df_orig = df.copy()\n msg = "cannot assign without a target object"\n with pytest.raises(ValueError, match=msg):\n df.query("a = 1")\n tm.assert_frame_equal(df, df_orig)\n\n def test_query_inplace(self):\n # see gh-11149\n df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})\n expected = df.copy()\n expected = expected[expected["a"] == 2]\n df.query("a == 2", inplace=True)\n tm.assert_frame_equal(expected, df)\n\n df = {}\n expected = {"a": 3}\n\n self.eval("a = 1 + 2", target=df, inplace=True)\n tm.assert_dict_equal(df, expected)\n\n @pytest.mark.parametrize("invalid_target", [1, "cat", [1, 2], np.array([]), (1, 3)])\n def test_cannot_item_assign(self, invalid_target):\n msg = "Cannot assign expression output to target"\n expression = "a = 1 + 2"\n\n with pytest.raises(ValueError, match=msg):\n self.eval(expression, target=invalid_target, inplace=True)\n\n if hasattr(invalid_target, "copy"):\n with pytest.raises(ValueError, match=msg):\n self.eval(expression, target=invalid_target, inplace=False)\n\n @pytest.mark.parametrize("invalid_target", [1, "cat", (1, 3)])\n def test_cannot_copy_item(self, invalid_target):\n msg = "Cannot return a copy of the target"\n expression = "a = 1 + 2"\n\n with pytest.raises(ValueError, match=msg):\n self.eval(expression, target=invalid_target, inplace=False)\n\n @pytest.mark.parametrize("target", [1, "cat", [1, 2], np.array([]), (1, 3), {1: 2}])\n def test_inplace_no_assignment(self, target):\n expression = "1 + 2"\n\n assert self.eval(expression, target=target, inplace=False) == 3\n\n msg = "Cannot operate inplace if there is no assignment"\n with pytest.raises(ValueError, match=msg):\n self.eval(expression, target=target, inplace=True)\n\n def test_basic_period_index_boolean_expression(self):\n df = DataFrame(\n np.random.default_rng(2).standard_normal((2, 2)),\n columns=period_range("2020-01-01", freq="D", periods=2),\n )\n e = df < 2\n r = self.eval("df < 2", local_dict={"df": df})\n x = df < 2\n\n tm.assert_frame_equal(r, e)\n tm.assert_frame_equal(x, e)\n\n def test_basic_period_index_subscript_expression(self):\n df = DataFrame(\n np.random.default_rng(2).standard_normal((2, 2)),\n columns=period_range("2020-01-01", freq="D", periods=2),\n )\n r = self.eval("df[df < 2 + 3]", local_dict={"df": df})\n e = df[df < 2 + 3]\n tm.assert_frame_equal(r, e)\n\n def test_nested_period_index_subscript_expression(self):\n df = DataFrame(\n np.random.default_rng(2).standard_normal((2, 2)),\n columns=period_range("2020-01-01", freq="D", periods=2),\n )\n r = self.eval("df[df[df < 2] < 2] + df * 2", local_dict={"df": df})\n e = df[df[df < 2] < 2] + df * 2\n tm.assert_frame_equal(r, e)\n\n def test_date_boolean(self, engine, parser):\n df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))\n df["dates1"] = date_range("1/1/2012", periods=5)\n res = self.eval(\n "df.dates1 < 20130101",\n local_dict={"df": df},\n engine=engine,\n parser=parser,\n )\n expec = df.dates1 < "20130101"\n tm.assert_series_equal(res, expec, check_names=False)\n\n def test_simple_in_ops(self, engine, parser):\n if parser != "python":\n res = pd.eval("1 in [1, 2]", engine=engine, parser=parser)\n assert res\n\n res = pd.eval("2 in (1, 2)", engine=engine, parser=parser)\n assert res\n\n res = pd.eval("3 in (1, 2)", engine=engine, parser=parser)\n assert not res\n\n res = pd.eval("3 not in (1, 2)", engine=engine, parser=parser)\n assert res\n\n res = pd.eval("[3] not in (1, 2)", engine=engine, parser=parser)\n assert res\n\n res = pd.eval("[3] in ([3], 2)", engine=engine, parser=parser)\n assert res\n\n res = pd.eval("[[3]] in [[[3]], 2]", engine=engine, parser=parser)\n assert res\n\n res = pd.eval("(3,) in [(3,), 2]", engine=engine, parser=parser)\n assert res\n\n res = pd.eval("(3,) not in [(3,), 2]", engine=engine, parser=parser)\n assert not res\n\n res = pd.eval("[(3,)] in [[(3,)], 2]", engine=engine, parser=parser)\n assert res\n else:\n msg = "'In' nodes are not implemented"\n with pytest.raises(NotImplementedError, match=msg):\n pd.eval("1 in [1, 2]", engine=engine, parser=parser)\n with pytest.raises(NotImplementedError, match=msg):\n pd.eval("2 in (1, 2)", engine=engine, parser=parser)\n with pytest.raises(NotImplementedError, match=msg):\n pd.eval("3 in (1, 2)", engine=engine, parser=parser)\n with pytest.raises(NotImplementedError, match=msg):\n pd.eval("[(3,)] in (1, 2, [(3,)])", engine=engine, parser=parser)\n msg = "'NotIn' nodes are not implemented"\n with pytest.raises(NotImplementedError, match=msg):\n pd.eval("3 not in (1, 2)", engine=engine, parser=parser)\n with pytest.raises(NotImplementedError, match=msg):\n pd.eval("[3] not in (1, 2, [[3]])", engine=engine, parser=parser)\n\n def test_check_many_exprs(self, engine, parser):\n a = 1 # noqa: F841\n expr = " * ".join("a" * 33)\n expected = 1\n res = pd.eval(expr, engine=engine, parser=parser)\n assert res == expected\n\n @pytest.mark.parametrize(\n "expr",\n [\n "df > 2 and df > 3",\n "df > 2 or df > 3",\n "not df > 2",\n ],\n )\n def test_fails_and_or_not(self, expr, engine, parser):\n df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)))\n if parser == "python":\n msg = "'BoolOp' nodes are not implemented"\n if "not" in expr:\n msg = "'Not' nodes are not implemented"\n\n with pytest.raises(NotImplementedError, match=msg):\n pd.eval(\n expr,\n local_dict={"df": df},\n parser=parser,\n engine=engine,\n )\n else:\n # smoke-test, should not raise\n pd.eval(\n expr,\n local_dict={"df": df},\n parser=parser,\n engine=engine,\n )\n\n @pytest.mark.parametrize("char", ["|", "&"])\n def test_fails_ampersand_pipe(self, char, engine, parser):\n df = DataFrame(np.random.default_rng(2).standard_normal((5, 3))) # noqa: F841\n ex = f"(df + 2)[df > 1] > 0 {char} (df > 0)"\n if parser == "python":\n msg = "cannot evaluate scalar only bool ops"\n with pytest.raises(NotImplementedError, match=msg):\n pd.eval(ex, parser=parser, engine=engine)\n else:\n # smoke-test, should not raise\n pd.eval(ex, parser=parser, engine=engine)\n\n\nclass TestMath:\n def eval(self, *args, **kwargs):\n kwargs["level"] = kwargs.pop("level", 0) + 1\n return pd.eval(*args, **kwargs)\n\n @pytest.mark.skipif(\n not NUMEXPR_INSTALLED, reason="Unary ops only implemented for numexpr"\n )\n @pytest.mark.parametrize("fn", _unary_math_ops)\n def test_unary_functions(self, fn):\n df = DataFrame({"a": np.random.default_rng(2).standard_normal(10)})\n a = df.a\n\n expr = f"{fn}(a)"\n got = self.eval(expr)\n with np.errstate(all="ignore"):\n expect = getattr(np, fn)(a)\n tm.assert_series_equal(got, expect, check_names=False)\n\n @pytest.mark.parametrize("fn", _binary_math_ops)\n def test_binary_functions(self, fn):\n df = DataFrame(\n {\n "a": np.random.default_rng(2).standard_normal(10),\n "b": np.random.default_rng(2).standard_normal(10),\n }\n )\n a = df.a\n b = df.b\n\n expr = f"{fn}(a, b)"\n got = self.eval(expr)\n with np.errstate(all="ignore"):\n expect = getattr(np, fn)(a, b)\n tm.assert_almost_equal(got, expect, check_names=False)\n\n def test_df_use_case(self, engine, parser):\n df = DataFrame(\n {\n "a": np.random.default_rng(2).standard_normal(10),\n "b": np.random.default_rng(2).standard_normal(10),\n }\n )\n df.eval(\n "e = arctan2(sin(a), b)",\n engine=engine,\n parser=parser,\n inplace=True,\n )\n got = df.e\n expect = np.arctan2(np.sin(df.a), df.b)\n tm.assert_series_equal(got, expect, check_names=False)\n\n def test_df_arithmetic_subexpression(self, engine, parser):\n df = DataFrame(\n {\n "a": np.random.default_rng(2).standard_normal(10),\n "b": np.random.default_rng(2).standard_normal(10),\n }\n )\n df.eval("e = sin(a + b)", engine=engine, parser=parser, inplace=True)\n got = df.e\n expect = np.sin(df.a + df.b)\n tm.assert_series_equal(got, expect, check_names=False)\n\n @pytest.mark.parametrize(\n "dtype, expect_dtype",\n [\n (np.int32, np.float64),\n (np.int64, np.float64),\n (np.float32, np.float32),\n (np.float64, np.float64),\n pytest.param(np.complex128, np.complex128, marks=td.skip_if_windows),\n ],\n )\n def test_result_types(self, dtype, expect_dtype, engine, parser):\n # xref https://github.com/pandas-dev/pandas/issues/12293\n # this fails on Windows, apparently a floating point precision issue\n\n # Did not test complex64 because DataFrame is converting it to\n # complex128. Due to https://github.com/pandas-dev/pandas/issues/10952\n df = DataFrame(\n {"a": np.random.default_rng(2).standard_normal(10).astype(dtype)}\n )\n assert df.a.dtype == dtype\n df.eval("b = sin(a)", engine=engine, parser=parser, inplace=True)\n got = df.b\n expect = np.sin(df.a)\n assert expect.dtype == got.dtype\n assert expect_dtype == got.dtype\n tm.assert_series_equal(got, expect, check_names=False)\n\n def test_undefined_func(self, engine, parser):\n df = DataFrame({"a": np.random.default_rng(2).standard_normal(10)})\n msg = '"mysin" is not a supported function'\n\n with pytest.raises(ValueError, match=msg):\n df.eval("mysin(a)", engine=engine, parser=parser)\n\n def test_keyword_arg(self, engine, parser):\n df = DataFrame({"a": np.random.default_rng(2).standard_normal(10)})\n msg = 'Function "sin" does not support keyword arguments'\n\n with pytest.raises(TypeError, match=msg):\n df.eval("sin(x=a)", engine=engine, parser=parser)\n\n\n_var_s = np.random.default_rng(2).standard_normal(10)\n\n\nclass TestScope:\n def test_global_scope(self, engine, parser):\n e = "_var_s * 2"\n tm.assert_numpy_array_equal(\n _var_s * 2, pd.eval(e, engine=engine, parser=parser)\n )\n\n def test_no_new_locals(self, engine, parser):\n x = 1\n lcls = locals().copy()\n pd.eval("x + 1", local_dict=lcls, engine=engine, parser=parser)\n lcls2 = locals().copy()\n lcls2.pop("lcls")\n assert lcls == lcls2\n\n def test_no_new_globals(self, engine, parser):\n x = 1 # noqa: F841\n gbls = globals().copy()\n pd.eval("x + 1", engine=engine, parser=parser)\n gbls2 = globals().copy()\n assert gbls == gbls2\n\n def test_empty_locals(self, engine, parser):\n # GH 47084\n x = 1 # noqa: F841\n msg = "name 'x' is not defined"\n with pytest.raises(UndefinedVariableError, match=msg):\n pd.eval("x + 1", engine=engine, parser=parser, local_dict={})\n\n def test_empty_globals(self, engine, parser):\n # GH 47084\n msg = "name '_var_s' is not defined"\n e = "_var_s * 2"\n with pytest.raises(UndefinedVariableError, match=msg):\n pd.eval(e, engine=engine, parser=parser, global_dict={})\n\n\n@td.skip_if_no("numexpr")\ndef test_invalid_engine():\n msg = "Invalid engine 'asdf' passed"\n with pytest.raises(KeyError, match=msg):\n pd.eval("x + y", local_dict={"x": 1, "y": 2}, engine="asdf")\n\n\n@td.skip_if_no("numexpr")\n@pytest.mark.parametrize(\n ("use_numexpr", "expected"),\n (\n (True, "numexpr"),\n (False, "python"),\n ),\n)\ndef test_numexpr_option_respected(use_numexpr, expected):\n # GH 32556\n from pandas.core.computation.eval import _check_engine\n\n with pd.option_context("compute.use_numexpr", use_numexpr):\n result = _check_engine(None)\n assert result == expected\n\n\n@td.skip_if_no("numexpr")\ndef test_numexpr_option_incompatible_op():\n # GH 32556\n with pd.option_context("compute.use_numexpr", False):\n df = DataFrame(\n {"A": [True, False, True, False, None, None], "B": [1, 2, 3, 4, 5, 6]}\n )\n result = df.query("A.isnull()")\n expected = DataFrame({"A": [None, None], "B": [5, 6]}, index=[4, 5])\n tm.assert_frame_equal(result, expected)\n\n\n@td.skip_if_no("numexpr")\ndef test_invalid_parser():\n msg = "Invalid parser 'asdf' passed"\n with pytest.raises(KeyError, match=msg):\n pd.eval("x + y", local_dict={"x": 1, "y": 2}, parser="asdf")\n\n\n_parsers: dict[str, type[BaseExprVisitor]] = {\n "python": PythonExprVisitor,\n "pytables": pytables.PyTablesExprVisitor,\n "pandas": PandasExprVisitor,\n}\n\n\n@pytest.mark.parametrize("engine", ENGINES)\n@pytest.mark.parametrize("parser", _parsers)\ndef test_disallowed_nodes(engine, parser):\n VisitorClass = _parsers[parser]\n inst = VisitorClass("x + 1", engine, parser)\n\n for ops in VisitorClass.unsupported_nodes:\n msg = "nodes are not implemented"\n with pytest.raises(NotImplementedError, match=msg):\n getattr(inst, ops)()\n\n\ndef test_syntax_error_exprs(engine, parser):\n e = "s +"\n with pytest.raises(SyntaxError, match="invalid syntax"):\n pd.eval(e, engine=engine, parser=parser)\n\n\ndef test_name_error_exprs(engine, parser):\n e = "s + t"\n msg = "name 's' is not defined"\n with pytest.raises(NameError, match=msg):\n pd.eval(e, engine=engine, parser=parser)\n\n\n@pytest.mark.parametrize("express", ["a + @b", "@a + b", "@a + @b"])\ndef test_invalid_local_variable_reference(engine, parser, express):\n a, b = 1, 2 # noqa: F841\n\n if parser != "pandas":\n with pytest.raises(SyntaxError, match="The '@' prefix is only"):\n pd.eval(express, engine=engine, parser=parser)\n else:\n with pytest.raises(SyntaxError, match="The '@' prefix is not"):\n pd.eval(express, engine=engine, parser=parser)\n\n\ndef test_numexpr_builtin_raises(engine, parser):\n sin, dotted_line = 1, 2\n if engine == "numexpr":\n msg = "Variables in expression .+"\n with pytest.raises(NumExprClobberingError, match=msg):\n pd.eval("sin + dotted_line", engine=engine, parser=parser)\n else:\n res = pd.eval("sin + dotted_line", engine=engine, parser=parser)\n assert res == sin + dotted_line\n\n\ndef test_bad_resolver_raises(engine, parser):\n cannot_resolve = 42, 3.0\n with pytest.raises(TypeError, match="Resolver of type .+"):\n pd.eval("1 + 2", resolvers=cannot_resolve, engine=engine, parser=parser)\n\n\ndef test_empty_string_raises(engine, parser):\n # GH 13139\n with pytest.raises(ValueError, match="expr cannot be an empty string"):\n pd.eval("", engine=engine, parser=parser)\n\n\ndef test_more_than_one_expression_raises(engine, parser):\n with pytest.raises(SyntaxError, match="only a single expression is allowed"):\n pd.eval("1 + 1; 2 + 2", engine=engine, parser=parser)\n\n\n@pytest.mark.parametrize("cmp", ("and", "or"))\n@pytest.mark.parametrize("lhs", (int, float))\n@pytest.mark.parametrize("rhs", (int, float))\ndef test_bool_ops_fails_on_scalars(lhs, cmp, rhs, engine, parser):\n gen = {\n int: lambda: np.random.default_rng(2).integers(10),\n float: np.random.default_rng(2).standard_normal,\n }\n\n mid = gen[lhs]() # noqa: F841\n lhs = gen[lhs]()\n rhs = gen[rhs]()\n\n ex1 = f"lhs {cmp} mid {cmp} rhs"\n ex2 = f"lhs {cmp} mid and mid {cmp} rhs"\n ex3 = f"(lhs {cmp} mid) & (mid {cmp} rhs)"\n for ex in (ex1, ex2, ex3):\n msg = "cannot evaluate scalar only bool ops|'BoolOp' nodes are not"\n with pytest.raises(NotImplementedError, match=msg):\n pd.eval(ex, engine=engine, parser=parser)\n\n\n@pytest.mark.parametrize(\n "other",\n [\n "'x'",\n "...",\n ],\n)\ndef test_equals_various(other):\n df = DataFrame({"A": ["a", "b", "c"]}, dtype=object)\n result = df.eval(f"A == {other}")\n expected = Series([False, False, False], name="A")\n if USE_NUMEXPR:\n # https://github.com/pandas-dev/pandas/issues/10239\n # lose name with numexpr engine. Remove when that's fixed.\n expected.name = None\n tm.assert_series_equal(result, expected)\n\n\ndef test_inf(engine, parser):\n s = "inf + 1"\n expected = np.inf\n result = pd.eval(s, engine=engine, parser=parser)\n assert result == expected\n\n\n@pytest.mark.parametrize("column", ["Temp(°C)", "Capacitance(μF)"])\ndef test_query_token(engine, column):\n # See: https://github.com/pandas-dev/pandas/pull/42826\n df = DataFrame(\n np.random.default_rng(2).standard_normal((5, 2)), columns=[column, "b"]\n )\n expected = df[df[column] > 5]\n query_string = f"`{column}` > 5"\n result = df.query(query_string, engine=engine)\n tm.assert_frame_equal(result, expected)\n\n\ndef test_negate_lt_eq_le(engine, parser):\n df = DataFrame([[0, 10], [1, 20]], columns=["cat", "count"])\n expected = df[~(df.cat > 0)]\n\n result = df.query("~(cat > 0)", engine=engine, parser=parser)\n tm.assert_frame_equal(result, expected)\n\n if parser == "python":\n msg = "'Not' nodes are not implemented"\n with pytest.raises(NotImplementedError, match=msg):\n df.query("not (cat > 0)", engine=engine, parser=parser)\n else:\n result = df.query("not (cat > 0)", engine=engine, parser=parser)\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "column",\n DEFAULT_GLOBALS.keys(),\n)\ndef test_eval_no_support_column_name(request, column):\n # GH 44603\n if column in ["True", "False", "inf", "Inf"]:\n request.applymarker(\n pytest.mark.xfail(\n raises=KeyError,\n reason=f"GH 47859 DataFrame eval not supported with {column}",\n )\n )\n\n df = DataFrame(\n np.random.default_rng(2).integers(0, 100, size=(10, 2)),\n columns=[column, "col1"],\n )\n expected = df[df[column] > 6]\n result = df.query(f"{column}>6")\n\n tm.assert_frame_equal(result, expected)\n\n\ndef test_set_inplace(using_copy_on_write, warn_copy_on_write):\n # https://github.com/pandas-dev/pandas/issues/47449\n # Ensure we don't only update the DataFrame inplace, but also the actual\n # column values, such that references to this column also get updated\n df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]})\n result_view = df[:]\n ser = df["A"]\n with tm.assert_cow_warning(warn_copy_on_write):\n df.eval("A = B + C", inplace=True)\n expected = DataFrame({"A": [11, 13, 15], "B": [4, 5, 6], "C": [7, 8, 9]})\n tm.assert_frame_equal(df, expected)\n if not using_copy_on_write:\n tm.assert_series_equal(ser, expected["A"])\n tm.assert_series_equal(result_view["A"], expected["A"])\n else:\n expected = Series([1, 2, 3], name="A")\n tm.assert_series_equal(ser, expected)\n tm.assert_series_equal(result_view["A"], expected)\n\n\nclass TestValidate:\n @pytest.mark.parametrize("value", [1, "True", [1, 2, 3], 5.0])\n def test_validate_bool_args(self, value):\n msg = 'For argument "inplace" expected type bool, received type'\n with pytest.raises(ValueError, match=msg):\n pd.eval("2+2", inplace=value)\n
.venv\Lib\site-packages\pandas\tests\computation\test_eval.py
test_eval.py
Python
71,699
0.75
0.1125
0.057861
python-kit
421
2024-05-08T00:13:50.987625
BSD-3-Clause
true
5ff0f78a5a36cc70753bf95adc057e29
\n\n
.venv\Lib\site-packages\pandas\tests\computation\__pycache__\test_compat.cpython-313.pyc
test_compat.cpython-313.pyc
Other
1,584
0.95
0
0
awesome-app
143
2024-08-10T07:39:41.738445
BSD-3-Clause
true
d57c84e3566f3a7af65a63ed5f6a9357
\n\n
.venv\Lib\site-packages\pandas\tests\computation\__pycache__\test_eval.cpython-313.pyc
test_eval.cpython-313.pyc
Other
109,440
0.75
0.012015
0.001876
python-kit
406
2025-05-20T09:40:35.948561
Apache-2.0
true
94c7cb31010fbea29a07eb08296b0cb9
\n\n
.venv\Lib\site-packages\pandas\tests\computation\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
199
0.7
0
0
node-utils
979
2025-06-14T07:24:39.646703
Apache-2.0
true
e08e029e6e669f6dd75b36a37d8902b0
import pytest\n\nfrom pandas._config import config as cf\nfrom pandas._config.config import OptionError\n\nimport pandas as pd\nimport pandas._testing as tm\n\n\nclass TestConfig:\n @pytest.fixture(autouse=True)\n def clean_config(self, monkeypatch):\n with monkeypatch.context() as m:\n m.setattr(cf, "_global_config", {})\n m.setattr(cf, "options", cf.DictWrapper(cf._global_config))\n m.setattr(cf, "_deprecated_options", {})\n m.setattr(cf, "_registered_options", {})\n\n # Our test fixture in conftest.py sets "chained_assignment"\n # to "raise" only after all test methods have been setup.\n # However, after this setup, there is no longer any\n # "chained_assignment" option, so re-register it.\n cf.register_option("chained_assignment", "raise")\n yield\n\n def test_api(self):\n # the pandas object exposes the user API\n assert hasattr(pd, "get_option")\n assert hasattr(pd, "set_option")\n assert hasattr(pd, "reset_option")\n assert hasattr(pd, "describe_option")\n\n def test_is_one_of_factory(self):\n v = cf.is_one_of_factory([None, 12])\n\n v(12)\n v(None)\n msg = r"Value must be one of None\|12"\n with pytest.raises(ValueError, match=msg):\n v(1.1)\n\n def test_register_option(self):\n cf.register_option("a", 1, "doc")\n\n # can't register an already registered option\n msg = "Option 'a' has already been registered"\n with pytest.raises(OptionError, match=msg):\n cf.register_option("a", 1, "doc")\n\n # can't register an already registered option\n msg = "Path prefix to option 'a' is already an option"\n with pytest.raises(OptionError, match=msg):\n cf.register_option("a.b.c.d1", 1, "doc")\n with pytest.raises(OptionError, match=msg):\n cf.register_option("a.b.c.d2", 1, "doc")\n\n # no python keywords\n msg = "for is a python keyword"\n with pytest.raises(ValueError, match=msg):\n cf.register_option("for", 0)\n with pytest.raises(ValueError, match=msg):\n cf.register_option("a.for.b", 0)\n # must be valid identifier (ensure attribute access works)\n msg = "oh my goddess! is not a valid identifier"\n with pytest.raises(ValueError, match=msg):\n cf.register_option("Oh my Goddess!", 0)\n\n # we can register options several levels deep\n # without predefining the intermediate steps\n # and we can define differently named options\n # in the same namespace\n cf.register_option("k.b.c.d1", 1, "doc")\n cf.register_option("k.b.c.d2", 1, "doc")\n\n def test_describe_option(self):\n cf.register_option("a", 1, "doc")\n cf.register_option("b", 1, "doc2")\n cf.deprecate_option("b")\n\n cf.register_option("c.d.e1", 1, "doc3")\n cf.register_option("c.d.e2", 1, "doc4")\n cf.register_option("f", 1)\n cf.register_option("g.h", 1)\n cf.register_option("k", 2)\n cf.deprecate_option("g.h", rkey="k")\n cf.register_option("l", "foo")\n\n # non-existent keys raise KeyError\n msg = r"No such keys\(s\)"\n with pytest.raises(OptionError, match=msg):\n cf.describe_option("no.such.key")\n\n # we can get the description for any key we registered\n assert "doc" in cf.describe_option("a", _print_desc=False)\n assert "doc2" in cf.describe_option("b", _print_desc=False)\n assert "precated" in cf.describe_option("b", _print_desc=False)\n assert "doc3" in cf.describe_option("c.d.e1", _print_desc=False)\n assert "doc4" in cf.describe_option("c.d.e2", _print_desc=False)\n\n # if no doc is specified we get a default message\n # saying "description not available"\n assert "available" in cf.describe_option("f", _print_desc=False)\n assert "available" in cf.describe_option("g.h", _print_desc=False)\n assert "precated" in cf.describe_option("g.h", _print_desc=False)\n assert "k" in cf.describe_option("g.h", _print_desc=False)\n\n # default is reported\n assert "foo" in cf.describe_option("l", _print_desc=False)\n # current value is reported\n assert "bar" not in cf.describe_option("l", _print_desc=False)\n cf.set_option("l", "bar")\n assert "bar" in cf.describe_option("l", _print_desc=False)\n\n def test_case_insensitive(self):\n cf.register_option("KanBAN", 1, "doc")\n\n assert "doc" in cf.describe_option("kanbaN", _print_desc=False)\n assert cf.get_option("kanBaN") == 1\n cf.set_option("KanBan", 2)\n assert cf.get_option("kAnBaN") == 2\n\n # gets of non-existent keys fail\n msg = r"No such keys\(s\): 'no_such_option'"\n with pytest.raises(OptionError, match=msg):\n cf.get_option("no_such_option")\n cf.deprecate_option("KanBan")\n\n assert cf._is_deprecated("kAnBaN")\n\n def test_get_option(self):\n cf.register_option("a", 1, "doc")\n cf.register_option("b.c", "hullo", "doc2")\n cf.register_option("b.b", None, "doc2")\n\n # gets of existing keys succeed\n assert cf.get_option("a") == 1\n assert cf.get_option("b.c") == "hullo"\n assert cf.get_option("b.b") is None\n\n # gets of non-existent keys fail\n msg = r"No such keys\(s\): 'no_such_option'"\n with pytest.raises(OptionError, match=msg):\n cf.get_option("no_such_option")\n\n def test_set_option(self):\n cf.register_option("a", 1, "doc")\n cf.register_option("b.c", "hullo", "doc2")\n cf.register_option("b.b", None, "doc2")\n\n assert cf.get_option("a") == 1\n assert cf.get_option("b.c") == "hullo"\n assert cf.get_option("b.b") is None\n\n cf.set_option("a", 2)\n cf.set_option("b.c", "wurld")\n cf.set_option("b.b", 1.1)\n\n assert cf.get_option("a") == 2\n assert cf.get_option("b.c") == "wurld"\n assert cf.get_option("b.b") == 1.1\n\n msg = r"No such keys\(s\): 'no.such.key'"\n with pytest.raises(OptionError, match=msg):\n cf.set_option("no.such.key", None)\n\n def test_set_option_empty_args(self):\n msg = "Must provide an even number of non-keyword arguments"\n with pytest.raises(ValueError, match=msg):\n cf.set_option()\n\n def test_set_option_uneven_args(self):\n msg = "Must provide an even number of non-keyword arguments"\n with pytest.raises(ValueError, match=msg):\n cf.set_option("a.b", 2, "b.c")\n\n def test_set_option_invalid_single_argument_type(self):\n msg = "Must provide an even number of non-keyword arguments"\n with pytest.raises(ValueError, match=msg):\n cf.set_option(2)\n\n def test_set_option_multiple(self):\n cf.register_option("a", 1, "doc")\n cf.register_option("b.c", "hullo", "doc2")\n cf.register_option("b.b", None, "doc2")\n\n assert cf.get_option("a") == 1\n assert cf.get_option("b.c") == "hullo"\n assert cf.get_option("b.b") is None\n\n cf.set_option("a", "2", "b.c", None, "b.b", 10.0)\n\n assert cf.get_option("a") == "2"\n assert cf.get_option("b.c") is None\n assert cf.get_option("b.b") == 10.0\n\n def test_validation(self):\n cf.register_option("a", 1, "doc", validator=cf.is_int)\n cf.register_option("d", 1, "doc", validator=cf.is_nonnegative_int)\n cf.register_option("b.c", "hullo", "doc2", validator=cf.is_text)\n\n msg = "Value must have type '<class 'int'>'"\n with pytest.raises(ValueError, match=msg):\n cf.register_option("a.b.c.d2", "NO", "doc", validator=cf.is_int)\n\n cf.set_option("a", 2) # int is_int\n cf.set_option("b.c", "wurld") # str is_str\n cf.set_option("d", 2)\n cf.set_option("d", None) # non-negative int can be None\n\n # None not is_int\n with pytest.raises(ValueError, match=msg):\n cf.set_option("a", None)\n with pytest.raises(ValueError, match=msg):\n cf.set_option("a", "ab")\n\n msg = "Value must be a nonnegative integer or None"\n with pytest.raises(ValueError, match=msg):\n cf.register_option("a.b.c.d3", "NO", "doc", validator=cf.is_nonnegative_int)\n with pytest.raises(ValueError, match=msg):\n cf.register_option("a.b.c.d3", -2, "doc", validator=cf.is_nonnegative_int)\n\n msg = r"Value must be an instance of <class 'str'>\|<class 'bytes'>"\n with pytest.raises(ValueError, match=msg):\n cf.set_option("b.c", 1)\n\n validator = cf.is_one_of_factory([None, cf.is_callable])\n cf.register_option("b", lambda: None, "doc", validator=validator)\n # pylint: disable-next=consider-using-f-string\n cf.set_option("b", "%.1f".format) # Formatter is callable\n cf.set_option("b", None) # Formatter is none (default)\n with pytest.raises(ValueError, match="Value must be a callable"):\n cf.set_option("b", "%.1f")\n\n def test_reset_option(self):\n cf.register_option("a", 1, "doc", validator=cf.is_int)\n cf.register_option("b.c", "hullo", "doc2", validator=cf.is_str)\n assert cf.get_option("a") == 1\n assert cf.get_option("b.c") == "hullo"\n\n cf.set_option("a", 2)\n cf.set_option("b.c", "wurld")\n assert cf.get_option("a") == 2\n assert cf.get_option("b.c") == "wurld"\n\n cf.reset_option("a")\n assert cf.get_option("a") == 1\n assert cf.get_option("b.c") == "wurld"\n cf.reset_option("b.c")\n assert cf.get_option("a") == 1\n assert cf.get_option("b.c") == "hullo"\n\n def test_reset_option_all(self):\n cf.register_option("a", 1, "doc", validator=cf.is_int)\n cf.register_option("b.c", "hullo", "doc2", validator=cf.is_str)\n assert cf.get_option("a") == 1\n assert cf.get_option("b.c") == "hullo"\n\n cf.set_option("a", 2)\n cf.set_option("b.c", "wurld")\n assert cf.get_option("a") == 2\n assert cf.get_option("b.c") == "wurld"\n\n cf.reset_option("all")\n assert cf.get_option("a") == 1\n assert cf.get_option("b.c") == "hullo"\n\n def test_deprecate_option(self):\n # we can deprecate non-existent options\n cf.deprecate_option("foo")\n\n assert cf._is_deprecated("foo")\n with tm.assert_produces_warning(FutureWarning, match="deprecated"):\n with pytest.raises(KeyError, match="No such keys.s.: 'foo'"):\n cf.get_option("foo")\n\n cf.register_option("a", 1, "doc", validator=cf.is_int)\n cf.register_option("b.c", "hullo", "doc2")\n cf.register_option("foo", "hullo", "doc2")\n\n cf.deprecate_option("a", removal_ver="nifty_ver")\n with tm.assert_produces_warning(FutureWarning, match="eprecated.*nifty_ver"):\n cf.get_option("a")\n\n msg = "Option 'a' has already been defined as deprecated"\n with pytest.raises(OptionError, match=msg):\n cf.deprecate_option("a")\n\n cf.deprecate_option("b.c", "zounds!")\n with tm.assert_produces_warning(FutureWarning, match="zounds!"):\n cf.get_option("b.c")\n\n # test rerouting keys\n cf.register_option("d.a", "foo", "doc2")\n cf.register_option("d.dep", "bar", "doc2")\n assert cf.get_option("d.a") == "foo"\n assert cf.get_option("d.dep") == "bar"\n\n cf.deprecate_option("d.dep", rkey="d.a") # reroute d.dep to d.a\n with tm.assert_produces_warning(FutureWarning, match="eprecated"):\n assert cf.get_option("d.dep") == "foo"\n\n with tm.assert_produces_warning(FutureWarning, match="eprecated"):\n cf.set_option("d.dep", "baz") # should overwrite "d.a"\n\n with tm.assert_produces_warning(FutureWarning, match="eprecated"):\n assert cf.get_option("d.dep") == "baz"\n\n def test_config_prefix(self):\n with cf.config_prefix("base"):\n cf.register_option("a", 1, "doc1")\n cf.register_option("b", 2, "doc2")\n assert cf.get_option("a") == 1\n assert cf.get_option("b") == 2\n\n cf.set_option("a", 3)\n cf.set_option("b", 4)\n assert cf.get_option("a") == 3\n assert cf.get_option("b") == 4\n\n assert cf.get_option("base.a") == 3\n assert cf.get_option("base.b") == 4\n assert "doc1" in cf.describe_option("base.a", _print_desc=False)\n assert "doc2" in cf.describe_option("base.b", _print_desc=False)\n\n cf.reset_option("base.a")\n cf.reset_option("base.b")\n\n with cf.config_prefix("base"):\n assert cf.get_option("a") == 1\n assert cf.get_option("b") == 2\n\n def test_callback(self):\n k = [None]\n v = [None]\n\n def callback(key):\n k.append(key)\n v.append(cf.get_option(key))\n\n cf.register_option("d.a", "foo", cb=callback)\n cf.register_option("d.b", "foo", cb=callback)\n\n del k[-1], v[-1]\n cf.set_option("d.a", "fooz")\n assert k[-1] == "d.a"\n assert v[-1] == "fooz"\n\n del k[-1], v[-1]\n cf.set_option("d.b", "boo")\n assert k[-1] == "d.b"\n assert v[-1] == "boo"\n\n del k[-1], v[-1]\n cf.reset_option("d.b")\n assert k[-1] == "d.b"\n\n def test_set_ContextManager(self):\n def eq(val):\n assert cf.get_option("a") == val\n\n cf.register_option("a", 0)\n eq(0)\n with cf.option_context("a", 15):\n eq(15)\n with cf.option_context("a", 25):\n eq(25)\n eq(15)\n eq(0)\n\n cf.set_option("a", 17)\n eq(17)\n\n # Test that option_context can be used as a decorator too (#34253).\n @cf.option_context("a", 123)\n def f():\n eq(123)\n\n f()\n\n def test_attribute_access(self):\n holder = []\n\n def f3(key):\n holder.append(True)\n\n cf.register_option("a", 0)\n cf.register_option("c", 0, cb=f3)\n options = cf.options\n\n assert options.a == 0\n with cf.option_context("a", 15):\n assert options.a == 15\n\n options.a = 500\n assert cf.get_option("a") == 500\n\n cf.reset_option("a")\n assert options.a == cf.get_option("a", 0)\n\n msg = "You can only set the value of existing options"\n with pytest.raises(OptionError, match=msg):\n options.b = 1\n with pytest.raises(OptionError, match=msg):\n options.display = 1\n\n # make sure callback kicks when using this form of setting\n options.c = 1\n assert len(holder) == 1\n\n def test_option_context_scope(self):\n # Ensure that creating a context does not affect the existing\n # environment as it is supposed to be used with the `with` statement.\n # See https://github.com/pandas-dev/pandas/issues/8514\n\n original_value = 60\n context_value = 10\n option_name = "a"\n\n cf.register_option(option_name, original_value)\n\n # Ensure creating contexts didn't affect the current context.\n ctx = cf.option_context(option_name, context_value)\n assert cf.get_option(option_name) == original_value\n\n # Ensure the correct value is available inside the context.\n with ctx:\n assert cf.get_option(option_name) == context_value\n\n # Ensure the current context is reset\n assert cf.get_option(option_name) == original_value\n\n def test_dictwrapper_getattr(self):\n options = cf.options\n # GH 19789\n with pytest.raises(OptionError, match="No such option"):\n options.bananas\n assert not hasattr(options, "bananas")\n
.venv\Lib\site-packages\pandas\tests\config\test_config.py
test_config.py
Python
15,858
0.95
0.080092
0.101449
node-utils
750
2024-05-12T13:00:20.169997
MIT
true
6e3bb6169ba0328e45998ff0f7bd5f50
import codecs\nimport locale\nimport os\n\nimport pytest\n\nfrom pandas._config.localization import (\n can_set_locale,\n get_locales,\n set_locale,\n)\n\nfrom pandas.compat import ISMUSL\n\nimport pandas as pd\n\n_all_locales = get_locales()\n_current_locale = locale.setlocale(locale.LC_ALL) # getlocale() is wrong, see GH#46595\n\n# Don't run any of these tests if we have no locales.\npytestmark = pytest.mark.skipif(not _all_locales, reason="Need locales")\n\n_skip_if_only_one_locale = pytest.mark.skipif(\n len(_all_locales) <= 1, reason="Need multiple locales for meaningful test"\n)\n\n\ndef _get_current_locale(lc_var: int = locale.LC_ALL) -> str:\n # getlocale is not always compliant with setlocale, use setlocale. GH#46595\n return locale.setlocale(lc_var)\n\n\n@pytest.mark.parametrize("lc_var", (locale.LC_ALL, locale.LC_CTYPE, locale.LC_TIME))\ndef test_can_set_current_locale(lc_var):\n # Can set the current locale\n before_locale = _get_current_locale(lc_var)\n assert can_set_locale(before_locale, lc_var=lc_var)\n after_locale = _get_current_locale(lc_var)\n assert before_locale == after_locale\n\n\n@pytest.mark.parametrize("lc_var", (locale.LC_ALL, locale.LC_CTYPE, locale.LC_TIME))\ndef test_can_set_locale_valid_set(lc_var):\n # Can set the default locale.\n before_locale = _get_current_locale(lc_var)\n assert can_set_locale("", lc_var=lc_var)\n after_locale = _get_current_locale(lc_var)\n assert before_locale == after_locale\n\n\n@pytest.mark.parametrize(\n "lc_var",\n (\n locale.LC_ALL,\n locale.LC_CTYPE,\n pytest.param(\n locale.LC_TIME,\n marks=pytest.mark.skipif(\n ISMUSL, reason="MUSL allows setting invalid LC_TIME."\n ),\n ),\n ),\n)\ndef test_can_set_locale_invalid_set(lc_var):\n # Cannot set an invalid locale.\n before_locale = _get_current_locale(lc_var)\n assert not can_set_locale("non-existent_locale", lc_var=lc_var)\n after_locale = _get_current_locale(lc_var)\n assert before_locale == after_locale\n\n\n@pytest.mark.parametrize(\n "lang,enc",\n [\n ("it_CH", "UTF-8"),\n ("en_US", "ascii"),\n ("zh_CN", "GB2312"),\n ("it_IT", "ISO-8859-1"),\n ],\n)\n@pytest.mark.parametrize("lc_var", (locale.LC_ALL, locale.LC_CTYPE, locale.LC_TIME))\ndef test_can_set_locale_no_leak(lang, enc, lc_var):\n # Test that can_set_locale does not leak even when returning False. See GH#46595\n before_locale = _get_current_locale(lc_var)\n can_set_locale((lang, enc), locale.LC_ALL)\n after_locale = _get_current_locale(lc_var)\n assert before_locale == after_locale\n\n\ndef test_can_set_locale_invalid_get(monkeypatch):\n # see GH#22129\n # In some cases, an invalid locale can be set,\n # but a subsequent getlocale() raises a ValueError.\n\n def mock_get_locale():\n raise ValueError()\n\n with monkeypatch.context() as m:\n m.setattr(locale, "getlocale", mock_get_locale)\n assert not can_set_locale("")\n\n\ndef test_get_locales_at_least_one():\n # see GH#9744\n assert len(_all_locales) > 0\n\n\n@_skip_if_only_one_locale\ndef test_get_locales_prefix():\n first_locale = _all_locales[0]\n assert len(get_locales(prefix=first_locale[:2])) > 0\n\n\n@_skip_if_only_one_locale\n@pytest.mark.parametrize(\n "lang,enc",\n [\n ("it_CH", "UTF-8"),\n ("en_US", "ascii"),\n ("zh_CN", "GB2312"),\n ("it_IT", "ISO-8859-1"),\n ],\n)\ndef test_set_locale(lang, enc):\n before_locale = _get_current_locale()\n\n enc = codecs.lookup(enc).name\n new_locale = lang, enc\n\n if not can_set_locale(new_locale):\n msg = "unsupported locale setting"\n\n with pytest.raises(locale.Error, match=msg):\n with set_locale(new_locale):\n pass\n else:\n with set_locale(new_locale) as normalized_locale:\n new_lang, new_enc = normalized_locale.split(".")\n new_enc = codecs.lookup(enc).name\n\n normalized_locale = new_lang, new_enc\n assert normalized_locale == new_locale\n\n # Once we exit the "with" statement, locale should be back to what it was.\n after_locale = _get_current_locale()\n assert before_locale == after_locale\n\n\ndef test_encoding_detected():\n system_locale = os.environ.get("LC_ALL")\n system_encoding = system_locale.split(".")[-1] if system_locale else "utf-8"\n\n assert (\n codecs.lookup(pd.options.display.encoding).name\n == codecs.lookup(system_encoding).name\n )\n
.venv\Lib\site-packages\pandas\tests\config\test_localization.py
test_localization.py
Python
4,479
0.95
0.096154
0.090909
node-utils
765
2024-06-16T08:45:11.805861
MIT
true
fca0c650142d44f5487e123450a1865b