Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/__init__.py +0 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/conftest.py +41 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/numeric/__init__.py +0 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/numeric/__pycache__/__init__.cpython-310.pyc +0 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/numeric/__pycache__/test_astype.cpython-310.pyc +0 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/numeric/__pycache__/test_indexing.cpython-310.pyc +0 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/numeric/__pycache__/test_join.cpython-310.pyc +0 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/numeric/__pycache__/test_numeric.cpython-310.pyc +0 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/numeric/test_astype.py +95 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/numeric/test_indexing.py +611 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/numeric/test_join.py +380 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/numeric/test_numeric.py +553 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/numeric/test_setops.py +168 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/test_any_index.py +172 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/test_base.py +1737 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/test_common.py +512 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/test_datetimelike.py +171 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/test_engines.py +192 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/test_frozen.py +113 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/test_index_new.py +432 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/test_indexing.py +357 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/test_numpy_compat.py +189 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/test_old_base.py +1061 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/test_setops.py +959 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/test_subclass.py +40 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__init__.py +0 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__pycache__/test_arithmetic.cpython-310.pyc +0 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__pycache__/test_delete.cpython-310.pyc +0 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__pycache__/test_indexing.cpython-310.pyc +0 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__pycache__/test_join.cpython-310.pyc +0 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__pycache__/test_ops.cpython-310.pyc +0 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__pycache__/test_pickle.cpython-310.pyc +0 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__pycache__/test_setops.cpython-310.pyc +0 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__pycache__/test_timedelta_range.cpython-310.pyc +0 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/methods/__init__.py +0 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/methods/__pycache__/__init__.cpython-310.pyc +0 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/methods/__pycache__/test_factorize.cpython-310.pyc +0 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/methods/test_astype.py +176 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/methods/test_factorize.py +40 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/methods/test_repeat.py +34 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_arithmetic.py +51 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_constructors.py +291 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_delete.py +71 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_formats.py +106 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_freq_attr.py +72 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_indexing.py +347 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_join.py +47 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_ops.py +14 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_pickle.py +11 -0
- omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_scalar_compat.py +142 -0
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/__init__.py
ADDED
|
File without changes
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/conftest.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from pandas import (
|
| 5 |
+
Series,
|
| 6 |
+
array,
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@pytest.fixture(params=[None, False])
|
| 11 |
+
def sort(request):
|
| 12 |
+
"""
|
| 13 |
+
Valid values for the 'sort' parameter used in the Index
|
| 14 |
+
setops methods (intersection, union, etc.)
|
| 15 |
+
|
| 16 |
+
Caution:
|
| 17 |
+
Don't confuse this one with the "sort" fixture used
|
| 18 |
+
for DataFrame.append or concat. That one has
|
| 19 |
+
parameters [True, False].
|
| 20 |
+
|
| 21 |
+
We can't combine them as sort=True is not permitted
|
| 22 |
+
in the Index setops methods.
|
| 23 |
+
"""
|
| 24 |
+
return request.param
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@pytest.fixture(params=["D", "3D", "-3D", "h", "2h", "-2h", "min", "2min", "s", "-3s"])
|
| 28 |
+
def freq_sample(request):
|
| 29 |
+
"""
|
| 30 |
+
Valid values for 'freq' parameter used to create date_range and
|
| 31 |
+
timedelta_range..
|
| 32 |
+
"""
|
| 33 |
+
return request.param
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@pytest.fixture(params=[list, tuple, np.array, array, Series])
|
| 37 |
+
def listlike_box(request):
|
| 38 |
+
"""
|
| 39 |
+
Types that may be passed as the indexer to searchsorted.
|
| 40 |
+
"""
|
| 41 |
+
return request.param
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/numeric/__init__.py
ADDED
|
File without changes
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/numeric/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (181 Bytes). View file
|
|
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/numeric/__pycache__/test_astype.cpython-310.pyc
ADDED
|
Binary file (3.84 kB). View file
|
|
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/numeric/__pycache__/test_indexing.cpython-310.pyc
ADDED
|
Binary file (22.5 kB). View file
|
|
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/numeric/__pycache__/test_join.cpython-310.pyc
ADDED
|
Binary file (10 kB). View file
|
|
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/numeric/__pycache__/test_numeric.cpython-310.pyc
ADDED
|
Binary file (16.9 kB). View file
|
|
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/numeric/test_astype.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from pandas import (
|
| 5 |
+
Index,
|
| 6 |
+
to_datetime,
|
| 7 |
+
to_timedelta,
|
| 8 |
+
)
|
| 9 |
+
import pandas._testing as tm
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class TestAstype:
|
| 13 |
+
def test_astype_float64_to_uint64(self):
|
| 14 |
+
# GH#45309 used to incorrectly return Index with int64 dtype
|
| 15 |
+
idx = Index([0.0, 5.0, 10.0, 15.0, 20.0], dtype=np.float64)
|
| 16 |
+
result = idx.astype("u8")
|
| 17 |
+
expected = Index([0, 5, 10, 15, 20], dtype=np.uint64)
|
| 18 |
+
tm.assert_index_equal(result, expected, exact=True)
|
| 19 |
+
|
| 20 |
+
idx_with_negatives = idx - 10
|
| 21 |
+
with pytest.raises(ValueError, match="losslessly"):
|
| 22 |
+
idx_with_negatives.astype(np.uint64)
|
| 23 |
+
|
| 24 |
+
def test_astype_float64_to_object(self):
|
| 25 |
+
float_index = Index([0.0, 2.5, 5.0, 7.5, 10.0], dtype=np.float64)
|
| 26 |
+
result = float_index.astype(object)
|
| 27 |
+
assert result.equals(float_index)
|
| 28 |
+
assert float_index.equals(result)
|
| 29 |
+
assert isinstance(result, Index) and result.dtype == object
|
| 30 |
+
|
| 31 |
+
def test_astype_float64_mixed_to_object(self):
|
| 32 |
+
# mixed int-float
|
| 33 |
+
idx = Index([1.5, 2, 3, 4, 5], dtype=np.float64)
|
| 34 |
+
idx.name = "foo"
|
| 35 |
+
result = idx.astype(object)
|
| 36 |
+
assert result.equals(idx)
|
| 37 |
+
assert idx.equals(result)
|
| 38 |
+
assert isinstance(result, Index) and result.dtype == object
|
| 39 |
+
|
| 40 |
+
@pytest.mark.parametrize("dtype", ["int16", "int32", "int64"])
|
| 41 |
+
def test_astype_float64_to_int_dtype(self, dtype):
|
| 42 |
+
# GH#12881
|
| 43 |
+
# a float astype int
|
| 44 |
+
idx = Index([0, 1, 2], dtype=np.float64)
|
| 45 |
+
result = idx.astype(dtype)
|
| 46 |
+
expected = Index([0, 1, 2], dtype=dtype)
|
| 47 |
+
tm.assert_index_equal(result, expected, exact=True)
|
| 48 |
+
|
| 49 |
+
idx = Index([0, 1.1, 2], dtype=np.float64)
|
| 50 |
+
result = idx.astype(dtype)
|
| 51 |
+
expected = Index([0, 1, 2], dtype=dtype)
|
| 52 |
+
tm.assert_index_equal(result, expected, exact=True)
|
| 53 |
+
|
| 54 |
+
@pytest.mark.parametrize("dtype", ["float32", "float64"])
|
| 55 |
+
def test_astype_float64_to_float_dtype(self, dtype):
|
| 56 |
+
# GH#12881
|
| 57 |
+
# a float astype int
|
| 58 |
+
idx = Index([0, 1, 2], dtype=np.float64)
|
| 59 |
+
result = idx.astype(dtype)
|
| 60 |
+
assert isinstance(result, Index) and result.dtype == dtype
|
| 61 |
+
|
| 62 |
+
@pytest.mark.parametrize("dtype", ["M8[ns]", "m8[ns]"])
|
| 63 |
+
def test_astype_float_to_datetimelike(self, dtype):
|
| 64 |
+
# GH#49660 pre-2.0 Index.astype from floating to M8/m8/Period raised,
|
| 65 |
+
# inconsistent with Series.astype
|
| 66 |
+
idx = Index([0, 1.1, 2], dtype=np.float64)
|
| 67 |
+
|
| 68 |
+
result = idx.astype(dtype)
|
| 69 |
+
if dtype[0] == "M":
|
| 70 |
+
expected = to_datetime(idx.values)
|
| 71 |
+
else:
|
| 72 |
+
expected = to_timedelta(idx.values)
|
| 73 |
+
tm.assert_index_equal(result, expected)
|
| 74 |
+
|
| 75 |
+
# check that we match Series behavior
|
| 76 |
+
result = idx.to_series().set_axis(range(3)).astype(dtype)
|
| 77 |
+
expected = expected.to_series().set_axis(range(3))
|
| 78 |
+
tm.assert_series_equal(result, expected)
|
| 79 |
+
|
| 80 |
+
@pytest.mark.parametrize("dtype", [int, "int16", "int32", "int64"])
|
| 81 |
+
@pytest.mark.parametrize("non_finite", [np.inf, np.nan])
|
| 82 |
+
def test_cannot_cast_inf_to_int(self, non_finite, dtype):
|
| 83 |
+
# GH#13149
|
| 84 |
+
idx = Index([1, 2, non_finite], dtype=np.float64)
|
| 85 |
+
|
| 86 |
+
msg = r"Cannot convert non-finite values \(NA or inf\) to integer"
|
| 87 |
+
with pytest.raises(ValueError, match=msg):
|
| 88 |
+
idx.astype(dtype)
|
| 89 |
+
|
| 90 |
+
def test_astype_from_object(self):
|
| 91 |
+
index = Index([1.0, np.nan, 0.2], dtype="object")
|
| 92 |
+
result = index.astype(float)
|
| 93 |
+
expected = Index([1.0, np.nan, 0.2], dtype=np.float64)
|
| 94 |
+
assert result.dtype == expected.dtype
|
| 95 |
+
tm.assert_index_equal(result, expected)
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/numeric/test_indexing.py
ADDED
|
@@ -0,0 +1,611 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from pandas.errors import InvalidIndexError
|
| 5 |
+
|
| 6 |
+
from pandas import (
|
| 7 |
+
NA,
|
| 8 |
+
Index,
|
| 9 |
+
RangeIndex,
|
| 10 |
+
Series,
|
| 11 |
+
Timestamp,
|
| 12 |
+
)
|
| 13 |
+
import pandas._testing as tm
|
| 14 |
+
from pandas.core.arrays import (
|
| 15 |
+
ArrowExtensionArray,
|
| 16 |
+
FloatingArray,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@pytest.fixture
|
| 21 |
+
def index_large():
|
| 22 |
+
# large values used in Index[uint64] tests where no compat needed with Int64/Float64
|
| 23 |
+
large = [2**63, 2**63 + 10, 2**63 + 15, 2**63 + 20, 2**63 + 25]
|
| 24 |
+
return Index(large, dtype=np.uint64)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class TestGetLoc:
|
| 28 |
+
def test_get_loc(self):
|
| 29 |
+
index = Index([0, 1, 2])
|
| 30 |
+
assert index.get_loc(1) == 1
|
| 31 |
+
|
| 32 |
+
def test_get_loc_raises_bad_label(self):
|
| 33 |
+
index = Index([0, 1, 2])
|
| 34 |
+
with pytest.raises(InvalidIndexError, match=r"\[1, 2\]"):
|
| 35 |
+
index.get_loc([1, 2])
|
| 36 |
+
|
| 37 |
+
def test_get_loc_float64(self):
|
| 38 |
+
idx = Index([0.0, 1.0, 2.0], dtype=np.float64)
|
| 39 |
+
|
| 40 |
+
with pytest.raises(KeyError, match="^'foo'$"):
|
| 41 |
+
idx.get_loc("foo")
|
| 42 |
+
with pytest.raises(KeyError, match=r"^1\.5$"):
|
| 43 |
+
idx.get_loc(1.5)
|
| 44 |
+
with pytest.raises(KeyError, match="^True$"):
|
| 45 |
+
idx.get_loc(True)
|
| 46 |
+
with pytest.raises(KeyError, match="^False$"):
|
| 47 |
+
idx.get_loc(False)
|
| 48 |
+
|
| 49 |
+
def test_get_loc_na(self):
|
| 50 |
+
idx = Index([np.nan, 1, 2], dtype=np.float64)
|
| 51 |
+
assert idx.get_loc(1) == 1
|
| 52 |
+
assert idx.get_loc(np.nan) == 0
|
| 53 |
+
|
| 54 |
+
idx = Index([np.nan, 1, np.nan], dtype=np.float64)
|
| 55 |
+
assert idx.get_loc(1) == 1
|
| 56 |
+
|
| 57 |
+
# representable by slice [0:2:2]
|
| 58 |
+
msg = "'Cannot get left slice bound for non-unique label: nan'"
|
| 59 |
+
with pytest.raises(KeyError, match=msg):
|
| 60 |
+
idx.slice_locs(np.nan)
|
| 61 |
+
# not representable by slice
|
| 62 |
+
idx = Index([np.nan, 1, np.nan, np.nan], dtype=np.float64)
|
| 63 |
+
assert idx.get_loc(1) == 1
|
| 64 |
+
msg = "'Cannot get left slice bound for non-unique label: nan"
|
| 65 |
+
with pytest.raises(KeyError, match=msg):
|
| 66 |
+
idx.slice_locs(np.nan)
|
| 67 |
+
|
| 68 |
+
def test_get_loc_missing_nan(self):
|
| 69 |
+
# GH#8569
|
| 70 |
+
idx = Index([1, 2], dtype=np.float64)
|
| 71 |
+
assert idx.get_loc(1) == 0
|
| 72 |
+
with pytest.raises(KeyError, match=r"^3$"):
|
| 73 |
+
idx.get_loc(3)
|
| 74 |
+
with pytest.raises(KeyError, match="^nan$"):
|
| 75 |
+
idx.get_loc(np.nan)
|
| 76 |
+
with pytest.raises(InvalidIndexError, match=r"\[nan\]"):
|
| 77 |
+
# listlike/non-hashable raises TypeError
|
| 78 |
+
idx.get_loc([np.nan])
|
| 79 |
+
|
| 80 |
+
@pytest.mark.parametrize("vals", [[1], [1.0], [Timestamp("2019-12-31")], ["test"]])
|
| 81 |
+
def test_get_loc_float_index_nan_with_method(self, vals):
|
| 82 |
+
# GH#39382
|
| 83 |
+
idx = Index(vals)
|
| 84 |
+
with pytest.raises(KeyError, match="nan"):
|
| 85 |
+
idx.get_loc(np.nan)
|
| 86 |
+
|
| 87 |
+
@pytest.mark.parametrize("dtype", ["f8", "i8", "u8"])
|
| 88 |
+
def test_get_loc_numericindex_none_raises(self, dtype):
|
| 89 |
+
# case that goes through searchsorted and key is non-comparable to values
|
| 90 |
+
arr = np.arange(10**7, dtype=dtype)
|
| 91 |
+
idx = Index(arr)
|
| 92 |
+
with pytest.raises(KeyError, match="None"):
|
| 93 |
+
idx.get_loc(None)
|
| 94 |
+
|
| 95 |
+
def test_get_loc_overflows(self):
|
| 96 |
+
# unique but non-monotonic goes through IndexEngine.mapping.get_item
|
| 97 |
+
idx = Index([0, 2, 1])
|
| 98 |
+
|
| 99 |
+
val = np.iinfo(np.int64).max + 1
|
| 100 |
+
|
| 101 |
+
with pytest.raises(KeyError, match=str(val)):
|
| 102 |
+
idx.get_loc(val)
|
| 103 |
+
with pytest.raises(KeyError, match=str(val)):
|
| 104 |
+
idx._engine.get_loc(val)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class TestGetIndexer:
|
| 108 |
+
def test_get_indexer(self):
|
| 109 |
+
index1 = Index([1, 2, 3, 4, 5])
|
| 110 |
+
index2 = Index([2, 4, 6])
|
| 111 |
+
|
| 112 |
+
r1 = index1.get_indexer(index2)
|
| 113 |
+
e1 = np.array([1, 3, -1], dtype=np.intp)
|
| 114 |
+
tm.assert_almost_equal(r1, e1)
|
| 115 |
+
|
| 116 |
+
@pytest.mark.parametrize("reverse", [True, False])
|
| 117 |
+
@pytest.mark.parametrize(
|
| 118 |
+
"expected,method",
|
| 119 |
+
[
|
| 120 |
+
(np.array([-1, 0, 0, 1, 1], dtype=np.intp), "pad"),
|
| 121 |
+
(np.array([-1, 0, 0, 1, 1], dtype=np.intp), "ffill"),
|
| 122 |
+
(np.array([0, 0, 1, 1, 2], dtype=np.intp), "backfill"),
|
| 123 |
+
(np.array([0, 0, 1, 1, 2], dtype=np.intp), "bfill"),
|
| 124 |
+
],
|
| 125 |
+
)
|
| 126 |
+
def test_get_indexer_methods(self, reverse, expected, method):
|
| 127 |
+
index1 = Index([1, 2, 3, 4, 5])
|
| 128 |
+
index2 = Index([2, 4, 6])
|
| 129 |
+
|
| 130 |
+
if reverse:
|
| 131 |
+
index1 = index1[::-1]
|
| 132 |
+
expected = expected[::-1]
|
| 133 |
+
|
| 134 |
+
result = index2.get_indexer(index1, method=method)
|
| 135 |
+
tm.assert_almost_equal(result, expected)
|
| 136 |
+
|
| 137 |
+
def test_get_indexer_invalid(self):
|
| 138 |
+
# GH10411
|
| 139 |
+
index = Index(np.arange(10))
|
| 140 |
+
|
| 141 |
+
with pytest.raises(ValueError, match="tolerance argument"):
|
| 142 |
+
index.get_indexer([1, 0], tolerance=1)
|
| 143 |
+
|
| 144 |
+
with pytest.raises(ValueError, match="limit argument"):
|
| 145 |
+
index.get_indexer([1, 0], limit=1)
|
| 146 |
+
|
| 147 |
+
@pytest.mark.parametrize(
|
| 148 |
+
"method, tolerance, indexer, expected",
|
| 149 |
+
[
|
| 150 |
+
("pad", None, [0, 5, 9], [0, 5, 9]),
|
| 151 |
+
("backfill", None, [0, 5, 9], [0, 5, 9]),
|
| 152 |
+
("nearest", None, [0, 5, 9], [0, 5, 9]),
|
| 153 |
+
("pad", 0, [0, 5, 9], [0, 5, 9]),
|
| 154 |
+
("backfill", 0, [0, 5, 9], [0, 5, 9]),
|
| 155 |
+
("nearest", 0, [0, 5, 9], [0, 5, 9]),
|
| 156 |
+
("pad", None, [0.2, 1.8, 8.5], [0, 1, 8]),
|
| 157 |
+
("backfill", None, [0.2, 1.8, 8.5], [1, 2, 9]),
|
| 158 |
+
("nearest", None, [0.2, 1.8, 8.5], [0, 2, 9]),
|
| 159 |
+
("pad", 1, [0.2, 1.8, 8.5], [0, 1, 8]),
|
| 160 |
+
("backfill", 1, [0.2, 1.8, 8.5], [1, 2, 9]),
|
| 161 |
+
("nearest", 1, [0.2, 1.8, 8.5], [0, 2, 9]),
|
| 162 |
+
("pad", 0.2, [0.2, 1.8, 8.5], [0, -1, -1]),
|
| 163 |
+
("backfill", 0.2, [0.2, 1.8, 8.5], [-1, 2, -1]),
|
| 164 |
+
("nearest", 0.2, [0.2, 1.8, 8.5], [0, 2, -1]),
|
| 165 |
+
],
|
| 166 |
+
)
|
| 167 |
+
def test_get_indexer_nearest(self, method, tolerance, indexer, expected):
|
| 168 |
+
index = Index(np.arange(10))
|
| 169 |
+
|
| 170 |
+
actual = index.get_indexer(indexer, method=method, tolerance=tolerance)
|
| 171 |
+
tm.assert_numpy_array_equal(actual, np.array(expected, dtype=np.intp))
|
| 172 |
+
|
| 173 |
+
@pytest.mark.parametrize("listtype", [list, tuple, Series, np.array])
|
| 174 |
+
@pytest.mark.parametrize(
|
| 175 |
+
"tolerance, expected",
|
| 176 |
+
list(
|
| 177 |
+
zip(
|
| 178 |
+
[[0.3, 0.3, 0.1], [0.2, 0.1, 0.1], [0.1, 0.5, 0.5]],
|
| 179 |
+
[[0, 2, -1], [0, -1, -1], [-1, 2, 9]],
|
| 180 |
+
)
|
| 181 |
+
),
|
| 182 |
+
)
|
| 183 |
+
def test_get_indexer_nearest_listlike_tolerance(
|
| 184 |
+
self, tolerance, expected, listtype
|
| 185 |
+
):
|
| 186 |
+
index = Index(np.arange(10))
|
| 187 |
+
|
| 188 |
+
actual = index.get_indexer(
|
| 189 |
+
[0.2, 1.8, 8.5], method="nearest", tolerance=listtype(tolerance)
|
| 190 |
+
)
|
| 191 |
+
tm.assert_numpy_array_equal(actual, np.array(expected, dtype=np.intp))
|
| 192 |
+
|
| 193 |
+
def test_get_indexer_nearest_error(self):
|
| 194 |
+
index = Index(np.arange(10))
|
| 195 |
+
with pytest.raises(ValueError, match="limit argument"):
|
| 196 |
+
index.get_indexer([1, 0], method="nearest", limit=1)
|
| 197 |
+
|
| 198 |
+
with pytest.raises(ValueError, match="tolerance size must match"):
|
| 199 |
+
index.get_indexer([1, 0], method="nearest", tolerance=[1, 2, 3])
|
| 200 |
+
|
| 201 |
+
@pytest.mark.parametrize(
|
| 202 |
+
"method,expected",
|
| 203 |
+
[("pad", [8, 7, 0]), ("backfill", [9, 8, 1]), ("nearest", [9, 7, 0])],
|
| 204 |
+
)
|
| 205 |
+
def test_get_indexer_nearest_decreasing(self, method, expected):
|
| 206 |
+
index = Index(np.arange(10))[::-1]
|
| 207 |
+
|
| 208 |
+
actual = index.get_indexer([0, 5, 9], method=method)
|
| 209 |
+
tm.assert_numpy_array_equal(actual, np.array([9, 4, 0], dtype=np.intp))
|
| 210 |
+
|
| 211 |
+
actual = index.get_indexer([0.2, 1.8, 8.5], method=method)
|
| 212 |
+
tm.assert_numpy_array_equal(actual, np.array(expected, dtype=np.intp))
|
| 213 |
+
|
| 214 |
+
@pytest.mark.parametrize("idx_dtype", ["int64", "float64", "uint64", "range"])
|
| 215 |
+
@pytest.mark.parametrize("method", ["get_indexer", "get_indexer_non_unique"])
|
| 216 |
+
def test_get_indexer_numeric_index_boolean_target(self, method, idx_dtype):
|
| 217 |
+
# GH 16877
|
| 218 |
+
|
| 219 |
+
if idx_dtype == "range":
|
| 220 |
+
numeric_index = RangeIndex(4)
|
| 221 |
+
else:
|
| 222 |
+
numeric_index = Index(np.arange(4, dtype=idx_dtype))
|
| 223 |
+
|
| 224 |
+
other = Index([True, False, True])
|
| 225 |
+
|
| 226 |
+
result = getattr(numeric_index, method)(other)
|
| 227 |
+
expected = np.array([-1, -1, -1], dtype=np.intp)
|
| 228 |
+
if method == "get_indexer":
|
| 229 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 230 |
+
else:
|
| 231 |
+
missing = np.arange(3, dtype=np.intp)
|
| 232 |
+
tm.assert_numpy_array_equal(result[0], expected)
|
| 233 |
+
tm.assert_numpy_array_equal(result[1], missing)
|
| 234 |
+
|
| 235 |
+
@pytest.mark.parametrize("method", ["pad", "backfill", "nearest"])
|
| 236 |
+
def test_get_indexer_with_method_numeric_vs_bool(self, method):
|
| 237 |
+
left = Index([1, 2, 3])
|
| 238 |
+
right = Index([True, False])
|
| 239 |
+
|
| 240 |
+
with pytest.raises(TypeError, match="Cannot compare"):
|
| 241 |
+
left.get_indexer(right, method=method)
|
| 242 |
+
|
| 243 |
+
with pytest.raises(TypeError, match="Cannot compare"):
|
| 244 |
+
right.get_indexer(left, method=method)
|
| 245 |
+
|
| 246 |
+
def test_get_indexer_numeric_vs_bool(self):
|
| 247 |
+
left = Index([1, 2, 3])
|
| 248 |
+
right = Index([True, False])
|
| 249 |
+
|
| 250 |
+
res = left.get_indexer(right)
|
| 251 |
+
expected = -1 * np.ones(len(right), dtype=np.intp)
|
| 252 |
+
tm.assert_numpy_array_equal(res, expected)
|
| 253 |
+
|
| 254 |
+
res = right.get_indexer(left)
|
| 255 |
+
expected = -1 * np.ones(len(left), dtype=np.intp)
|
| 256 |
+
tm.assert_numpy_array_equal(res, expected)
|
| 257 |
+
|
| 258 |
+
res = left.get_indexer_non_unique(right)[0]
|
| 259 |
+
expected = -1 * np.ones(len(right), dtype=np.intp)
|
| 260 |
+
tm.assert_numpy_array_equal(res, expected)
|
| 261 |
+
|
| 262 |
+
res = right.get_indexer_non_unique(left)[0]
|
| 263 |
+
expected = -1 * np.ones(len(left), dtype=np.intp)
|
| 264 |
+
tm.assert_numpy_array_equal(res, expected)
|
| 265 |
+
|
| 266 |
+
def test_get_indexer_float64(self):
|
| 267 |
+
idx = Index([0.0, 1.0, 2.0], dtype=np.float64)
|
| 268 |
+
tm.assert_numpy_array_equal(
|
| 269 |
+
idx.get_indexer(idx), np.array([0, 1, 2], dtype=np.intp)
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
target = [-0.1, 0.5, 1.1]
|
| 273 |
+
tm.assert_numpy_array_equal(
|
| 274 |
+
idx.get_indexer(target, "pad"), np.array([-1, 0, 1], dtype=np.intp)
|
| 275 |
+
)
|
| 276 |
+
tm.assert_numpy_array_equal(
|
| 277 |
+
idx.get_indexer(target, "backfill"), np.array([0, 1, 2], dtype=np.intp)
|
| 278 |
+
)
|
| 279 |
+
tm.assert_numpy_array_equal(
|
| 280 |
+
idx.get_indexer(target, "nearest"), np.array([0, 1, 1], dtype=np.intp)
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
def test_get_indexer_nan(self):
|
| 284 |
+
# GH#7820
|
| 285 |
+
result = Index([1, 2, np.nan], dtype=np.float64).get_indexer([np.nan])
|
| 286 |
+
expected = np.array([2], dtype=np.intp)
|
| 287 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 288 |
+
|
| 289 |
+
def test_get_indexer_int64(self):
|
| 290 |
+
index = Index(range(0, 20, 2), dtype=np.int64)
|
| 291 |
+
target = Index(np.arange(10), dtype=np.int64)
|
| 292 |
+
indexer = index.get_indexer(target)
|
| 293 |
+
expected = np.array([0, -1, 1, -1, 2, -1, 3, -1, 4, -1], dtype=np.intp)
|
| 294 |
+
tm.assert_numpy_array_equal(indexer, expected)
|
| 295 |
+
|
| 296 |
+
target = Index(np.arange(10), dtype=np.int64)
|
| 297 |
+
indexer = index.get_indexer(target, method="pad")
|
| 298 |
+
expected = np.array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4], dtype=np.intp)
|
| 299 |
+
tm.assert_numpy_array_equal(indexer, expected)
|
| 300 |
+
|
| 301 |
+
target = Index(np.arange(10), dtype=np.int64)
|
| 302 |
+
indexer = index.get_indexer(target, method="backfill")
|
| 303 |
+
expected = np.array([0, 1, 1, 2, 2, 3, 3, 4, 4, 5], dtype=np.intp)
|
| 304 |
+
tm.assert_numpy_array_equal(indexer, expected)
|
| 305 |
+
|
| 306 |
+
def test_get_indexer_uint64(self, index_large):
|
| 307 |
+
target = Index(np.arange(10).astype("uint64") * 5 + 2**63)
|
| 308 |
+
indexer = index_large.get_indexer(target)
|
| 309 |
+
expected = np.array([0, -1, 1, 2, 3, 4, -1, -1, -1, -1], dtype=np.intp)
|
| 310 |
+
tm.assert_numpy_array_equal(indexer, expected)
|
| 311 |
+
|
| 312 |
+
target = Index(np.arange(10).astype("uint64") * 5 + 2**63)
|
| 313 |
+
indexer = index_large.get_indexer(target, method="pad")
|
| 314 |
+
expected = np.array([0, 0, 1, 2, 3, 4, 4, 4, 4, 4], dtype=np.intp)
|
| 315 |
+
tm.assert_numpy_array_equal(indexer, expected)
|
| 316 |
+
|
| 317 |
+
target = Index(np.arange(10).astype("uint64") * 5 + 2**63)
|
| 318 |
+
indexer = index_large.get_indexer(target, method="backfill")
|
| 319 |
+
expected = np.array([0, 1, 1, 2, 3, 4, -1, -1, -1, -1], dtype=np.intp)
|
| 320 |
+
tm.assert_numpy_array_equal(indexer, expected)
|
| 321 |
+
|
| 322 |
+
@pytest.mark.parametrize("val, val2", [(4, 5), (4, 4), (4, NA), (NA, NA)])
|
| 323 |
+
def test_get_loc_masked(self, val, val2, any_numeric_ea_and_arrow_dtype):
|
| 324 |
+
# GH#39133
|
| 325 |
+
idx = Index([1, 2, 3, val, val2], dtype=any_numeric_ea_and_arrow_dtype)
|
| 326 |
+
result = idx.get_loc(2)
|
| 327 |
+
assert result == 1
|
| 328 |
+
|
| 329 |
+
with pytest.raises(KeyError, match="9"):
|
| 330 |
+
idx.get_loc(9)
|
| 331 |
+
|
| 332 |
+
def test_get_loc_masked_na(self, any_numeric_ea_and_arrow_dtype):
|
| 333 |
+
# GH#39133
|
| 334 |
+
idx = Index([1, 2, NA], dtype=any_numeric_ea_and_arrow_dtype)
|
| 335 |
+
result = idx.get_loc(NA)
|
| 336 |
+
assert result == 2
|
| 337 |
+
|
| 338 |
+
idx = Index([1, 2, NA, NA], dtype=any_numeric_ea_and_arrow_dtype)
|
| 339 |
+
result = idx.get_loc(NA)
|
| 340 |
+
tm.assert_numpy_array_equal(result, np.array([False, False, True, True]))
|
| 341 |
+
|
| 342 |
+
idx = Index([1, 2, 3], dtype=any_numeric_ea_and_arrow_dtype)
|
| 343 |
+
with pytest.raises(KeyError, match="NA"):
|
| 344 |
+
idx.get_loc(NA)
|
| 345 |
+
|
| 346 |
+
def test_get_loc_masked_na_and_nan(self):
|
| 347 |
+
# GH#39133
|
| 348 |
+
idx = Index(
|
| 349 |
+
FloatingArray(
|
| 350 |
+
np.array([1, 2, 1, np.nan]), mask=np.array([False, False, True, False])
|
| 351 |
+
)
|
| 352 |
+
)
|
| 353 |
+
result = idx.get_loc(NA)
|
| 354 |
+
assert result == 2
|
| 355 |
+
result = idx.get_loc(np.nan)
|
| 356 |
+
assert result == 3
|
| 357 |
+
|
| 358 |
+
idx = Index(
|
| 359 |
+
FloatingArray(np.array([1, 2, 1.0]), mask=np.array([False, False, True]))
|
| 360 |
+
)
|
| 361 |
+
result = idx.get_loc(NA)
|
| 362 |
+
assert result == 2
|
| 363 |
+
with pytest.raises(KeyError, match="nan"):
|
| 364 |
+
idx.get_loc(np.nan)
|
| 365 |
+
|
| 366 |
+
idx = Index(
|
| 367 |
+
FloatingArray(
|
| 368 |
+
np.array([1, 2, np.nan]), mask=np.array([False, False, False])
|
| 369 |
+
)
|
| 370 |
+
)
|
| 371 |
+
result = idx.get_loc(np.nan)
|
| 372 |
+
assert result == 2
|
| 373 |
+
with pytest.raises(KeyError, match="NA"):
|
| 374 |
+
idx.get_loc(NA)
|
| 375 |
+
|
| 376 |
+
@pytest.mark.parametrize("val", [4, 2])
|
| 377 |
+
def test_get_indexer_masked_na(self, any_numeric_ea_and_arrow_dtype, val):
|
| 378 |
+
# GH#39133
|
| 379 |
+
idx = Index([1, 2, NA, 3, val], dtype=any_numeric_ea_and_arrow_dtype)
|
| 380 |
+
result = idx.get_indexer_for([1, NA, 5])
|
| 381 |
+
expected = np.array([0, 2, -1])
|
| 382 |
+
tm.assert_numpy_array_equal(result, expected, check_dtype=False)
|
| 383 |
+
|
| 384 |
+
@pytest.mark.parametrize("dtype", ["boolean", "bool[pyarrow]"])
|
| 385 |
+
def test_get_indexer_masked_na_boolean(self, dtype):
|
| 386 |
+
# GH#39133
|
| 387 |
+
if dtype == "bool[pyarrow]":
|
| 388 |
+
pytest.importorskip("pyarrow")
|
| 389 |
+
idx = Index([True, False, NA], dtype=dtype)
|
| 390 |
+
result = idx.get_loc(False)
|
| 391 |
+
assert result == 1
|
| 392 |
+
result = idx.get_loc(NA)
|
| 393 |
+
assert result == 2
|
| 394 |
+
|
| 395 |
+
def test_get_indexer_arrow_dictionary_target(self):
|
| 396 |
+
pa = pytest.importorskip("pyarrow")
|
| 397 |
+
target = Index(
|
| 398 |
+
ArrowExtensionArray(
|
| 399 |
+
pa.array([1, 2], type=pa.dictionary(pa.int8(), pa.int8()))
|
| 400 |
+
)
|
| 401 |
+
)
|
| 402 |
+
idx = Index([1])
|
| 403 |
+
|
| 404 |
+
result = idx.get_indexer(target)
|
| 405 |
+
expected = np.array([0, -1], dtype=np.int64)
|
| 406 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 407 |
+
|
| 408 |
+
result_1, result_2 = idx.get_indexer_non_unique(target)
|
| 409 |
+
expected_1, expected_2 = np.array([0, -1], dtype=np.int64), np.array(
|
| 410 |
+
[1], dtype=np.int64
|
| 411 |
+
)
|
| 412 |
+
tm.assert_numpy_array_equal(result_1, expected_1)
|
| 413 |
+
tm.assert_numpy_array_equal(result_2, expected_2)
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
class TestWhere:
|
| 417 |
+
@pytest.mark.parametrize(
|
| 418 |
+
"index",
|
| 419 |
+
[
|
| 420 |
+
Index(np.arange(5, dtype="float64")),
|
| 421 |
+
Index(range(0, 20, 2), dtype=np.int64),
|
| 422 |
+
Index(np.arange(5, dtype="uint64")),
|
| 423 |
+
],
|
| 424 |
+
)
|
| 425 |
+
def test_where(self, listlike_box, index):
|
| 426 |
+
cond = [True] * len(index)
|
| 427 |
+
expected = index
|
| 428 |
+
result = index.where(listlike_box(cond))
|
| 429 |
+
|
| 430 |
+
cond = [False] + [True] * (len(index) - 1)
|
| 431 |
+
expected = Index([index._na_value] + index[1:].tolist(), dtype=np.float64)
|
| 432 |
+
result = index.where(listlike_box(cond))
|
| 433 |
+
tm.assert_index_equal(result, expected)
|
| 434 |
+
|
| 435 |
+
def test_where_uint64(self):
|
| 436 |
+
idx = Index([0, 6, 2], dtype=np.uint64)
|
| 437 |
+
mask = np.array([False, True, False])
|
| 438 |
+
other = np.array([1], dtype=np.int64)
|
| 439 |
+
|
| 440 |
+
expected = Index([1, 6, 1], dtype=np.uint64)
|
| 441 |
+
|
| 442 |
+
result = idx.where(mask, other)
|
| 443 |
+
tm.assert_index_equal(result, expected)
|
| 444 |
+
|
| 445 |
+
result = idx.putmask(~mask, other)
|
| 446 |
+
tm.assert_index_equal(result, expected)
|
| 447 |
+
|
| 448 |
+
def test_where_infers_type_instead_of_trying_to_convert_string_to_float(self):
|
| 449 |
+
# GH 32413
|
| 450 |
+
index = Index([1, np.nan])
|
| 451 |
+
cond = index.notna()
|
| 452 |
+
other = Index(["a", "b"], dtype="string")
|
| 453 |
+
|
| 454 |
+
expected = Index([1.0, "b"])
|
| 455 |
+
result = index.where(cond, other)
|
| 456 |
+
|
| 457 |
+
tm.assert_index_equal(result, expected)
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
class TestTake:
|
| 461 |
+
@pytest.mark.parametrize("idx_dtype", [np.float64, np.int64, np.uint64])
|
| 462 |
+
def test_take_preserve_name(self, idx_dtype):
|
| 463 |
+
index = Index([1, 2, 3, 4], dtype=idx_dtype, name="foo")
|
| 464 |
+
taken = index.take([3, 0, 1])
|
| 465 |
+
assert index.name == taken.name
|
| 466 |
+
|
| 467 |
+
def test_take_fill_value_float64(self):
|
| 468 |
+
# GH 12631
|
| 469 |
+
idx = Index([1.0, 2.0, 3.0], name="xxx", dtype=np.float64)
|
| 470 |
+
result = idx.take(np.array([1, 0, -1]))
|
| 471 |
+
expected = Index([2.0, 1.0, 3.0], dtype=np.float64, name="xxx")
|
| 472 |
+
tm.assert_index_equal(result, expected)
|
| 473 |
+
|
| 474 |
+
# fill_value
|
| 475 |
+
result = idx.take(np.array([1, 0, -1]), fill_value=True)
|
| 476 |
+
expected = Index([2.0, 1.0, np.nan], dtype=np.float64, name="xxx")
|
| 477 |
+
tm.assert_index_equal(result, expected)
|
| 478 |
+
|
| 479 |
+
# allow_fill=False
|
| 480 |
+
result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True)
|
| 481 |
+
expected = Index([2.0, 1.0, 3.0], dtype=np.float64, name="xxx")
|
| 482 |
+
tm.assert_index_equal(result, expected)
|
| 483 |
+
|
| 484 |
+
msg = (
|
| 485 |
+
"When allow_fill=True and fill_value is not None, "
|
| 486 |
+
"all indices must be >= -1"
|
| 487 |
+
)
|
| 488 |
+
with pytest.raises(ValueError, match=msg):
|
| 489 |
+
idx.take(np.array([1, 0, -2]), fill_value=True)
|
| 490 |
+
with pytest.raises(ValueError, match=msg):
|
| 491 |
+
idx.take(np.array([1, 0, -5]), fill_value=True)
|
| 492 |
+
|
| 493 |
+
msg = "index -5 is out of bounds for (axis 0 with )?size 3"
|
| 494 |
+
with pytest.raises(IndexError, match=msg):
|
| 495 |
+
idx.take(np.array([1, -5]))
|
| 496 |
+
|
| 497 |
+
@pytest.mark.parametrize("dtype", [np.int64, np.uint64])
|
| 498 |
+
def test_take_fill_value_ints(self, dtype):
|
| 499 |
+
# see gh-12631
|
| 500 |
+
idx = Index([1, 2, 3], dtype=dtype, name="xxx")
|
| 501 |
+
result = idx.take(np.array([1, 0, -1]))
|
| 502 |
+
expected = Index([2, 1, 3], dtype=dtype, name="xxx")
|
| 503 |
+
tm.assert_index_equal(result, expected)
|
| 504 |
+
|
| 505 |
+
name = type(idx).__name__
|
| 506 |
+
msg = f"Unable to fill values because {name} cannot contain NA"
|
| 507 |
+
|
| 508 |
+
# fill_value=True
|
| 509 |
+
with pytest.raises(ValueError, match=msg):
|
| 510 |
+
idx.take(np.array([1, 0, -1]), fill_value=True)
|
| 511 |
+
|
| 512 |
+
# allow_fill=False
|
| 513 |
+
result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True)
|
| 514 |
+
expected = Index([2, 1, 3], dtype=dtype, name="xxx")
|
| 515 |
+
tm.assert_index_equal(result, expected)
|
| 516 |
+
|
| 517 |
+
with pytest.raises(ValueError, match=msg):
|
| 518 |
+
idx.take(np.array([1, 0, -2]), fill_value=True)
|
| 519 |
+
with pytest.raises(ValueError, match=msg):
|
| 520 |
+
idx.take(np.array([1, 0, -5]), fill_value=True)
|
| 521 |
+
|
| 522 |
+
msg = "index -5 is out of bounds for (axis 0 with )?size 3"
|
| 523 |
+
with pytest.raises(IndexError, match=msg):
|
| 524 |
+
idx.take(np.array([1, -5]))
|
| 525 |
+
|
| 526 |
+
|
| 527 |
+
class TestContains:
|
| 528 |
+
@pytest.mark.parametrize("dtype", [np.float64, np.int64, np.uint64])
|
| 529 |
+
def test_contains_none(self, dtype):
|
| 530 |
+
# GH#35788 should return False, not raise TypeError
|
| 531 |
+
index = Index([0, 1, 2, 3, 4], dtype=dtype)
|
| 532 |
+
assert None not in index
|
| 533 |
+
|
| 534 |
+
def test_contains_float64_nans(self):
|
| 535 |
+
index = Index([1.0, 2.0, np.nan], dtype=np.float64)
|
| 536 |
+
assert np.nan in index
|
| 537 |
+
|
| 538 |
+
def test_contains_float64_not_nans(self):
|
| 539 |
+
index = Index([1.0, 2.0, np.nan], dtype=np.float64)
|
| 540 |
+
assert 1.0 in index
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
class TestSliceLocs:
|
| 544 |
+
@pytest.mark.parametrize("dtype", [int, float])
|
| 545 |
+
def test_slice_locs(self, dtype):
|
| 546 |
+
index = Index(np.array([0, 1, 2, 5, 6, 7, 9, 10], dtype=dtype))
|
| 547 |
+
n = len(index)
|
| 548 |
+
|
| 549 |
+
assert index.slice_locs(start=2) == (2, n)
|
| 550 |
+
assert index.slice_locs(start=3) == (3, n)
|
| 551 |
+
assert index.slice_locs(3, 8) == (3, 6)
|
| 552 |
+
assert index.slice_locs(5, 10) == (3, n)
|
| 553 |
+
assert index.slice_locs(end=8) == (0, 6)
|
| 554 |
+
assert index.slice_locs(end=9) == (0, 7)
|
| 555 |
+
|
| 556 |
+
# reversed
|
| 557 |
+
index2 = index[::-1]
|
| 558 |
+
assert index2.slice_locs(8, 2) == (2, 6)
|
| 559 |
+
assert index2.slice_locs(7, 3) == (2, 5)
|
| 560 |
+
|
| 561 |
+
@pytest.mark.parametrize("dtype", [int, float])
|
| 562 |
+
def test_slice_locs_float_locs(self, dtype):
|
| 563 |
+
index = Index(np.array([0, 1, 2, 5, 6, 7, 9, 10], dtype=dtype))
|
| 564 |
+
n = len(index)
|
| 565 |
+
assert index.slice_locs(5.0, 10.0) == (3, n)
|
| 566 |
+
assert index.slice_locs(4.5, 10.5) == (3, 8)
|
| 567 |
+
|
| 568 |
+
index2 = index[::-1]
|
| 569 |
+
assert index2.slice_locs(8.5, 1.5) == (2, 6)
|
| 570 |
+
assert index2.slice_locs(10.5, -1) == (0, n)
|
| 571 |
+
|
| 572 |
+
@pytest.mark.parametrize("dtype", [int, float])
|
| 573 |
+
def test_slice_locs_dup_numeric(self, dtype):
|
| 574 |
+
index = Index(np.array([10, 12, 12, 14], dtype=dtype))
|
| 575 |
+
assert index.slice_locs(12, 12) == (1, 3)
|
| 576 |
+
assert index.slice_locs(11, 13) == (1, 3)
|
| 577 |
+
|
| 578 |
+
index2 = index[::-1]
|
| 579 |
+
assert index2.slice_locs(12, 12) == (1, 3)
|
| 580 |
+
assert index2.slice_locs(13, 11) == (1, 3)
|
| 581 |
+
|
| 582 |
+
def test_slice_locs_na(self):
|
| 583 |
+
index = Index([np.nan, 1, 2])
|
| 584 |
+
assert index.slice_locs(1) == (1, 3)
|
| 585 |
+
assert index.slice_locs(np.nan) == (0, 3)
|
| 586 |
+
|
| 587 |
+
index = Index([0, np.nan, np.nan, 1, 2])
|
| 588 |
+
assert index.slice_locs(np.nan) == (1, 5)
|
| 589 |
+
|
| 590 |
+
def test_slice_locs_na_raises(self):
|
| 591 |
+
index = Index([np.nan, 1, 2])
|
| 592 |
+
with pytest.raises(KeyError, match=""):
|
| 593 |
+
index.slice_locs(start=1.5)
|
| 594 |
+
|
| 595 |
+
with pytest.raises(KeyError, match=""):
|
| 596 |
+
index.slice_locs(end=1.5)
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
class TestGetSliceBounds:
|
| 600 |
+
@pytest.mark.parametrize("side, expected", [("left", 4), ("right", 5)])
|
| 601 |
+
def test_get_slice_bounds_within(self, side, expected):
|
| 602 |
+
index = Index(range(6))
|
| 603 |
+
result = index.get_slice_bound(4, side=side)
|
| 604 |
+
assert result == expected
|
| 605 |
+
|
| 606 |
+
@pytest.mark.parametrize("side", ["left", "right"])
|
| 607 |
+
@pytest.mark.parametrize("bound, expected", [(-1, 0), (10, 6)])
|
| 608 |
+
def test_get_slice_bounds_outside(self, side, expected, bound):
|
| 609 |
+
index = Index(range(6))
|
| 610 |
+
result = index.get_slice_bound(bound, side=side)
|
| 611 |
+
assert result == expected
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/numeric/test_join.py
ADDED
|
@@ -0,0 +1,380 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas._testing as tm
|
| 5 |
+
from pandas.core.indexes.api import Index
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class TestJoinInt64Index:
|
| 9 |
+
def test_join_non_unique(self):
|
| 10 |
+
left = Index([4, 4, 3, 3])
|
| 11 |
+
|
| 12 |
+
joined, lidx, ridx = left.join(left, return_indexers=True)
|
| 13 |
+
|
| 14 |
+
exp_joined = Index([4, 4, 4, 4, 3, 3, 3, 3])
|
| 15 |
+
tm.assert_index_equal(joined, exp_joined)
|
| 16 |
+
|
| 17 |
+
exp_lidx = np.array([0, 0, 1, 1, 2, 2, 3, 3], dtype=np.intp)
|
| 18 |
+
tm.assert_numpy_array_equal(lidx, exp_lidx)
|
| 19 |
+
|
| 20 |
+
exp_ridx = np.array([0, 1, 0, 1, 2, 3, 2, 3], dtype=np.intp)
|
| 21 |
+
tm.assert_numpy_array_equal(ridx, exp_ridx)
|
| 22 |
+
|
| 23 |
+
def test_join_inner(self):
|
| 24 |
+
index = Index(range(0, 20, 2), dtype=np.int64)
|
| 25 |
+
other = Index([7, 12, 25, 1, 2, 5], dtype=np.int64)
|
| 26 |
+
other_mono = Index([1, 2, 5, 7, 12, 25], dtype=np.int64)
|
| 27 |
+
|
| 28 |
+
# not monotonic
|
| 29 |
+
res, lidx, ridx = index.join(other, how="inner", return_indexers=True)
|
| 30 |
+
|
| 31 |
+
# no guarantee of sortedness, so sort for comparison purposes
|
| 32 |
+
ind = res.argsort()
|
| 33 |
+
res = res.take(ind)
|
| 34 |
+
lidx = lidx.take(ind)
|
| 35 |
+
ridx = ridx.take(ind)
|
| 36 |
+
|
| 37 |
+
eres = Index([2, 12], dtype=np.int64)
|
| 38 |
+
elidx = np.array([1, 6], dtype=np.intp)
|
| 39 |
+
eridx = np.array([4, 1], dtype=np.intp)
|
| 40 |
+
|
| 41 |
+
assert isinstance(res, Index) and res.dtype == np.int64
|
| 42 |
+
tm.assert_index_equal(res, eres)
|
| 43 |
+
tm.assert_numpy_array_equal(lidx, elidx)
|
| 44 |
+
tm.assert_numpy_array_equal(ridx, eridx)
|
| 45 |
+
|
| 46 |
+
# monotonic
|
| 47 |
+
res, lidx, ridx = index.join(other_mono, how="inner", return_indexers=True)
|
| 48 |
+
|
| 49 |
+
res2 = index.intersection(other_mono)
|
| 50 |
+
tm.assert_index_equal(res, res2)
|
| 51 |
+
|
| 52 |
+
elidx = np.array([1, 6], dtype=np.intp)
|
| 53 |
+
eridx = np.array([1, 4], dtype=np.intp)
|
| 54 |
+
assert isinstance(res, Index) and res.dtype == np.int64
|
| 55 |
+
tm.assert_index_equal(res, eres)
|
| 56 |
+
tm.assert_numpy_array_equal(lidx, elidx)
|
| 57 |
+
tm.assert_numpy_array_equal(ridx, eridx)
|
| 58 |
+
|
| 59 |
+
def test_join_left(self):
|
| 60 |
+
index = Index(range(0, 20, 2), dtype=np.int64)
|
| 61 |
+
other = Index([7, 12, 25, 1, 2, 5], dtype=np.int64)
|
| 62 |
+
other_mono = Index([1, 2, 5, 7, 12, 25], dtype=np.int64)
|
| 63 |
+
|
| 64 |
+
# not monotonic
|
| 65 |
+
res, lidx, ridx = index.join(other, how="left", return_indexers=True)
|
| 66 |
+
eres = index
|
| 67 |
+
eridx = np.array([-1, 4, -1, -1, -1, -1, 1, -1, -1, -1], dtype=np.intp)
|
| 68 |
+
|
| 69 |
+
assert isinstance(res, Index) and res.dtype == np.int64
|
| 70 |
+
tm.assert_index_equal(res, eres)
|
| 71 |
+
assert lidx is None
|
| 72 |
+
tm.assert_numpy_array_equal(ridx, eridx)
|
| 73 |
+
|
| 74 |
+
# monotonic
|
| 75 |
+
res, lidx, ridx = index.join(other_mono, how="left", return_indexers=True)
|
| 76 |
+
eridx = np.array([-1, 1, -1, -1, -1, -1, 4, -1, -1, -1], dtype=np.intp)
|
| 77 |
+
assert isinstance(res, Index) and res.dtype == np.int64
|
| 78 |
+
tm.assert_index_equal(res, eres)
|
| 79 |
+
assert lidx is None
|
| 80 |
+
tm.assert_numpy_array_equal(ridx, eridx)
|
| 81 |
+
|
| 82 |
+
# non-unique
|
| 83 |
+
idx = Index([1, 1, 2, 5])
|
| 84 |
+
idx2 = Index([1, 2, 5, 7, 9])
|
| 85 |
+
res, lidx, ridx = idx2.join(idx, how="left", return_indexers=True)
|
| 86 |
+
eres = Index([1, 1, 2, 5, 7, 9]) # 1 is in idx2, so it should be x2
|
| 87 |
+
eridx = np.array([0, 1, 2, 3, -1, -1], dtype=np.intp)
|
| 88 |
+
elidx = np.array([0, 0, 1, 2, 3, 4], dtype=np.intp)
|
| 89 |
+
tm.assert_index_equal(res, eres)
|
| 90 |
+
tm.assert_numpy_array_equal(lidx, elidx)
|
| 91 |
+
tm.assert_numpy_array_equal(ridx, eridx)
|
| 92 |
+
|
| 93 |
+
def test_join_right(self):
|
| 94 |
+
index = Index(range(0, 20, 2), dtype=np.int64)
|
| 95 |
+
other = Index([7, 12, 25, 1, 2, 5], dtype=np.int64)
|
| 96 |
+
other_mono = Index([1, 2, 5, 7, 12, 25], dtype=np.int64)
|
| 97 |
+
|
| 98 |
+
# not monotonic
|
| 99 |
+
res, lidx, ridx = index.join(other, how="right", return_indexers=True)
|
| 100 |
+
eres = other
|
| 101 |
+
elidx = np.array([-1, 6, -1, -1, 1, -1], dtype=np.intp)
|
| 102 |
+
|
| 103 |
+
assert isinstance(other, Index) and other.dtype == np.int64
|
| 104 |
+
tm.assert_index_equal(res, eres)
|
| 105 |
+
tm.assert_numpy_array_equal(lidx, elidx)
|
| 106 |
+
assert ridx is None
|
| 107 |
+
|
| 108 |
+
# monotonic
|
| 109 |
+
res, lidx, ridx = index.join(other_mono, how="right", return_indexers=True)
|
| 110 |
+
eres = other_mono
|
| 111 |
+
elidx = np.array([-1, 1, -1, -1, 6, -1], dtype=np.intp)
|
| 112 |
+
assert isinstance(other, Index) and other.dtype == np.int64
|
| 113 |
+
tm.assert_index_equal(res, eres)
|
| 114 |
+
tm.assert_numpy_array_equal(lidx, elidx)
|
| 115 |
+
assert ridx is None
|
| 116 |
+
|
| 117 |
+
# non-unique
|
| 118 |
+
idx = Index([1, 1, 2, 5])
|
| 119 |
+
idx2 = Index([1, 2, 5, 7, 9])
|
| 120 |
+
res, lidx, ridx = idx.join(idx2, how="right", return_indexers=True)
|
| 121 |
+
eres = Index([1, 1, 2, 5, 7, 9]) # 1 is in idx2, so it should be x2
|
| 122 |
+
elidx = np.array([0, 1, 2, 3, -1, -1], dtype=np.intp)
|
| 123 |
+
eridx = np.array([0, 0, 1, 2, 3, 4], dtype=np.intp)
|
| 124 |
+
tm.assert_index_equal(res, eres)
|
| 125 |
+
tm.assert_numpy_array_equal(lidx, elidx)
|
| 126 |
+
tm.assert_numpy_array_equal(ridx, eridx)
|
| 127 |
+
|
| 128 |
+
def test_join_non_int_index(self):
|
| 129 |
+
index = Index(range(0, 20, 2), dtype=np.int64)
|
| 130 |
+
other = Index([3, 6, 7, 8, 10], dtype=object)
|
| 131 |
+
|
| 132 |
+
outer = index.join(other, how="outer")
|
| 133 |
+
outer2 = other.join(index, how="outer")
|
| 134 |
+
expected = Index([0, 2, 3, 4, 6, 7, 8, 10, 12, 14, 16, 18])
|
| 135 |
+
tm.assert_index_equal(outer, outer2)
|
| 136 |
+
tm.assert_index_equal(outer, expected)
|
| 137 |
+
|
| 138 |
+
inner = index.join(other, how="inner")
|
| 139 |
+
inner2 = other.join(index, how="inner")
|
| 140 |
+
expected = Index([6, 8, 10])
|
| 141 |
+
tm.assert_index_equal(inner, inner2)
|
| 142 |
+
tm.assert_index_equal(inner, expected)
|
| 143 |
+
|
| 144 |
+
left = index.join(other, how="left")
|
| 145 |
+
tm.assert_index_equal(left, index.astype(object))
|
| 146 |
+
|
| 147 |
+
left2 = other.join(index, how="left")
|
| 148 |
+
tm.assert_index_equal(left2, other)
|
| 149 |
+
|
| 150 |
+
right = index.join(other, how="right")
|
| 151 |
+
tm.assert_index_equal(right, other)
|
| 152 |
+
|
| 153 |
+
right2 = other.join(index, how="right")
|
| 154 |
+
tm.assert_index_equal(right2, index.astype(object))
|
| 155 |
+
|
| 156 |
+
def test_join_outer(self):
|
| 157 |
+
index = Index(range(0, 20, 2), dtype=np.int64)
|
| 158 |
+
other = Index([7, 12, 25, 1, 2, 5], dtype=np.int64)
|
| 159 |
+
other_mono = Index([1, 2, 5, 7, 12, 25], dtype=np.int64)
|
| 160 |
+
|
| 161 |
+
# not monotonic
|
| 162 |
+
# guarantee of sortedness
|
| 163 |
+
res, lidx, ridx = index.join(other, how="outer", return_indexers=True)
|
| 164 |
+
noidx_res = index.join(other, how="outer")
|
| 165 |
+
tm.assert_index_equal(res, noidx_res)
|
| 166 |
+
|
| 167 |
+
eres = Index([0, 1, 2, 4, 5, 6, 7, 8, 10, 12, 14, 16, 18, 25], dtype=np.int64)
|
| 168 |
+
elidx = np.array([0, -1, 1, 2, -1, 3, -1, 4, 5, 6, 7, 8, 9, -1], dtype=np.intp)
|
| 169 |
+
eridx = np.array(
|
| 170 |
+
[-1, 3, 4, -1, 5, -1, 0, -1, -1, 1, -1, -1, -1, 2], dtype=np.intp
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
assert isinstance(res, Index) and res.dtype == np.int64
|
| 174 |
+
tm.assert_index_equal(res, eres)
|
| 175 |
+
tm.assert_numpy_array_equal(lidx, elidx)
|
| 176 |
+
tm.assert_numpy_array_equal(ridx, eridx)
|
| 177 |
+
|
| 178 |
+
# monotonic
|
| 179 |
+
res, lidx, ridx = index.join(other_mono, how="outer", return_indexers=True)
|
| 180 |
+
noidx_res = index.join(other_mono, how="outer")
|
| 181 |
+
tm.assert_index_equal(res, noidx_res)
|
| 182 |
+
|
| 183 |
+
elidx = np.array([0, -1, 1, 2, -1, 3, -1, 4, 5, 6, 7, 8, 9, -1], dtype=np.intp)
|
| 184 |
+
eridx = np.array(
|
| 185 |
+
[-1, 0, 1, -1, 2, -1, 3, -1, -1, 4, -1, -1, -1, 5], dtype=np.intp
|
| 186 |
+
)
|
| 187 |
+
assert isinstance(res, Index) and res.dtype == np.int64
|
| 188 |
+
tm.assert_index_equal(res, eres)
|
| 189 |
+
tm.assert_numpy_array_equal(lidx, elidx)
|
| 190 |
+
tm.assert_numpy_array_equal(ridx, eridx)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
class TestJoinUInt64Index:
|
| 194 |
+
@pytest.fixture
|
| 195 |
+
def index_large(self):
|
| 196 |
+
# large values used in TestUInt64Index where no compat needed with int64/float64
|
| 197 |
+
large = [2**63, 2**63 + 10, 2**63 + 15, 2**63 + 20, 2**63 + 25]
|
| 198 |
+
return Index(large, dtype=np.uint64)
|
| 199 |
+
|
| 200 |
+
def test_join_inner(self, index_large):
|
| 201 |
+
other = Index(2**63 + np.array([7, 12, 25, 1, 2, 10], dtype="uint64"))
|
| 202 |
+
other_mono = Index(2**63 + np.array([1, 2, 7, 10, 12, 25], dtype="uint64"))
|
| 203 |
+
|
| 204 |
+
# not monotonic
|
| 205 |
+
res, lidx, ridx = index_large.join(other, how="inner", return_indexers=True)
|
| 206 |
+
|
| 207 |
+
# no guarantee of sortedness, so sort for comparison purposes
|
| 208 |
+
ind = res.argsort()
|
| 209 |
+
res = res.take(ind)
|
| 210 |
+
lidx = lidx.take(ind)
|
| 211 |
+
ridx = ridx.take(ind)
|
| 212 |
+
|
| 213 |
+
eres = Index(2**63 + np.array([10, 25], dtype="uint64"))
|
| 214 |
+
elidx = np.array([1, 4], dtype=np.intp)
|
| 215 |
+
eridx = np.array([5, 2], dtype=np.intp)
|
| 216 |
+
|
| 217 |
+
assert isinstance(res, Index) and res.dtype == np.uint64
|
| 218 |
+
tm.assert_index_equal(res, eres)
|
| 219 |
+
tm.assert_numpy_array_equal(lidx, elidx)
|
| 220 |
+
tm.assert_numpy_array_equal(ridx, eridx)
|
| 221 |
+
|
| 222 |
+
# monotonic
|
| 223 |
+
res, lidx, ridx = index_large.join(
|
| 224 |
+
other_mono, how="inner", return_indexers=True
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
res2 = index_large.intersection(other_mono)
|
| 228 |
+
tm.assert_index_equal(res, res2)
|
| 229 |
+
|
| 230 |
+
elidx = np.array([1, 4], dtype=np.intp)
|
| 231 |
+
eridx = np.array([3, 5], dtype=np.intp)
|
| 232 |
+
|
| 233 |
+
assert isinstance(res, Index) and res.dtype == np.uint64
|
| 234 |
+
tm.assert_index_equal(res, eres)
|
| 235 |
+
tm.assert_numpy_array_equal(lidx, elidx)
|
| 236 |
+
tm.assert_numpy_array_equal(ridx, eridx)
|
| 237 |
+
|
| 238 |
+
def test_join_left(self, index_large):
|
| 239 |
+
other = Index(2**63 + np.array([7, 12, 25, 1, 2, 10], dtype="uint64"))
|
| 240 |
+
other_mono = Index(2**63 + np.array([1, 2, 7, 10, 12, 25], dtype="uint64"))
|
| 241 |
+
|
| 242 |
+
# not monotonic
|
| 243 |
+
res, lidx, ridx = index_large.join(other, how="left", return_indexers=True)
|
| 244 |
+
eres = index_large
|
| 245 |
+
eridx = np.array([-1, 5, -1, -1, 2], dtype=np.intp)
|
| 246 |
+
|
| 247 |
+
assert isinstance(res, Index) and res.dtype == np.uint64
|
| 248 |
+
tm.assert_index_equal(res, eres)
|
| 249 |
+
assert lidx is None
|
| 250 |
+
tm.assert_numpy_array_equal(ridx, eridx)
|
| 251 |
+
|
| 252 |
+
# monotonic
|
| 253 |
+
res, lidx, ridx = index_large.join(other_mono, how="left", return_indexers=True)
|
| 254 |
+
eridx = np.array([-1, 3, -1, -1, 5], dtype=np.intp)
|
| 255 |
+
|
| 256 |
+
assert isinstance(res, Index) and res.dtype == np.uint64
|
| 257 |
+
tm.assert_index_equal(res, eres)
|
| 258 |
+
assert lidx is None
|
| 259 |
+
tm.assert_numpy_array_equal(ridx, eridx)
|
| 260 |
+
|
| 261 |
+
# non-unique
|
| 262 |
+
idx = Index(2**63 + np.array([1, 1, 2, 5], dtype="uint64"))
|
| 263 |
+
idx2 = Index(2**63 + np.array([1, 2, 5, 7, 9], dtype="uint64"))
|
| 264 |
+
res, lidx, ridx = idx2.join(idx, how="left", return_indexers=True)
|
| 265 |
+
|
| 266 |
+
# 1 is in idx2, so it should be x2
|
| 267 |
+
eres = Index(2**63 + np.array([1, 1, 2, 5, 7, 9], dtype="uint64"))
|
| 268 |
+
eridx = np.array([0, 1, 2, 3, -1, -1], dtype=np.intp)
|
| 269 |
+
elidx = np.array([0, 0, 1, 2, 3, 4], dtype=np.intp)
|
| 270 |
+
|
| 271 |
+
tm.assert_index_equal(res, eres)
|
| 272 |
+
tm.assert_numpy_array_equal(lidx, elidx)
|
| 273 |
+
tm.assert_numpy_array_equal(ridx, eridx)
|
| 274 |
+
|
| 275 |
+
def test_join_right(self, index_large):
|
| 276 |
+
other = Index(2**63 + np.array([7, 12, 25, 1, 2, 10], dtype="uint64"))
|
| 277 |
+
other_mono = Index(2**63 + np.array([1, 2, 7, 10, 12, 25], dtype="uint64"))
|
| 278 |
+
|
| 279 |
+
# not monotonic
|
| 280 |
+
res, lidx, ridx = index_large.join(other, how="right", return_indexers=True)
|
| 281 |
+
eres = other
|
| 282 |
+
elidx = np.array([-1, -1, 4, -1, -1, 1], dtype=np.intp)
|
| 283 |
+
|
| 284 |
+
tm.assert_numpy_array_equal(lidx, elidx)
|
| 285 |
+
assert isinstance(other, Index) and other.dtype == np.uint64
|
| 286 |
+
tm.assert_index_equal(res, eres)
|
| 287 |
+
assert ridx is None
|
| 288 |
+
|
| 289 |
+
# monotonic
|
| 290 |
+
res, lidx, ridx = index_large.join(
|
| 291 |
+
other_mono, how="right", return_indexers=True
|
| 292 |
+
)
|
| 293 |
+
eres = other_mono
|
| 294 |
+
elidx = np.array([-1, -1, -1, 1, -1, 4], dtype=np.intp)
|
| 295 |
+
|
| 296 |
+
assert isinstance(other, Index) and other.dtype == np.uint64
|
| 297 |
+
tm.assert_numpy_array_equal(lidx, elidx)
|
| 298 |
+
tm.assert_index_equal(res, eres)
|
| 299 |
+
assert ridx is None
|
| 300 |
+
|
| 301 |
+
# non-unique
|
| 302 |
+
idx = Index(2**63 + np.array([1, 1, 2, 5], dtype="uint64"))
|
| 303 |
+
idx2 = Index(2**63 + np.array([1, 2, 5, 7, 9], dtype="uint64"))
|
| 304 |
+
res, lidx, ridx = idx.join(idx2, how="right", return_indexers=True)
|
| 305 |
+
|
| 306 |
+
# 1 is in idx2, so it should be x2
|
| 307 |
+
eres = Index(2**63 + np.array([1, 1, 2, 5, 7, 9], dtype="uint64"))
|
| 308 |
+
elidx = np.array([0, 1, 2, 3, -1, -1], dtype=np.intp)
|
| 309 |
+
eridx = np.array([0, 0, 1, 2, 3, 4], dtype=np.intp)
|
| 310 |
+
|
| 311 |
+
tm.assert_index_equal(res, eres)
|
| 312 |
+
tm.assert_numpy_array_equal(lidx, elidx)
|
| 313 |
+
tm.assert_numpy_array_equal(ridx, eridx)
|
| 314 |
+
|
| 315 |
+
def test_join_non_int_index(self, index_large):
|
| 316 |
+
other = Index(
|
| 317 |
+
2**63 + np.array([1, 5, 7, 10, 20], dtype="uint64"), dtype=object
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
outer = index_large.join(other, how="outer")
|
| 321 |
+
outer2 = other.join(index_large, how="outer")
|
| 322 |
+
expected = Index(
|
| 323 |
+
2**63 + np.array([0, 1, 5, 7, 10, 15, 20, 25], dtype="uint64")
|
| 324 |
+
)
|
| 325 |
+
tm.assert_index_equal(outer, outer2)
|
| 326 |
+
tm.assert_index_equal(outer, expected)
|
| 327 |
+
|
| 328 |
+
inner = index_large.join(other, how="inner")
|
| 329 |
+
inner2 = other.join(index_large, how="inner")
|
| 330 |
+
expected = Index(2**63 + np.array([10, 20], dtype="uint64"))
|
| 331 |
+
tm.assert_index_equal(inner, inner2)
|
| 332 |
+
tm.assert_index_equal(inner, expected)
|
| 333 |
+
|
| 334 |
+
left = index_large.join(other, how="left")
|
| 335 |
+
tm.assert_index_equal(left, index_large.astype(object))
|
| 336 |
+
|
| 337 |
+
left2 = other.join(index_large, how="left")
|
| 338 |
+
tm.assert_index_equal(left2, other)
|
| 339 |
+
|
| 340 |
+
right = index_large.join(other, how="right")
|
| 341 |
+
tm.assert_index_equal(right, other)
|
| 342 |
+
|
| 343 |
+
right2 = other.join(index_large, how="right")
|
| 344 |
+
tm.assert_index_equal(right2, index_large.astype(object))
|
| 345 |
+
|
| 346 |
+
def test_join_outer(self, index_large):
|
| 347 |
+
other = Index(2**63 + np.array([7, 12, 25, 1, 2, 10], dtype="uint64"))
|
| 348 |
+
other_mono = Index(2**63 + np.array([1, 2, 7, 10, 12, 25], dtype="uint64"))
|
| 349 |
+
|
| 350 |
+
# not monotonic
|
| 351 |
+
# guarantee of sortedness
|
| 352 |
+
res, lidx, ridx = index_large.join(other, how="outer", return_indexers=True)
|
| 353 |
+
noidx_res = index_large.join(other, how="outer")
|
| 354 |
+
tm.assert_index_equal(res, noidx_res)
|
| 355 |
+
|
| 356 |
+
eres = Index(
|
| 357 |
+
2**63 + np.array([0, 1, 2, 7, 10, 12, 15, 20, 25], dtype="uint64")
|
| 358 |
+
)
|
| 359 |
+
elidx = np.array([0, -1, -1, -1, 1, -1, 2, 3, 4], dtype=np.intp)
|
| 360 |
+
eridx = np.array([-1, 3, 4, 0, 5, 1, -1, -1, 2], dtype=np.intp)
|
| 361 |
+
|
| 362 |
+
assert isinstance(res, Index) and res.dtype == np.uint64
|
| 363 |
+
tm.assert_index_equal(res, eres)
|
| 364 |
+
tm.assert_numpy_array_equal(lidx, elidx)
|
| 365 |
+
tm.assert_numpy_array_equal(ridx, eridx)
|
| 366 |
+
|
| 367 |
+
# monotonic
|
| 368 |
+
res, lidx, ridx = index_large.join(
|
| 369 |
+
other_mono, how="outer", return_indexers=True
|
| 370 |
+
)
|
| 371 |
+
noidx_res = index_large.join(other_mono, how="outer")
|
| 372 |
+
tm.assert_index_equal(res, noidx_res)
|
| 373 |
+
|
| 374 |
+
elidx = np.array([0, -1, -1, -1, 1, -1, 2, 3, 4], dtype=np.intp)
|
| 375 |
+
eridx = np.array([-1, 0, 1, 2, 3, 4, -1, -1, 5], dtype=np.intp)
|
| 376 |
+
|
| 377 |
+
assert isinstance(res, Index) and res.dtype == np.uint64
|
| 378 |
+
tm.assert_index_equal(res, eres)
|
| 379 |
+
tm.assert_numpy_array_equal(lidx, elidx)
|
| 380 |
+
tm.assert_numpy_array_equal(ridx, eridx)
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/numeric/test_numeric.py
ADDED
|
@@ -0,0 +1,553 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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m
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class TestFloatNumericIndex:
|
| 13 |
+
@pytest.fixture(params=[np.float64, np.float32])
|
| 14 |
+
def dtype(self, request):
|
| 15 |
+
return request.param
|
| 16 |
+
|
| 17 |
+
@pytest.fixture
|
| 18 |
+
def simple_index(self, dtype):
|
| 19 |
+
values = np.arange(5, dtype=dtype)
|
| 20 |
+
return Index(values)
|
| 21 |
+
|
| 22 |
+
@pytest.fixture(
|
| 23 |
+
params=[
|
| 24 |
+
[1.5, 2, 3, 4, 5],
|
| 25 |
+
[0.0, 2.5, 5.0, 7.5, 10.0],
|
| 26 |
+
[5, 4, 3, 2, 1.5],
|
| 27 |
+
[10.0, 7.5, 5.0, 2.5, 0.0],
|
| 28 |
+
],
|
| 29 |
+
ids=["mixed", "float", "mixed_dec", "float_dec"],
|
| 30 |
+
)
|
| 31 |
+
def index(self, request, dtype):
|
| 32 |
+
return Index(request.param, dtype=dtype)
|
| 33 |
+
|
| 34 |
+
@pytest.fixture
|
| 35 |
+
def mixed_index(self, dtype):
|
| 36 |
+
return Index([1.5, 2, 3, 4, 5], dtype=dtype)
|
| 37 |
+
|
| 38 |
+
@pytest.fixture
|
| 39 |
+
def float_index(self, dtype):
|
| 40 |
+
return Index([0.0, 2.5, 5.0, 7.5, 10.0], dtype=dtype)
|
| 41 |
+
|
| 42 |
+
def test_repr_roundtrip(self, index):
|
| 43 |
+
tm.assert_index_equal(eval(repr(index)), index, exact=True)
|
| 44 |
+
|
| 45 |
+
def check_coerce(self, a, b, is_float_index=True):
|
| 46 |
+
assert a.equals(b)
|
| 47 |
+
tm.assert_index_equal(a, b, exact=False)
|
| 48 |
+
if is_float_index:
|
| 49 |
+
assert isinstance(b, Index)
|
| 50 |
+
else:
|
| 51 |
+
assert type(b) is Index
|
| 52 |
+
|
| 53 |
+
def test_constructor_from_list_no_dtype(self):
|
| 54 |
+
index = Index([1.5, 2.5, 3.5])
|
| 55 |
+
assert index.dtype == np.float64
|
| 56 |
+
|
| 57 |
+
def test_constructor(self, dtype):
|
| 58 |
+
index_cls = Index
|
| 59 |
+
|
| 60 |
+
# explicit construction
|
| 61 |
+
index = index_cls([1, 2, 3, 4, 5], dtype=dtype)
|
| 62 |
+
|
| 63 |
+
assert isinstance(index, index_cls)
|
| 64 |
+
assert index.dtype == dtype
|
| 65 |
+
|
| 66 |
+
expected = np.array([1, 2, 3, 4, 5], dtype=dtype)
|
| 67 |
+
tm.assert_numpy_array_equal(index.values, expected)
|
| 68 |
+
|
| 69 |
+
index = index_cls(np.array([1, 2, 3, 4, 5]), dtype=dtype)
|
| 70 |
+
assert isinstance(index, index_cls)
|
| 71 |
+
assert index.dtype == dtype
|
| 72 |
+
|
| 73 |
+
index = index_cls([1.0, 2, 3, 4, 5], dtype=dtype)
|
| 74 |
+
assert isinstance(index, index_cls)
|
| 75 |
+
assert index.dtype == dtype
|
| 76 |
+
|
| 77 |
+
index = index_cls(np.array([1.0, 2, 3, 4, 5]), dtype=dtype)
|
| 78 |
+
assert isinstance(index, index_cls)
|
| 79 |
+
assert index.dtype == dtype
|
| 80 |
+
|
| 81 |
+
index = index_cls([1.0, 2, 3, 4, 5], dtype=dtype)
|
| 82 |
+
assert isinstance(index, index_cls)
|
| 83 |
+
assert index.dtype == dtype
|
| 84 |
+
|
| 85 |
+
index = index_cls(np.array([1.0, 2, 3, 4, 5]), dtype=dtype)
|
| 86 |
+
assert isinstance(index, index_cls)
|
| 87 |
+
assert index.dtype == dtype
|
| 88 |
+
|
| 89 |
+
# nan handling
|
| 90 |
+
result = index_cls([np.nan, np.nan], dtype=dtype)
|
| 91 |
+
assert pd.isna(result.values).all()
|
| 92 |
+
|
| 93 |
+
result = index_cls(np.array([np.nan]), dtype=dtype)
|
| 94 |
+
assert pd.isna(result.values).all()
|
| 95 |
+
|
| 96 |
+
def test_constructor_invalid(self):
|
| 97 |
+
index_cls = Index
|
| 98 |
+
cls_name = index_cls.__name__
|
| 99 |
+
# invalid
|
| 100 |
+
msg = (
|
| 101 |
+
rf"{cls_name}\(\.\.\.\) must be called with a collection of "
|
| 102 |
+
r"some kind, 0\.0 was passed"
|
| 103 |
+
)
|
| 104 |
+
with pytest.raises(TypeError, match=msg):
|
| 105 |
+
index_cls(0.0)
|
| 106 |
+
|
| 107 |
+
def test_constructor_coerce(self, mixed_index, float_index):
|
| 108 |
+
self.check_coerce(mixed_index, Index([1.5, 2, 3, 4, 5]))
|
| 109 |
+
self.check_coerce(float_index, Index(np.arange(5) * 2.5))
|
| 110 |
+
|
| 111 |
+
result = Index(np.array(np.arange(5) * 2.5, dtype=object))
|
| 112 |
+
assert result.dtype == object # as of 2.0 to match Series
|
| 113 |
+
self.check_coerce(float_index, result.astype("float64"))
|
| 114 |
+
|
| 115 |
+
def test_constructor_explicit(self, mixed_index, float_index):
|
| 116 |
+
# these don't auto convert
|
| 117 |
+
self.check_coerce(
|
| 118 |
+
float_index, Index((np.arange(5) * 2.5), dtype=object), is_float_index=False
|
| 119 |
+
)
|
| 120 |
+
self.check_coerce(
|
| 121 |
+
mixed_index, Index([1.5, 2, 3, 4, 5], dtype=object), is_float_index=False
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
def test_type_coercion_fail(self, any_int_numpy_dtype):
|
| 125 |
+
# see gh-15832
|
| 126 |
+
msg = "Trying to coerce float values to integers"
|
| 127 |
+
with pytest.raises(ValueError, match=msg):
|
| 128 |
+
Index([1, 2, 3.5], dtype=any_int_numpy_dtype)
|
| 129 |
+
|
| 130 |
+
def test_equals_numeric(self):
|
| 131 |
+
index_cls = Index
|
| 132 |
+
|
| 133 |
+
idx = index_cls([1.0, 2.0])
|
| 134 |
+
assert idx.equals(idx)
|
| 135 |
+
assert idx.identical(idx)
|
| 136 |
+
|
| 137 |
+
idx2 = index_cls([1.0, 2.0])
|
| 138 |
+
assert idx.equals(idx2)
|
| 139 |
+
|
| 140 |
+
idx = index_cls([1.0, np.nan])
|
| 141 |
+
assert idx.equals(idx)
|
| 142 |
+
assert idx.identical(idx)
|
| 143 |
+
|
| 144 |
+
idx2 = index_cls([1.0, np.nan])
|
| 145 |
+
assert idx.equals(idx2)
|
| 146 |
+
|
| 147 |
+
@pytest.mark.parametrize(
|
| 148 |
+
"other",
|
| 149 |
+
(
|
| 150 |
+
Index([1, 2], dtype=np.int64),
|
| 151 |
+
Index([1.0, 2.0], dtype=object),
|
| 152 |
+
Index([1, 2], dtype=object),
|
| 153 |
+
),
|
| 154 |
+
)
|
| 155 |
+
def test_equals_numeric_other_index_type(self, other):
|
| 156 |
+
idx = Index([1.0, 2.0])
|
| 157 |
+
assert idx.equals(other)
|
| 158 |
+
assert other.equals(idx)
|
| 159 |
+
|
| 160 |
+
@pytest.mark.parametrize(
|
| 161 |
+
"vals",
|
| 162 |
+
[
|
| 163 |
+
pd.date_range("2016-01-01", periods=3),
|
| 164 |
+
pd.timedelta_range("1 Day", periods=3),
|
| 165 |
+
],
|
| 166 |
+
)
|
| 167 |
+
def test_lookups_datetimelike_values(self, vals, dtype):
|
| 168 |
+
# If we have datetime64 or timedelta64 values, make sure they are
|
| 169 |
+
# wrapped correctly GH#31163
|
| 170 |
+
ser = Series(vals, index=range(3, 6))
|
| 171 |
+
ser.index = ser.index.astype(dtype)
|
| 172 |
+
|
| 173 |
+
expected = vals[1]
|
| 174 |
+
|
| 175 |
+
result = ser[4.0]
|
| 176 |
+
assert isinstance(result, type(expected)) and result == expected
|
| 177 |
+
result = ser[4]
|
| 178 |
+
assert isinstance(result, type(expected)) and result == expected
|
| 179 |
+
|
| 180 |
+
result = ser.loc[4.0]
|
| 181 |
+
assert isinstance(result, type(expected)) and result == expected
|
| 182 |
+
result = ser.loc[4]
|
| 183 |
+
assert isinstance(result, type(expected)) and result == expected
|
| 184 |
+
|
| 185 |
+
result = ser.at[4.0]
|
| 186 |
+
assert isinstance(result, type(expected)) and result == expected
|
| 187 |
+
# GH#31329 .at[4] should cast to 4.0, matching .loc behavior
|
| 188 |
+
result = ser.at[4]
|
| 189 |
+
assert isinstance(result, type(expected)) and result == expected
|
| 190 |
+
|
| 191 |
+
result = ser.iloc[1]
|
| 192 |
+
assert isinstance(result, type(expected)) and result == expected
|
| 193 |
+
|
| 194 |
+
result = ser.iat[1]
|
| 195 |
+
assert isinstance(result, type(expected)) and result == expected
|
| 196 |
+
|
| 197 |
+
def test_doesnt_contain_all_the_things(self):
|
| 198 |
+
idx = Index([np.nan])
|
| 199 |
+
assert not idx.isin([0]).item()
|
| 200 |
+
assert not idx.isin([1]).item()
|
| 201 |
+
assert idx.isin([np.nan]).item()
|
| 202 |
+
|
| 203 |
+
def test_nan_multiple_containment(self):
|
| 204 |
+
index_cls = Index
|
| 205 |
+
|
| 206 |
+
idx = index_cls([1.0, np.nan])
|
| 207 |
+
tm.assert_numpy_array_equal(idx.isin([1.0]), np.array([True, False]))
|
| 208 |
+
tm.assert_numpy_array_equal(idx.isin([2.0, np.pi]), np.array([False, False]))
|
| 209 |
+
tm.assert_numpy_array_equal(idx.isin([np.nan]), np.array([False, True]))
|
| 210 |
+
tm.assert_numpy_array_equal(idx.isin([1.0, np.nan]), np.array([True, True]))
|
| 211 |
+
idx = index_cls([1.0, 2.0])
|
| 212 |
+
tm.assert_numpy_array_equal(idx.isin([np.nan]), np.array([False, False]))
|
| 213 |
+
|
| 214 |
+
def test_fillna_float64(self):
|
| 215 |
+
index_cls = Index
|
| 216 |
+
# GH 11343
|
| 217 |
+
idx = Index([1.0, np.nan, 3.0], dtype=float, name="x")
|
| 218 |
+
# can't downcast
|
| 219 |
+
exp = Index([1.0, 0.1, 3.0], name="x")
|
| 220 |
+
tm.assert_index_equal(idx.fillna(0.1), exp, exact=True)
|
| 221 |
+
|
| 222 |
+
# downcast
|
| 223 |
+
exp = index_cls([1.0, 2.0, 3.0], name="x")
|
| 224 |
+
tm.assert_index_equal(idx.fillna(2), exp)
|
| 225 |
+
|
| 226 |
+
# object
|
| 227 |
+
exp = Index([1.0, "obj", 3.0], name="x")
|
| 228 |
+
tm.assert_index_equal(idx.fillna("obj"), exp, exact=True)
|
| 229 |
+
|
| 230 |
+
def test_logical_compat(self, simple_index):
|
| 231 |
+
idx = simple_index
|
| 232 |
+
assert idx.all() == idx.values.all()
|
| 233 |
+
assert idx.any() == idx.values.any()
|
| 234 |
+
|
| 235 |
+
assert idx.all() == idx.to_series().all()
|
| 236 |
+
assert idx.any() == idx.to_series().any()
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
class TestNumericInt:
|
| 240 |
+
@pytest.fixture(params=[np.int64, np.int32, np.int16, np.int8, np.uint64])
|
| 241 |
+
def dtype(self, request):
|
| 242 |
+
return request.param
|
| 243 |
+
|
| 244 |
+
@pytest.fixture
|
| 245 |
+
def simple_index(self, dtype):
|
| 246 |
+
return Index(range(0, 20, 2), dtype=dtype)
|
| 247 |
+
|
| 248 |
+
def test_is_monotonic(self):
|
| 249 |
+
index_cls = Index
|
| 250 |
+
|
| 251 |
+
index = index_cls([1, 2, 3, 4])
|
| 252 |
+
assert index.is_monotonic_increasing is True
|
| 253 |
+
assert index.is_monotonic_increasing is True
|
| 254 |
+
assert index._is_strictly_monotonic_increasing is True
|
| 255 |
+
assert index.is_monotonic_decreasing is False
|
| 256 |
+
assert index._is_strictly_monotonic_decreasing is False
|
| 257 |
+
|
| 258 |
+
index = index_cls([4, 3, 2, 1])
|
| 259 |
+
assert index.is_monotonic_increasing is False
|
| 260 |
+
assert index._is_strictly_monotonic_increasing is False
|
| 261 |
+
assert index._is_strictly_monotonic_decreasing is True
|
| 262 |
+
|
| 263 |
+
index = index_cls([1])
|
| 264 |
+
assert index.is_monotonic_increasing is True
|
| 265 |
+
assert index.is_monotonic_increasing is True
|
| 266 |
+
assert index.is_monotonic_decreasing is True
|
| 267 |
+
assert index._is_strictly_monotonic_increasing is True
|
| 268 |
+
assert index._is_strictly_monotonic_decreasing is True
|
| 269 |
+
|
| 270 |
+
def test_is_strictly_monotonic(self):
|
| 271 |
+
index_cls = Index
|
| 272 |
+
|
| 273 |
+
index = index_cls([1, 1, 2, 3])
|
| 274 |
+
assert index.is_monotonic_increasing is True
|
| 275 |
+
assert index._is_strictly_monotonic_increasing is False
|
| 276 |
+
|
| 277 |
+
index = index_cls([3, 2, 1, 1])
|
| 278 |
+
assert index.is_monotonic_decreasing is True
|
| 279 |
+
assert index._is_strictly_monotonic_decreasing is False
|
| 280 |
+
|
| 281 |
+
index = index_cls([1, 1])
|
| 282 |
+
assert index.is_monotonic_increasing
|
| 283 |
+
assert index.is_monotonic_decreasing
|
| 284 |
+
assert not index._is_strictly_monotonic_increasing
|
| 285 |
+
assert not index._is_strictly_monotonic_decreasing
|
| 286 |
+
|
| 287 |
+
def test_logical_compat(self, simple_index):
|
| 288 |
+
idx = simple_index
|
| 289 |
+
assert idx.all() == idx.values.all()
|
| 290 |
+
assert idx.any() == idx.values.any()
|
| 291 |
+
|
| 292 |
+
def test_identical(self, simple_index, dtype):
|
| 293 |
+
index = simple_index
|
| 294 |
+
|
| 295 |
+
idx = Index(index.copy())
|
| 296 |
+
assert idx.identical(index)
|
| 297 |
+
|
| 298 |
+
same_values_different_type = Index(idx, dtype=object)
|
| 299 |
+
assert not idx.identical(same_values_different_type)
|
| 300 |
+
|
| 301 |
+
idx = index.astype(dtype=object)
|
| 302 |
+
idx = idx.rename("foo")
|
| 303 |
+
same_values = Index(idx, dtype=object)
|
| 304 |
+
assert same_values.identical(idx)
|
| 305 |
+
|
| 306 |
+
assert not idx.identical(index)
|
| 307 |
+
assert Index(same_values, name="foo", dtype=object).identical(idx)
|
| 308 |
+
|
| 309 |
+
assert not index.astype(dtype=object).identical(index.astype(dtype=dtype))
|
| 310 |
+
|
| 311 |
+
def test_cant_or_shouldnt_cast(self, dtype):
|
| 312 |
+
msg = r"invalid literal for int\(\) with base 10: 'foo'"
|
| 313 |
+
|
| 314 |
+
# can't
|
| 315 |
+
data = ["foo", "bar", "baz"]
|
| 316 |
+
with pytest.raises(ValueError, match=msg):
|
| 317 |
+
Index(data, dtype=dtype)
|
| 318 |
+
|
| 319 |
+
def test_view_index(self, simple_index):
|
| 320 |
+
index = simple_index
|
| 321 |
+
msg = "Passing a type in .*Index.view is deprecated"
|
| 322 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 323 |
+
index.view(Index)
|
| 324 |
+
|
| 325 |
+
def test_prevent_casting(self, simple_index):
|
| 326 |
+
index = simple_index
|
| 327 |
+
result = index.astype("O")
|
| 328 |
+
assert result.dtype == np.object_
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
class TestIntNumericIndex:
|
| 332 |
+
@pytest.fixture(params=[np.int64, np.int32, np.int16, np.int8])
|
| 333 |
+
def dtype(self, request):
|
| 334 |
+
return request.param
|
| 335 |
+
|
| 336 |
+
def test_constructor_from_list_no_dtype(self):
|
| 337 |
+
index = Index([1, 2, 3])
|
| 338 |
+
assert index.dtype == np.int64
|
| 339 |
+
|
| 340 |
+
def test_constructor(self, dtype):
|
| 341 |
+
index_cls = Index
|
| 342 |
+
|
| 343 |
+
# scalar raise Exception
|
| 344 |
+
msg = (
|
| 345 |
+
rf"{index_cls.__name__}\(\.\.\.\) must be called with a collection of some "
|
| 346 |
+
"kind, 5 was passed"
|
| 347 |
+
)
|
| 348 |
+
with pytest.raises(TypeError, match=msg):
|
| 349 |
+
index_cls(5)
|
| 350 |
+
|
| 351 |
+
# copy
|
| 352 |
+
# pass list, coerce fine
|
| 353 |
+
index = index_cls([-5, 0, 1, 2], dtype=dtype)
|
| 354 |
+
arr = index.values.copy()
|
| 355 |
+
new_index = index_cls(arr, copy=True)
|
| 356 |
+
tm.assert_index_equal(new_index, index, exact=True)
|
| 357 |
+
val = int(arr[0]) + 3000
|
| 358 |
+
|
| 359 |
+
# this should not change index
|
| 360 |
+
if dtype != np.int8:
|
| 361 |
+
# NEP 50 won't allow assignment that would overflow
|
| 362 |
+
arr[0] = val
|
| 363 |
+
assert new_index[0] != val
|
| 364 |
+
|
| 365 |
+
if dtype == np.int64:
|
| 366 |
+
# pass list, coerce fine
|
| 367 |
+
index = index_cls([-5, 0, 1, 2], dtype=dtype)
|
| 368 |
+
expected = Index([-5, 0, 1, 2], dtype=dtype)
|
| 369 |
+
tm.assert_index_equal(index, expected)
|
| 370 |
+
|
| 371 |
+
# from iterable
|
| 372 |
+
index = index_cls(iter([-5, 0, 1, 2]), dtype=dtype)
|
| 373 |
+
expected = index_cls([-5, 0, 1, 2], dtype=dtype)
|
| 374 |
+
tm.assert_index_equal(index, expected, exact=True)
|
| 375 |
+
|
| 376 |
+
# interpret list-like
|
| 377 |
+
expected = index_cls([5, 0], dtype=dtype)
|
| 378 |
+
for cls in [Index, index_cls]:
|
| 379 |
+
for idx in [
|
| 380 |
+
cls([5, 0], dtype=dtype),
|
| 381 |
+
cls(np.array([5, 0]), dtype=dtype),
|
| 382 |
+
cls(Series([5, 0]), dtype=dtype),
|
| 383 |
+
]:
|
| 384 |
+
tm.assert_index_equal(idx, expected)
|
| 385 |
+
|
| 386 |
+
def test_constructor_corner(self, dtype):
|
| 387 |
+
index_cls = Index
|
| 388 |
+
|
| 389 |
+
arr = np.array([1, 2, 3, 4], dtype=object)
|
| 390 |
+
|
| 391 |
+
index = index_cls(arr, dtype=dtype)
|
| 392 |
+
assert index.values.dtype == index.dtype
|
| 393 |
+
if dtype == np.int64:
|
| 394 |
+
without_dtype = Index(arr)
|
| 395 |
+
# as of 2.0 we do not infer a dtype when we get an object-dtype
|
| 396 |
+
# ndarray of numbers, matching Series behavior
|
| 397 |
+
assert without_dtype.dtype == object
|
| 398 |
+
|
| 399 |
+
tm.assert_index_equal(index, without_dtype.astype(np.int64))
|
| 400 |
+
|
| 401 |
+
# preventing casting
|
| 402 |
+
arr = np.array([1, "2", 3, "4"], dtype=object)
|
| 403 |
+
msg = "Trying to coerce float values to integers"
|
| 404 |
+
with pytest.raises(ValueError, match=msg):
|
| 405 |
+
index_cls(arr, dtype=dtype)
|
| 406 |
+
|
| 407 |
+
def test_constructor_coercion_signed_to_unsigned(
|
| 408 |
+
self,
|
| 409 |
+
any_unsigned_int_numpy_dtype,
|
| 410 |
+
):
|
| 411 |
+
# see gh-15832
|
| 412 |
+
msg = "|".join(
|
| 413 |
+
[
|
| 414 |
+
"Trying to coerce negative values to unsigned integers",
|
| 415 |
+
"The elements provided in the data cannot all be casted",
|
| 416 |
+
]
|
| 417 |
+
)
|
| 418 |
+
with pytest.raises(OverflowError, match=msg):
|
| 419 |
+
Index([-1], dtype=any_unsigned_int_numpy_dtype)
|
| 420 |
+
|
| 421 |
+
def test_constructor_np_signed(self, any_signed_int_numpy_dtype):
|
| 422 |
+
# GH#47475
|
| 423 |
+
scalar = np.dtype(any_signed_int_numpy_dtype).type(1)
|
| 424 |
+
result = Index([scalar])
|
| 425 |
+
expected = Index([1], dtype=any_signed_int_numpy_dtype)
|
| 426 |
+
tm.assert_index_equal(result, expected, exact=True)
|
| 427 |
+
|
| 428 |
+
def test_constructor_np_unsigned(self, any_unsigned_int_numpy_dtype):
|
| 429 |
+
# GH#47475
|
| 430 |
+
scalar = np.dtype(any_unsigned_int_numpy_dtype).type(1)
|
| 431 |
+
result = Index([scalar])
|
| 432 |
+
expected = Index([1], dtype=any_unsigned_int_numpy_dtype)
|
| 433 |
+
tm.assert_index_equal(result, expected, exact=True)
|
| 434 |
+
|
| 435 |
+
def test_coerce_list(self):
|
| 436 |
+
# coerce things
|
| 437 |
+
arr = Index([1, 2, 3, 4])
|
| 438 |
+
assert isinstance(arr, Index)
|
| 439 |
+
|
| 440 |
+
# but not if explicit dtype passed
|
| 441 |
+
arr = Index([1, 2, 3, 4], dtype=object)
|
| 442 |
+
assert type(arr) is Index
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
class TestFloat16Index:
|
| 446 |
+
# float 16 indexes not supported
|
| 447 |
+
# GH 49535
|
| 448 |
+
def test_constructor(self):
|
| 449 |
+
index_cls = Index
|
| 450 |
+
dtype = np.float16
|
| 451 |
+
|
| 452 |
+
msg = "float16 indexes are not supported"
|
| 453 |
+
|
| 454 |
+
# explicit construction
|
| 455 |
+
with pytest.raises(NotImplementedError, match=msg):
|
| 456 |
+
index_cls([1, 2, 3, 4, 5], dtype=dtype)
|
| 457 |
+
|
| 458 |
+
with pytest.raises(NotImplementedError, match=msg):
|
| 459 |
+
index_cls(np.array([1, 2, 3, 4, 5]), dtype=dtype)
|
| 460 |
+
|
| 461 |
+
with pytest.raises(NotImplementedError, match=msg):
|
| 462 |
+
index_cls([1.0, 2, 3, 4, 5], dtype=dtype)
|
| 463 |
+
|
| 464 |
+
with pytest.raises(NotImplementedError, match=msg):
|
| 465 |
+
index_cls(np.array([1.0, 2, 3, 4, 5]), dtype=dtype)
|
| 466 |
+
|
| 467 |
+
with pytest.raises(NotImplementedError, match=msg):
|
| 468 |
+
index_cls([1.0, 2, 3, 4, 5], dtype=dtype)
|
| 469 |
+
|
| 470 |
+
with pytest.raises(NotImplementedError, match=msg):
|
| 471 |
+
index_cls(np.array([1.0, 2, 3, 4, 5]), dtype=dtype)
|
| 472 |
+
|
| 473 |
+
# nan handling
|
| 474 |
+
with pytest.raises(NotImplementedError, match=msg):
|
| 475 |
+
index_cls([np.nan, np.nan], dtype=dtype)
|
| 476 |
+
|
| 477 |
+
with pytest.raises(NotImplementedError, match=msg):
|
| 478 |
+
index_cls(np.array([np.nan]), dtype=dtype)
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
@pytest.mark.parametrize(
|
| 482 |
+
"box",
|
| 483 |
+
[list, lambda x: np.array(x, dtype=object), lambda x: Index(x, dtype=object)],
|
| 484 |
+
)
|
| 485 |
+
def test_uint_index_does_not_convert_to_float64(box):
|
| 486 |
+
# https://github.com/pandas-dev/pandas/issues/28279
|
| 487 |
+
# https://github.com/pandas-dev/pandas/issues/28023
|
| 488 |
+
series = Series(
|
| 489 |
+
[0, 1, 2, 3, 4, 5],
|
| 490 |
+
index=[
|
| 491 |
+
7606741985629028552,
|
| 492 |
+
17876870360202815256,
|
| 493 |
+
17876870360202815256,
|
| 494 |
+
13106359306506049338,
|
| 495 |
+
8991270399732411471,
|
| 496 |
+
8991270399732411472,
|
| 497 |
+
],
|
| 498 |
+
)
|
| 499 |
+
|
| 500 |
+
result = series.loc[box([7606741985629028552, 17876870360202815256])]
|
| 501 |
+
|
| 502 |
+
expected = Index(
|
| 503 |
+
[7606741985629028552, 17876870360202815256, 17876870360202815256],
|
| 504 |
+
dtype="uint64",
|
| 505 |
+
)
|
| 506 |
+
tm.assert_index_equal(result.index, expected)
|
| 507 |
+
|
| 508 |
+
tm.assert_equal(result, series.iloc[:3])
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
def test_float64_index_equals():
|
| 512 |
+
# https://github.com/pandas-dev/pandas/issues/35217
|
| 513 |
+
float_index = Index([1.0, 2, 3])
|
| 514 |
+
string_index = Index(["1", "2", "3"])
|
| 515 |
+
|
| 516 |
+
result = float_index.equals(string_index)
|
| 517 |
+
assert result is False
|
| 518 |
+
|
| 519 |
+
result = string_index.equals(float_index)
|
| 520 |
+
assert result is False
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
def test_map_dtype_inference_unsigned_to_signed():
|
| 524 |
+
# GH#44609 cases where we don't retain dtype
|
| 525 |
+
idx = Index([1, 2, 3], dtype=np.uint64)
|
| 526 |
+
result = idx.map(lambda x: -x)
|
| 527 |
+
expected = Index([-1, -2, -3], dtype=np.int64)
|
| 528 |
+
tm.assert_index_equal(result, expected)
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
def test_map_dtype_inference_overflows():
|
| 532 |
+
# GH#44609 case where we have to upcast
|
| 533 |
+
idx = Index(np.array([1, 2, 3], dtype=np.int8))
|
| 534 |
+
result = idx.map(lambda x: x * 1000)
|
| 535 |
+
# TODO: we could plausibly try to infer down to int16 here
|
| 536 |
+
expected = Index([1000, 2000, 3000], dtype=np.int64)
|
| 537 |
+
tm.assert_index_equal(result, expected)
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
def test_view_to_datetimelike():
|
| 541 |
+
# GH#55710
|
| 542 |
+
idx = Index([1, 2, 3])
|
| 543 |
+
res = idx.view("m8[s]")
|
| 544 |
+
expected = pd.TimedeltaIndex(idx.values.view("m8[s]"))
|
| 545 |
+
tm.assert_index_equal(res, expected)
|
| 546 |
+
|
| 547 |
+
res2 = idx.view("m8[D]")
|
| 548 |
+
expected2 = idx.values.view("m8[D]")
|
| 549 |
+
tm.assert_numpy_array_equal(res2, expected2)
|
| 550 |
+
|
| 551 |
+
res3 = idx.view("M8[h]")
|
| 552 |
+
expected3 = idx.values.view("M8[h]")
|
| 553 |
+
tm.assert_numpy_array_equal(res3, expected3)
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/numeric/test_setops.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import (
|
| 2 |
+
datetime,
|
| 3 |
+
timedelta,
|
| 4 |
+
)
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pytest
|
| 8 |
+
|
| 9 |
+
import pandas._testing as tm
|
| 10 |
+
from pandas.core.indexes.api import (
|
| 11 |
+
Index,
|
| 12 |
+
RangeIndex,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@pytest.fixture
|
| 17 |
+
def index_large():
|
| 18 |
+
# large values used in TestUInt64Index where no compat needed with int64/float64
|
| 19 |
+
large = [2**63, 2**63 + 10, 2**63 + 15, 2**63 + 20, 2**63 + 25]
|
| 20 |
+
return Index(large, dtype=np.uint64)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class TestSetOps:
|
| 24 |
+
@pytest.mark.parametrize("dtype", ["f8", "u8", "i8"])
|
| 25 |
+
def test_union_non_numeric(self, dtype):
|
| 26 |
+
# corner case, non-numeric
|
| 27 |
+
index = Index(np.arange(5, dtype=dtype), dtype=dtype)
|
| 28 |
+
assert index.dtype == dtype
|
| 29 |
+
|
| 30 |
+
other = Index([datetime.now() + timedelta(i) for i in range(4)], dtype=object)
|
| 31 |
+
result = index.union(other)
|
| 32 |
+
expected = Index(np.concatenate((index, other)))
|
| 33 |
+
tm.assert_index_equal(result, expected)
|
| 34 |
+
|
| 35 |
+
result = other.union(index)
|
| 36 |
+
expected = Index(np.concatenate((other, index)))
|
| 37 |
+
tm.assert_index_equal(result, expected)
|
| 38 |
+
|
| 39 |
+
def test_intersection(self):
|
| 40 |
+
index = Index(range(5), dtype=np.int64)
|
| 41 |
+
|
| 42 |
+
other = Index([1, 2, 3, 4, 5])
|
| 43 |
+
result = index.intersection(other)
|
| 44 |
+
expected = Index(np.sort(np.intersect1d(index.values, other.values)))
|
| 45 |
+
tm.assert_index_equal(result, expected)
|
| 46 |
+
|
| 47 |
+
result = other.intersection(index)
|
| 48 |
+
expected = Index(
|
| 49 |
+
np.sort(np.asarray(np.intersect1d(index.values, other.values)))
|
| 50 |
+
)
|
| 51 |
+
tm.assert_index_equal(result, expected)
|
| 52 |
+
|
| 53 |
+
@pytest.mark.parametrize("dtype", ["int64", "uint64"])
|
| 54 |
+
def test_int_float_union_dtype(self, dtype):
|
| 55 |
+
# https://github.com/pandas-dev/pandas/issues/26778
|
| 56 |
+
# [u]int | float -> float
|
| 57 |
+
index = Index([0, 2, 3], dtype=dtype)
|
| 58 |
+
other = Index([0.5, 1.5], dtype=np.float64)
|
| 59 |
+
expected = Index([0.0, 0.5, 1.5, 2.0, 3.0], dtype=np.float64)
|
| 60 |
+
result = index.union(other)
|
| 61 |
+
tm.assert_index_equal(result, expected)
|
| 62 |
+
|
| 63 |
+
result = other.union(index)
|
| 64 |
+
tm.assert_index_equal(result, expected)
|
| 65 |
+
|
| 66 |
+
def test_range_float_union_dtype(self):
|
| 67 |
+
# https://github.com/pandas-dev/pandas/issues/26778
|
| 68 |
+
index = RangeIndex(start=0, stop=3)
|
| 69 |
+
other = Index([0.5, 1.5], dtype=np.float64)
|
| 70 |
+
result = index.union(other)
|
| 71 |
+
expected = Index([0.0, 0.5, 1, 1.5, 2.0], dtype=np.float64)
|
| 72 |
+
tm.assert_index_equal(result, expected)
|
| 73 |
+
|
| 74 |
+
result = other.union(index)
|
| 75 |
+
tm.assert_index_equal(result, expected)
|
| 76 |
+
|
| 77 |
+
def test_range_uint64_union_dtype(self):
|
| 78 |
+
# https://github.com/pandas-dev/pandas/issues/26778
|
| 79 |
+
index = RangeIndex(start=0, stop=3)
|
| 80 |
+
other = Index([0, 10], dtype=np.uint64)
|
| 81 |
+
result = index.union(other)
|
| 82 |
+
expected = Index([0, 1, 2, 10], dtype=object)
|
| 83 |
+
tm.assert_index_equal(result, expected)
|
| 84 |
+
|
| 85 |
+
result = other.union(index)
|
| 86 |
+
tm.assert_index_equal(result, expected)
|
| 87 |
+
|
| 88 |
+
def test_float64_index_difference(self):
|
| 89 |
+
# https://github.com/pandas-dev/pandas/issues/35217
|
| 90 |
+
float_index = Index([1.0, 2, 3])
|
| 91 |
+
string_index = Index(["1", "2", "3"])
|
| 92 |
+
|
| 93 |
+
result = float_index.difference(string_index)
|
| 94 |
+
tm.assert_index_equal(result, float_index)
|
| 95 |
+
|
| 96 |
+
result = string_index.difference(float_index)
|
| 97 |
+
tm.assert_index_equal(result, string_index)
|
| 98 |
+
|
| 99 |
+
def test_intersection_uint64_outside_int64_range(self, index_large):
|
| 100 |
+
other = Index([2**63, 2**63 + 5, 2**63 + 10, 2**63 + 15, 2**63 + 20])
|
| 101 |
+
result = index_large.intersection(other)
|
| 102 |
+
expected = Index(np.sort(np.intersect1d(index_large.values, other.values)))
|
| 103 |
+
tm.assert_index_equal(result, expected)
|
| 104 |
+
|
| 105 |
+
result = other.intersection(index_large)
|
| 106 |
+
expected = Index(
|
| 107 |
+
np.sort(np.asarray(np.intersect1d(index_large.values, other.values)))
|
| 108 |
+
)
|
| 109 |
+
tm.assert_index_equal(result, expected)
|
| 110 |
+
|
| 111 |
+
@pytest.mark.parametrize(
|
| 112 |
+
"index2,keeps_name",
|
| 113 |
+
[
|
| 114 |
+
(Index([4, 7, 6, 5, 3], name="index"), True),
|
| 115 |
+
(Index([4, 7, 6, 5, 3], name="other"), False),
|
| 116 |
+
],
|
| 117 |
+
)
|
| 118 |
+
def test_intersection_monotonic(self, index2, keeps_name, sort):
|
| 119 |
+
index1 = Index([5, 3, 2, 4, 1], name="index")
|
| 120 |
+
expected = Index([5, 3, 4])
|
| 121 |
+
|
| 122 |
+
if keeps_name:
|
| 123 |
+
expected.name = "index"
|
| 124 |
+
|
| 125 |
+
result = index1.intersection(index2, sort=sort)
|
| 126 |
+
if sort is None:
|
| 127 |
+
expected = expected.sort_values()
|
| 128 |
+
tm.assert_index_equal(result, expected)
|
| 129 |
+
|
| 130 |
+
def test_symmetric_difference(self, sort):
|
| 131 |
+
# smoke
|
| 132 |
+
index1 = Index([5, 2, 3, 4], name="index1")
|
| 133 |
+
index2 = Index([2, 3, 4, 1])
|
| 134 |
+
result = index1.symmetric_difference(index2, sort=sort)
|
| 135 |
+
expected = Index([5, 1])
|
| 136 |
+
if sort is not None:
|
| 137 |
+
tm.assert_index_equal(result, expected)
|
| 138 |
+
else:
|
| 139 |
+
tm.assert_index_equal(result, expected.sort_values())
|
| 140 |
+
assert result.name is None
|
| 141 |
+
if sort is None:
|
| 142 |
+
expected = expected.sort_values()
|
| 143 |
+
tm.assert_index_equal(result, expected)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class TestSetOpsSort:
|
| 147 |
+
@pytest.mark.parametrize("slice_", [slice(None), slice(0)])
|
| 148 |
+
def test_union_sort_other_special(self, slice_):
|
| 149 |
+
# https://github.com/pandas-dev/pandas/issues/24959
|
| 150 |
+
|
| 151 |
+
idx = Index([1, 0, 2])
|
| 152 |
+
# default, sort=None
|
| 153 |
+
other = idx[slice_]
|
| 154 |
+
tm.assert_index_equal(idx.union(other), idx)
|
| 155 |
+
tm.assert_index_equal(other.union(idx), idx)
|
| 156 |
+
|
| 157 |
+
# sort=False
|
| 158 |
+
tm.assert_index_equal(idx.union(other, sort=False), idx)
|
| 159 |
+
|
| 160 |
+
@pytest.mark.parametrize("slice_", [slice(None), slice(0)])
|
| 161 |
+
def test_union_sort_special_true(self, slice_):
|
| 162 |
+
idx = Index([1, 0, 2])
|
| 163 |
+
# default, sort=None
|
| 164 |
+
other = idx[slice_]
|
| 165 |
+
|
| 166 |
+
result = idx.union(other, sort=True)
|
| 167 |
+
expected = Index([0, 1, 2])
|
| 168 |
+
tm.assert_index_equal(result, expected)
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/test_any_index.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests that can be parametrized over _any_ Index object.
|
| 3 |
+
"""
|
| 4 |
+
import re
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pytest
|
| 8 |
+
|
| 9 |
+
from pandas.errors import InvalidIndexError
|
| 10 |
+
|
| 11 |
+
import pandas._testing as tm
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def test_boolean_context_compat(index):
|
| 15 |
+
# GH#7897
|
| 16 |
+
with pytest.raises(ValueError, match="The truth value of a"):
|
| 17 |
+
if index:
|
| 18 |
+
pass
|
| 19 |
+
|
| 20 |
+
with pytest.raises(ValueError, match="The truth value of a"):
|
| 21 |
+
bool(index)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def test_sort(index):
|
| 25 |
+
msg = "cannot sort an Index object in-place, use sort_values instead"
|
| 26 |
+
with pytest.raises(TypeError, match=msg):
|
| 27 |
+
index.sort()
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def test_hash_error(index):
|
| 31 |
+
with pytest.raises(TypeError, match=f"unhashable type: '{type(index).__name__}'"):
|
| 32 |
+
hash(index)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def test_mutability(index):
|
| 36 |
+
if not len(index):
|
| 37 |
+
pytest.skip("Test doesn't make sense for empty index")
|
| 38 |
+
msg = "Index does not support mutable operations"
|
| 39 |
+
with pytest.raises(TypeError, match=msg):
|
| 40 |
+
index[0] = index[0]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
| 44 |
+
def test_map_identity_mapping(index, request):
|
| 45 |
+
# GH#12766
|
| 46 |
+
|
| 47 |
+
result = index.map(lambda x: x)
|
| 48 |
+
if index.dtype == object and result.dtype == bool:
|
| 49 |
+
assert (index == result).all()
|
| 50 |
+
# TODO: could work that into the 'exact="equiv"'?
|
| 51 |
+
return # FIXME: doesn't belong in this file anymore!
|
| 52 |
+
tm.assert_index_equal(result, index, exact="equiv")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def test_wrong_number_names(index):
|
| 56 |
+
names = index.nlevels * ["apple", "banana", "carrot"]
|
| 57 |
+
with pytest.raises(ValueError, match="^Length"):
|
| 58 |
+
index.names = names
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def test_view_preserves_name(index):
|
| 62 |
+
assert index.view().name == index.name
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def test_ravel(index):
|
| 66 |
+
# GH#19956 ravel returning ndarray is deprecated, in 2.0 returns a view on self
|
| 67 |
+
res = index.ravel()
|
| 68 |
+
tm.assert_index_equal(res, index)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class TestConversion:
|
| 72 |
+
def test_to_series(self, index):
|
| 73 |
+
# assert that we are creating a copy of the index
|
| 74 |
+
|
| 75 |
+
ser = index.to_series()
|
| 76 |
+
assert ser.values is not index.values
|
| 77 |
+
assert ser.index is not index
|
| 78 |
+
assert ser.name == index.name
|
| 79 |
+
|
| 80 |
+
def test_to_series_with_arguments(self, index):
|
| 81 |
+
# GH#18699
|
| 82 |
+
|
| 83 |
+
# index kwarg
|
| 84 |
+
ser = index.to_series(index=index)
|
| 85 |
+
|
| 86 |
+
assert ser.values is not index.values
|
| 87 |
+
assert ser.index is index
|
| 88 |
+
assert ser.name == index.name
|
| 89 |
+
|
| 90 |
+
# name kwarg
|
| 91 |
+
ser = index.to_series(name="__test")
|
| 92 |
+
|
| 93 |
+
assert ser.values is not index.values
|
| 94 |
+
assert ser.index is not index
|
| 95 |
+
assert ser.name != index.name
|
| 96 |
+
|
| 97 |
+
def test_tolist_matches_list(self, index):
|
| 98 |
+
assert index.tolist() == list(index)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class TestRoundTrips:
|
| 102 |
+
def test_pickle_roundtrip(self, index):
|
| 103 |
+
result = tm.round_trip_pickle(index)
|
| 104 |
+
tm.assert_index_equal(result, index, exact=True)
|
| 105 |
+
if result.nlevels > 1:
|
| 106 |
+
# GH#8367 round-trip with timezone
|
| 107 |
+
assert index.equal_levels(result)
|
| 108 |
+
|
| 109 |
+
def test_pickle_preserves_name(self, index):
|
| 110 |
+
original_name, index.name = index.name, "foo"
|
| 111 |
+
unpickled = tm.round_trip_pickle(index)
|
| 112 |
+
assert index.equals(unpickled)
|
| 113 |
+
index.name = original_name
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class TestIndexing:
|
| 117 |
+
def test_get_loc_listlike_raises_invalid_index_error(self, index):
|
| 118 |
+
# and never TypeError
|
| 119 |
+
key = np.array([0, 1], dtype=np.intp)
|
| 120 |
+
|
| 121 |
+
with pytest.raises(InvalidIndexError, match=r"\[0 1\]"):
|
| 122 |
+
index.get_loc(key)
|
| 123 |
+
|
| 124 |
+
with pytest.raises(InvalidIndexError, match=r"\[False True\]"):
|
| 125 |
+
index.get_loc(key.astype(bool))
|
| 126 |
+
|
| 127 |
+
def test_getitem_ellipsis(self, index):
|
| 128 |
+
# GH#21282
|
| 129 |
+
result = index[...]
|
| 130 |
+
assert result.equals(index)
|
| 131 |
+
assert result is not index
|
| 132 |
+
|
| 133 |
+
def test_slice_keeps_name(self, index):
|
| 134 |
+
assert index.name == index[1:].name
|
| 135 |
+
|
| 136 |
+
@pytest.mark.parametrize("item", [101, "no_int", 2.5])
|
| 137 |
+
def test_getitem_error(self, index, item):
|
| 138 |
+
msg = "|".join(
|
| 139 |
+
[
|
| 140 |
+
r"index 101 is out of bounds for axis 0 with size [\d]+",
|
| 141 |
+
re.escape(
|
| 142 |
+
"only integers, slices (`:`), ellipsis (`...`), "
|
| 143 |
+
"numpy.newaxis (`None`) and integer or boolean arrays "
|
| 144 |
+
"are valid indices"
|
| 145 |
+
),
|
| 146 |
+
"index out of bounds", # string[pyarrow]
|
| 147 |
+
]
|
| 148 |
+
)
|
| 149 |
+
with pytest.raises(IndexError, match=msg):
|
| 150 |
+
index[item]
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class TestRendering:
|
| 154 |
+
def test_str(self, index):
|
| 155 |
+
# test the string repr
|
| 156 |
+
index.name = "foo"
|
| 157 |
+
assert "'foo'" in str(index)
|
| 158 |
+
assert type(index).__name__ in str(index)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class TestReductions:
|
| 162 |
+
def test_argmax_axis_invalid(self, index):
|
| 163 |
+
# GH#23081
|
| 164 |
+
msg = r"`axis` must be fewer than the number of dimensions \(1\)"
|
| 165 |
+
with pytest.raises(ValueError, match=msg):
|
| 166 |
+
index.argmax(axis=1)
|
| 167 |
+
with pytest.raises(ValueError, match=msg):
|
| 168 |
+
index.argmin(axis=2)
|
| 169 |
+
with pytest.raises(ValueError, match=msg):
|
| 170 |
+
index.min(axis=-2)
|
| 171 |
+
with pytest.raises(ValueError, match=msg):
|
| 172 |
+
index.max(axis=-3)
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/test_base.py
ADDED
|
@@ -0,0 +1,1737 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import defaultdict
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
from functools import partial
|
| 4 |
+
import math
|
| 5 |
+
import operator
|
| 6 |
+
import re
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pytest
|
| 10 |
+
|
| 11 |
+
from pandas.compat import IS64
|
| 12 |
+
from pandas.errors import InvalidIndexError
|
| 13 |
+
import pandas.util._test_decorators as td
|
| 14 |
+
|
| 15 |
+
from pandas.core.dtypes.common import (
|
| 16 |
+
is_any_real_numeric_dtype,
|
| 17 |
+
is_numeric_dtype,
|
| 18 |
+
is_object_dtype,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
import pandas as pd
|
| 22 |
+
from pandas import (
|
| 23 |
+
CategoricalIndex,
|
| 24 |
+
DataFrame,
|
| 25 |
+
DatetimeIndex,
|
| 26 |
+
IntervalIndex,
|
| 27 |
+
PeriodIndex,
|
| 28 |
+
RangeIndex,
|
| 29 |
+
Series,
|
| 30 |
+
TimedeltaIndex,
|
| 31 |
+
date_range,
|
| 32 |
+
period_range,
|
| 33 |
+
timedelta_range,
|
| 34 |
+
)
|
| 35 |
+
import pandas._testing as tm
|
| 36 |
+
from pandas.core.indexes.api import (
|
| 37 |
+
Index,
|
| 38 |
+
MultiIndex,
|
| 39 |
+
_get_combined_index,
|
| 40 |
+
ensure_index,
|
| 41 |
+
ensure_index_from_sequences,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class TestIndex:
|
| 46 |
+
@pytest.fixture
|
| 47 |
+
def simple_index(self) -> Index:
|
| 48 |
+
return Index(list("abcde"))
|
| 49 |
+
|
| 50 |
+
def test_can_hold_identifiers(self, simple_index):
|
| 51 |
+
index = simple_index
|
| 52 |
+
key = index[0]
|
| 53 |
+
assert index._can_hold_identifiers_and_holds_name(key) is True
|
| 54 |
+
|
| 55 |
+
@pytest.mark.parametrize("index", ["datetime"], indirect=True)
|
| 56 |
+
def test_new_axis(self, index):
|
| 57 |
+
# TODO: a bunch of scattered tests check this deprecation is enforced.
|
| 58 |
+
# de-duplicate/centralize them.
|
| 59 |
+
with pytest.raises(ValueError, match="Multi-dimensional indexing"):
|
| 60 |
+
# GH#30588 multi-dimensional indexing deprecated
|
| 61 |
+
index[None, :]
|
| 62 |
+
|
| 63 |
+
def test_constructor_regular(self, index):
|
| 64 |
+
tm.assert_contains_all(index, index)
|
| 65 |
+
|
| 66 |
+
@pytest.mark.parametrize("index", ["string"], indirect=True)
|
| 67 |
+
def test_constructor_casting(self, index):
|
| 68 |
+
# casting
|
| 69 |
+
arr = np.array(index)
|
| 70 |
+
new_index = Index(arr)
|
| 71 |
+
tm.assert_contains_all(arr, new_index)
|
| 72 |
+
tm.assert_index_equal(index, new_index)
|
| 73 |
+
|
| 74 |
+
def test_constructor_copy(self, using_infer_string):
|
| 75 |
+
index = Index(list("abc"), name="name")
|
| 76 |
+
arr = np.array(index)
|
| 77 |
+
new_index = Index(arr, copy=True, name="name")
|
| 78 |
+
assert isinstance(new_index, Index)
|
| 79 |
+
assert new_index.name == "name"
|
| 80 |
+
if using_infer_string:
|
| 81 |
+
tm.assert_extension_array_equal(
|
| 82 |
+
new_index.values, pd.array(arr, dtype="string[pyarrow_numpy]")
|
| 83 |
+
)
|
| 84 |
+
else:
|
| 85 |
+
tm.assert_numpy_array_equal(arr, new_index.values)
|
| 86 |
+
arr[0] = "SOMEBIGLONGSTRING"
|
| 87 |
+
assert new_index[0] != "SOMEBIGLONGSTRING"
|
| 88 |
+
|
| 89 |
+
@pytest.mark.parametrize("cast_as_obj", [True, False])
|
| 90 |
+
@pytest.mark.parametrize(
|
| 91 |
+
"index",
|
| 92 |
+
[
|
| 93 |
+
date_range(
|
| 94 |
+
"2015-01-01 10:00",
|
| 95 |
+
freq="D",
|
| 96 |
+
periods=3,
|
| 97 |
+
tz="US/Eastern",
|
| 98 |
+
name="Green Eggs & Ham",
|
| 99 |
+
), # DTI with tz
|
| 100 |
+
date_range("2015-01-01 10:00", freq="D", periods=3), # DTI no tz
|
| 101 |
+
timedelta_range("1 days", freq="D", periods=3), # td
|
| 102 |
+
period_range("2015-01-01", freq="D", periods=3), # period
|
| 103 |
+
],
|
| 104 |
+
)
|
| 105 |
+
def test_constructor_from_index_dtlike(self, cast_as_obj, index):
|
| 106 |
+
if cast_as_obj:
|
| 107 |
+
with tm.assert_produces_warning(FutureWarning, match="Dtype inference"):
|
| 108 |
+
result = Index(index.astype(object))
|
| 109 |
+
else:
|
| 110 |
+
result = Index(index)
|
| 111 |
+
|
| 112 |
+
tm.assert_index_equal(result, index)
|
| 113 |
+
|
| 114 |
+
if isinstance(index, DatetimeIndex):
|
| 115 |
+
assert result.tz == index.tz
|
| 116 |
+
if cast_as_obj:
|
| 117 |
+
# GH#23524 check that Index(dti, dtype=object) does not
|
| 118 |
+
# incorrectly raise ValueError, and that nanoseconds are not
|
| 119 |
+
# dropped
|
| 120 |
+
index += pd.Timedelta(nanoseconds=50)
|
| 121 |
+
result = Index(index, dtype=object)
|
| 122 |
+
assert result.dtype == np.object_
|
| 123 |
+
assert list(result) == list(index)
|
| 124 |
+
|
| 125 |
+
@pytest.mark.parametrize(
|
| 126 |
+
"index,has_tz",
|
| 127 |
+
[
|
| 128 |
+
(
|
| 129 |
+
date_range("2015-01-01 10:00", freq="D", periods=3, tz="US/Eastern"),
|
| 130 |
+
True,
|
| 131 |
+
), # datetimetz
|
| 132 |
+
(timedelta_range("1 days", freq="D", periods=3), False), # td
|
| 133 |
+
(period_range("2015-01-01", freq="D", periods=3), False), # period
|
| 134 |
+
],
|
| 135 |
+
)
|
| 136 |
+
def test_constructor_from_series_dtlike(self, index, has_tz):
|
| 137 |
+
result = Index(Series(index))
|
| 138 |
+
tm.assert_index_equal(result, index)
|
| 139 |
+
|
| 140 |
+
if has_tz:
|
| 141 |
+
assert result.tz == index.tz
|
| 142 |
+
|
| 143 |
+
def test_constructor_from_series_freq(self):
|
| 144 |
+
# GH 6273
|
| 145 |
+
# create from a series, passing a freq
|
| 146 |
+
dts = ["1-1-1990", "2-1-1990", "3-1-1990", "4-1-1990", "5-1-1990"]
|
| 147 |
+
expected = DatetimeIndex(dts, freq="MS")
|
| 148 |
+
|
| 149 |
+
s = Series(pd.to_datetime(dts))
|
| 150 |
+
result = DatetimeIndex(s, freq="MS")
|
| 151 |
+
|
| 152 |
+
tm.assert_index_equal(result, expected)
|
| 153 |
+
|
| 154 |
+
def test_constructor_from_frame_series_freq(self, using_infer_string):
|
| 155 |
+
# GH 6273
|
| 156 |
+
# create from a series, passing a freq
|
| 157 |
+
dts = ["1-1-1990", "2-1-1990", "3-1-1990", "4-1-1990", "5-1-1990"]
|
| 158 |
+
expected = DatetimeIndex(dts, freq="MS")
|
| 159 |
+
|
| 160 |
+
df = DataFrame(np.random.default_rng(2).random((5, 3)))
|
| 161 |
+
df["date"] = dts
|
| 162 |
+
result = DatetimeIndex(df["date"], freq="MS")
|
| 163 |
+
dtype = object if not using_infer_string else "string"
|
| 164 |
+
assert df["date"].dtype == dtype
|
| 165 |
+
expected.name = "date"
|
| 166 |
+
tm.assert_index_equal(result, expected)
|
| 167 |
+
|
| 168 |
+
expected = Series(dts, name="date")
|
| 169 |
+
tm.assert_series_equal(df["date"], expected)
|
| 170 |
+
|
| 171 |
+
# GH 6274
|
| 172 |
+
# infer freq of same
|
| 173 |
+
if not using_infer_string:
|
| 174 |
+
# Doesn't work with arrow strings
|
| 175 |
+
freq = pd.infer_freq(df["date"])
|
| 176 |
+
assert freq == "MS"
|
| 177 |
+
|
| 178 |
+
def test_constructor_int_dtype_nan(self):
|
| 179 |
+
# see gh-15187
|
| 180 |
+
data = [np.nan]
|
| 181 |
+
expected = Index(data, dtype=np.float64)
|
| 182 |
+
result = Index(data, dtype="float")
|
| 183 |
+
tm.assert_index_equal(result, expected)
|
| 184 |
+
|
| 185 |
+
@pytest.mark.parametrize(
|
| 186 |
+
"klass,dtype,na_val",
|
| 187 |
+
[
|
| 188 |
+
(Index, np.float64, np.nan),
|
| 189 |
+
(DatetimeIndex, "datetime64[ns]", pd.NaT),
|
| 190 |
+
],
|
| 191 |
+
)
|
| 192 |
+
def test_index_ctor_infer_nan_nat(self, klass, dtype, na_val):
|
| 193 |
+
# GH 13467
|
| 194 |
+
na_list = [na_val, na_val]
|
| 195 |
+
expected = klass(na_list)
|
| 196 |
+
assert expected.dtype == dtype
|
| 197 |
+
|
| 198 |
+
result = Index(na_list)
|
| 199 |
+
tm.assert_index_equal(result, expected)
|
| 200 |
+
|
| 201 |
+
result = Index(np.array(na_list))
|
| 202 |
+
tm.assert_index_equal(result, expected)
|
| 203 |
+
|
| 204 |
+
@pytest.mark.parametrize(
|
| 205 |
+
"vals,dtype",
|
| 206 |
+
[
|
| 207 |
+
([1, 2, 3, 4, 5], "int"),
|
| 208 |
+
([1.1, np.nan, 2.2, 3.0], "float"),
|
| 209 |
+
(["A", "B", "C", np.nan], "obj"),
|
| 210 |
+
],
|
| 211 |
+
)
|
| 212 |
+
def test_constructor_simple_new(self, vals, dtype):
|
| 213 |
+
index = Index(vals, name=dtype)
|
| 214 |
+
result = index._simple_new(index.values, dtype)
|
| 215 |
+
tm.assert_index_equal(result, index)
|
| 216 |
+
|
| 217 |
+
@pytest.mark.parametrize("attr", ["values", "asi8"])
|
| 218 |
+
@pytest.mark.parametrize("klass", [Index, DatetimeIndex])
|
| 219 |
+
def test_constructor_dtypes_datetime(self, tz_naive_fixture, attr, klass):
|
| 220 |
+
# Test constructing with a datetimetz dtype
|
| 221 |
+
# .values produces numpy datetimes, so these are considered naive
|
| 222 |
+
# .asi8 produces integers, so these are considered epoch timestamps
|
| 223 |
+
# ^the above will be true in a later version. Right now we `.view`
|
| 224 |
+
# the i8 values as NS_DTYPE, effectively treating them as wall times.
|
| 225 |
+
index = date_range("2011-01-01", periods=5)
|
| 226 |
+
arg = getattr(index, attr)
|
| 227 |
+
index = index.tz_localize(tz_naive_fixture)
|
| 228 |
+
dtype = index.dtype
|
| 229 |
+
|
| 230 |
+
# As of 2.0 astype raises on dt64.astype(dt64tz)
|
| 231 |
+
err = tz_naive_fixture is not None
|
| 232 |
+
msg = "Cannot use .astype to convert from timezone-naive dtype to"
|
| 233 |
+
|
| 234 |
+
if attr == "asi8":
|
| 235 |
+
result = DatetimeIndex(arg).tz_localize(tz_naive_fixture)
|
| 236 |
+
tm.assert_index_equal(result, index)
|
| 237 |
+
elif klass is Index:
|
| 238 |
+
with pytest.raises(TypeError, match="unexpected keyword"):
|
| 239 |
+
klass(arg, tz=tz_naive_fixture)
|
| 240 |
+
else:
|
| 241 |
+
result = klass(arg, tz=tz_naive_fixture)
|
| 242 |
+
tm.assert_index_equal(result, index)
|
| 243 |
+
|
| 244 |
+
if attr == "asi8":
|
| 245 |
+
if err:
|
| 246 |
+
with pytest.raises(TypeError, match=msg):
|
| 247 |
+
DatetimeIndex(arg).astype(dtype)
|
| 248 |
+
else:
|
| 249 |
+
result = DatetimeIndex(arg).astype(dtype)
|
| 250 |
+
tm.assert_index_equal(result, index)
|
| 251 |
+
else:
|
| 252 |
+
result = klass(arg, dtype=dtype)
|
| 253 |
+
tm.assert_index_equal(result, index)
|
| 254 |
+
|
| 255 |
+
if attr == "asi8":
|
| 256 |
+
result = DatetimeIndex(list(arg)).tz_localize(tz_naive_fixture)
|
| 257 |
+
tm.assert_index_equal(result, index)
|
| 258 |
+
elif klass is Index:
|
| 259 |
+
with pytest.raises(TypeError, match="unexpected keyword"):
|
| 260 |
+
klass(arg, tz=tz_naive_fixture)
|
| 261 |
+
else:
|
| 262 |
+
result = klass(list(arg), tz=tz_naive_fixture)
|
| 263 |
+
tm.assert_index_equal(result, index)
|
| 264 |
+
|
| 265 |
+
if attr == "asi8":
|
| 266 |
+
if err:
|
| 267 |
+
with pytest.raises(TypeError, match=msg):
|
| 268 |
+
DatetimeIndex(list(arg)).astype(dtype)
|
| 269 |
+
else:
|
| 270 |
+
result = DatetimeIndex(list(arg)).astype(dtype)
|
| 271 |
+
tm.assert_index_equal(result, index)
|
| 272 |
+
else:
|
| 273 |
+
result = klass(list(arg), dtype=dtype)
|
| 274 |
+
tm.assert_index_equal(result, index)
|
| 275 |
+
|
| 276 |
+
@pytest.mark.parametrize("attr", ["values", "asi8"])
|
| 277 |
+
@pytest.mark.parametrize("klass", [Index, TimedeltaIndex])
|
| 278 |
+
def test_constructor_dtypes_timedelta(self, attr, klass):
|
| 279 |
+
index = timedelta_range("1 days", periods=5)
|
| 280 |
+
index = index._with_freq(None) # won't be preserved by constructors
|
| 281 |
+
dtype = index.dtype
|
| 282 |
+
|
| 283 |
+
values = getattr(index, attr)
|
| 284 |
+
|
| 285 |
+
result = klass(values, dtype=dtype)
|
| 286 |
+
tm.assert_index_equal(result, index)
|
| 287 |
+
|
| 288 |
+
result = klass(list(values), dtype=dtype)
|
| 289 |
+
tm.assert_index_equal(result, index)
|
| 290 |
+
|
| 291 |
+
@pytest.mark.parametrize("value", [[], iter([]), (_ for _ in [])])
|
| 292 |
+
@pytest.mark.parametrize(
|
| 293 |
+
"klass",
|
| 294 |
+
[
|
| 295 |
+
Index,
|
| 296 |
+
CategoricalIndex,
|
| 297 |
+
DatetimeIndex,
|
| 298 |
+
TimedeltaIndex,
|
| 299 |
+
],
|
| 300 |
+
)
|
| 301 |
+
def test_constructor_empty(self, value, klass):
|
| 302 |
+
empty = klass(value)
|
| 303 |
+
assert isinstance(empty, klass)
|
| 304 |
+
assert not len(empty)
|
| 305 |
+
|
| 306 |
+
@pytest.mark.parametrize(
|
| 307 |
+
"empty,klass",
|
| 308 |
+
[
|
| 309 |
+
(PeriodIndex([], freq="D"), PeriodIndex),
|
| 310 |
+
(PeriodIndex(iter([]), freq="D"), PeriodIndex),
|
| 311 |
+
(PeriodIndex((_ for _ in []), freq="D"), PeriodIndex),
|
| 312 |
+
(RangeIndex(step=1), RangeIndex),
|
| 313 |
+
(MultiIndex(levels=[[1, 2], ["blue", "red"]], codes=[[], []]), MultiIndex),
|
| 314 |
+
],
|
| 315 |
+
)
|
| 316 |
+
def test_constructor_empty_special(self, empty, klass):
|
| 317 |
+
assert isinstance(empty, klass)
|
| 318 |
+
assert not len(empty)
|
| 319 |
+
|
| 320 |
+
@pytest.mark.parametrize(
|
| 321 |
+
"index",
|
| 322 |
+
[
|
| 323 |
+
"datetime",
|
| 324 |
+
"float64",
|
| 325 |
+
"float32",
|
| 326 |
+
"int64",
|
| 327 |
+
"int32",
|
| 328 |
+
"period",
|
| 329 |
+
"range",
|
| 330 |
+
"repeats",
|
| 331 |
+
"timedelta",
|
| 332 |
+
"tuples",
|
| 333 |
+
"uint64",
|
| 334 |
+
"uint32",
|
| 335 |
+
],
|
| 336 |
+
indirect=True,
|
| 337 |
+
)
|
| 338 |
+
def test_view_with_args(self, index):
|
| 339 |
+
index.view("i8")
|
| 340 |
+
|
| 341 |
+
@pytest.mark.parametrize(
|
| 342 |
+
"index",
|
| 343 |
+
[
|
| 344 |
+
"string",
|
| 345 |
+
pytest.param("categorical", marks=pytest.mark.xfail(reason="gh-25464")),
|
| 346 |
+
"bool-object",
|
| 347 |
+
"bool-dtype",
|
| 348 |
+
"empty",
|
| 349 |
+
],
|
| 350 |
+
indirect=True,
|
| 351 |
+
)
|
| 352 |
+
def test_view_with_args_object_array_raises(self, index):
|
| 353 |
+
if index.dtype == bool:
|
| 354 |
+
msg = "When changing to a larger dtype"
|
| 355 |
+
with pytest.raises(ValueError, match=msg):
|
| 356 |
+
index.view("i8")
|
| 357 |
+
elif index.dtype == "string":
|
| 358 |
+
with pytest.raises(NotImplementedError, match="i8"):
|
| 359 |
+
index.view("i8")
|
| 360 |
+
else:
|
| 361 |
+
msg = (
|
| 362 |
+
"Cannot change data-type for array of references|"
|
| 363 |
+
"Cannot change data-type for object array|"
|
| 364 |
+
)
|
| 365 |
+
with pytest.raises(TypeError, match=msg):
|
| 366 |
+
index.view("i8")
|
| 367 |
+
|
| 368 |
+
@pytest.mark.parametrize(
|
| 369 |
+
"index",
|
| 370 |
+
["int64", "int32", "range"],
|
| 371 |
+
indirect=True,
|
| 372 |
+
)
|
| 373 |
+
def test_astype(self, index):
|
| 374 |
+
casted = index.astype("i8")
|
| 375 |
+
|
| 376 |
+
# it works!
|
| 377 |
+
casted.get_loc(5)
|
| 378 |
+
|
| 379 |
+
# pass on name
|
| 380 |
+
index.name = "foobar"
|
| 381 |
+
casted = index.astype("i8")
|
| 382 |
+
assert casted.name == "foobar"
|
| 383 |
+
|
| 384 |
+
def test_equals_object(self):
|
| 385 |
+
# same
|
| 386 |
+
assert Index(["a", "b", "c"]).equals(Index(["a", "b", "c"]))
|
| 387 |
+
|
| 388 |
+
@pytest.mark.parametrize(
|
| 389 |
+
"comp", [Index(["a", "b"]), Index(["a", "b", "d"]), ["a", "b", "c"]]
|
| 390 |
+
)
|
| 391 |
+
def test_not_equals_object(self, comp):
|
| 392 |
+
assert not Index(["a", "b", "c"]).equals(comp)
|
| 393 |
+
|
| 394 |
+
def test_identical(self):
|
| 395 |
+
# index
|
| 396 |
+
i1 = Index(["a", "b", "c"])
|
| 397 |
+
i2 = Index(["a", "b", "c"])
|
| 398 |
+
|
| 399 |
+
assert i1.identical(i2)
|
| 400 |
+
|
| 401 |
+
i1 = i1.rename("foo")
|
| 402 |
+
assert i1.equals(i2)
|
| 403 |
+
assert not i1.identical(i2)
|
| 404 |
+
|
| 405 |
+
i2 = i2.rename("foo")
|
| 406 |
+
assert i1.identical(i2)
|
| 407 |
+
|
| 408 |
+
i3 = Index([("a", "a"), ("a", "b"), ("b", "a")])
|
| 409 |
+
i4 = Index([("a", "a"), ("a", "b"), ("b", "a")], tupleize_cols=False)
|
| 410 |
+
assert not i3.identical(i4)
|
| 411 |
+
|
| 412 |
+
def test_is_(self):
|
| 413 |
+
ind = Index(range(10))
|
| 414 |
+
assert ind.is_(ind)
|
| 415 |
+
assert ind.is_(ind.view().view().view().view())
|
| 416 |
+
assert not ind.is_(Index(range(10)))
|
| 417 |
+
assert not ind.is_(ind.copy())
|
| 418 |
+
assert not ind.is_(ind.copy(deep=False))
|
| 419 |
+
assert not ind.is_(ind[:])
|
| 420 |
+
assert not ind.is_(np.array(range(10)))
|
| 421 |
+
|
| 422 |
+
# quasi-implementation dependent
|
| 423 |
+
assert ind.is_(ind.view())
|
| 424 |
+
ind2 = ind.view()
|
| 425 |
+
ind2.name = "bob"
|
| 426 |
+
assert ind.is_(ind2)
|
| 427 |
+
assert ind2.is_(ind)
|
| 428 |
+
# doesn't matter if Indices are *actually* views of underlying data,
|
| 429 |
+
assert not ind.is_(Index(ind.values))
|
| 430 |
+
arr = np.array(range(1, 11))
|
| 431 |
+
ind1 = Index(arr, copy=False)
|
| 432 |
+
ind2 = Index(arr, copy=False)
|
| 433 |
+
assert not ind1.is_(ind2)
|
| 434 |
+
|
| 435 |
+
def test_asof_numeric_vs_bool_raises(self):
|
| 436 |
+
left = Index([1, 2, 3])
|
| 437 |
+
right = Index([True, False], dtype=object)
|
| 438 |
+
|
| 439 |
+
msg = "Cannot compare dtypes int64 and bool"
|
| 440 |
+
with pytest.raises(TypeError, match=msg):
|
| 441 |
+
left.asof(right[0])
|
| 442 |
+
# TODO: should right.asof(left[0]) also raise?
|
| 443 |
+
|
| 444 |
+
with pytest.raises(InvalidIndexError, match=re.escape(str(right))):
|
| 445 |
+
left.asof(right)
|
| 446 |
+
|
| 447 |
+
with pytest.raises(InvalidIndexError, match=re.escape(str(left))):
|
| 448 |
+
right.asof(left)
|
| 449 |
+
|
| 450 |
+
@pytest.mark.parametrize("index", ["string"], indirect=True)
|
| 451 |
+
def test_booleanindex(self, index):
|
| 452 |
+
bool_index = np.ones(len(index), dtype=bool)
|
| 453 |
+
bool_index[5:30:2] = False
|
| 454 |
+
|
| 455 |
+
sub_index = index[bool_index]
|
| 456 |
+
|
| 457 |
+
for i, val in enumerate(sub_index):
|
| 458 |
+
assert sub_index.get_loc(val) == i
|
| 459 |
+
|
| 460 |
+
sub_index = index[list(bool_index)]
|
| 461 |
+
for i, val in enumerate(sub_index):
|
| 462 |
+
assert sub_index.get_loc(val) == i
|
| 463 |
+
|
| 464 |
+
def test_fancy(self, simple_index):
|
| 465 |
+
index = simple_index
|
| 466 |
+
sl = index[[1, 2, 3]]
|
| 467 |
+
for i in sl:
|
| 468 |
+
assert i == sl[sl.get_loc(i)]
|
| 469 |
+
|
| 470 |
+
@pytest.mark.parametrize(
|
| 471 |
+
"index",
|
| 472 |
+
["string", "int64", "int32", "uint64", "uint32", "float64", "float32"],
|
| 473 |
+
indirect=True,
|
| 474 |
+
)
|
| 475 |
+
@pytest.mark.parametrize("dtype", [int, np.bool_])
|
| 476 |
+
def test_empty_fancy(self, index, dtype, request, using_infer_string):
|
| 477 |
+
if dtype is np.bool_ and using_infer_string and index.dtype == "string":
|
| 478 |
+
request.applymarker(pytest.mark.xfail(reason="numpy behavior is buggy"))
|
| 479 |
+
empty_arr = np.array([], dtype=dtype)
|
| 480 |
+
empty_index = type(index)([], dtype=index.dtype)
|
| 481 |
+
|
| 482 |
+
assert index[[]].identical(empty_index)
|
| 483 |
+
if dtype == np.bool_:
|
| 484 |
+
with tm.assert_produces_warning(FutureWarning, match="is deprecated"):
|
| 485 |
+
assert index[empty_arr].identical(empty_index)
|
| 486 |
+
else:
|
| 487 |
+
assert index[empty_arr].identical(empty_index)
|
| 488 |
+
|
| 489 |
+
@pytest.mark.parametrize(
|
| 490 |
+
"index",
|
| 491 |
+
["string", "int64", "int32", "uint64", "uint32", "float64", "float32"],
|
| 492 |
+
indirect=True,
|
| 493 |
+
)
|
| 494 |
+
def test_empty_fancy_raises(self, index):
|
| 495 |
+
# DatetimeIndex is excluded, because it overrides getitem and should
|
| 496 |
+
# be tested separately.
|
| 497 |
+
empty_farr = np.array([], dtype=np.float64)
|
| 498 |
+
empty_index = type(index)([], dtype=index.dtype)
|
| 499 |
+
|
| 500 |
+
assert index[[]].identical(empty_index)
|
| 501 |
+
# np.ndarray only accepts ndarray of int & bool dtypes, so should Index
|
| 502 |
+
msg = r"arrays used as indices must be of integer"
|
| 503 |
+
with pytest.raises(IndexError, match=msg):
|
| 504 |
+
index[empty_farr]
|
| 505 |
+
|
| 506 |
+
def test_union_dt_as_obj(self, simple_index):
|
| 507 |
+
# TODO: Replace with fixturesult
|
| 508 |
+
index = simple_index
|
| 509 |
+
date_index = date_range("2019-01-01", periods=10)
|
| 510 |
+
first_cat = index.union(date_index)
|
| 511 |
+
second_cat = index.union(index)
|
| 512 |
+
|
| 513 |
+
appended = Index(np.append(index, date_index.astype("O")))
|
| 514 |
+
|
| 515 |
+
tm.assert_index_equal(first_cat, appended)
|
| 516 |
+
tm.assert_index_equal(second_cat, index)
|
| 517 |
+
tm.assert_contains_all(index, first_cat)
|
| 518 |
+
tm.assert_contains_all(index, second_cat)
|
| 519 |
+
tm.assert_contains_all(date_index, first_cat)
|
| 520 |
+
|
| 521 |
+
def test_map_with_tuples(self):
|
| 522 |
+
# GH 12766
|
| 523 |
+
|
| 524 |
+
# Test that returning a single tuple from an Index
|
| 525 |
+
# returns an Index.
|
| 526 |
+
index = Index(np.arange(3), dtype=np.int64)
|
| 527 |
+
result = index.map(lambda x: (x,))
|
| 528 |
+
expected = Index([(i,) for i in index])
|
| 529 |
+
tm.assert_index_equal(result, expected)
|
| 530 |
+
|
| 531 |
+
# Test that returning a tuple from a map of a single index
|
| 532 |
+
# returns a MultiIndex object.
|
| 533 |
+
result = index.map(lambda x: (x, x == 1))
|
| 534 |
+
expected = MultiIndex.from_tuples([(i, i == 1) for i in index])
|
| 535 |
+
tm.assert_index_equal(result, expected)
|
| 536 |
+
|
| 537 |
+
def test_map_with_tuples_mi(self):
|
| 538 |
+
# Test that returning a single object from a MultiIndex
|
| 539 |
+
# returns an Index.
|
| 540 |
+
first_level = ["foo", "bar", "baz"]
|
| 541 |
+
multi_index = MultiIndex.from_tuples(zip(first_level, [1, 2, 3]))
|
| 542 |
+
reduced_index = multi_index.map(lambda x: x[0])
|
| 543 |
+
tm.assert_index_equal(reduced_index, Index(first_level))
|
| 544 |
+
|
| 545 |
+
@pytest.mark.parametrize(
|
| 546 |
+
"index",
|
| 547 |
+
[
|
| 548 |
+
date_range("2020-01-01", freq="D", periods=10),
|
| 549 |
+
period_range("2020-01-01", freq="D", periods=10),
|
| 550 |
+
timedelta_range("1 day", periods=10),
|
| 551 |
+
],
|
| 552 |
+
)
|
| 553 |
+
def test_map_tseries_indices_return_index(self, index):
|
| 554 |
+
expected = Index([1] * 10)
|
| 555 |
+
result = index.map(lambda x: 1)
|
| 556 |
+
tm.assert_index_equal(expected, result)
|
| 557 |
+
|
| 558 |
+
def test_map_tseries_indices_accsr_return_index(self):
|
| 559 |
+
date_index = DatetimeIndex(
|
| 560 |
+
date_range("2020-01-01", periods=24, freq="h"), name="hourly"
|
| 561 |
+
)
|
| 562 |
+
result = date_index.map(lambda x: x.hour)
|
| 563 |
+
expected = Index(np.arange(24, dtype="int64"), name="hourly")
|
| 564 |
+
tm.assert_index_equal(result, expected, exact=True)
|
| 565 |
+
|
| 566 |
+
@pytest.mark.parametrize(
|
| 567 |
+
"mapper",
|
| 568 |
+
[
|
| 569 |
+
lambda values, index: {i: e for e, i in zip(values, index)},
|
| 570 |
+
lambda values, index: Series(values, index),
|
| 571 |
+
],
|
| 572 |
+
)
|
| 573 |
+
def test_map_dictlike_simple(self, mapper):
|
| 574 |
+
# GH 12756
|
| 575 |
+
expected = Index(["foo", "bar", "baz"])
|
| 576 |
+
index = Index(np.arange(3), dtype=np.int64)
|
| 577 |
+
result = index.map(mapper(expected.values, index))
|
| 578 |
+
tm.assert_index_equal(result, expected)
|
| 579 |
+
|
| 580 |
+
@pytest.mark.parametrize(
|
| 581 |
+
"mapper",
|
| 582 |
+
[
|
| 583 |
+
lambda values, index: {i: e for e, i in zip(values, index)},
|
| 584 |
+
lambda values, index: Series(values, index),
|
| 585 |
+
],
|
| 586 |
+
)
|
| 587 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
| 588 |
+
def test_map_dictlike(self, index, mapper, request):
|
| 589 |
+
# GH 12756
|
| 590 |
+
if isinstance(index, CategoricalIndex):
|
| 591 |
+
pytest.skip("Tested in test_categorical")
|
| 592 |
+
elif not index.is_unique:
|
| 593 |
+
pytest.skip("Cannot map duplicated index")
|
| 594 |
+
|
| 595 |
+
rng = np.arange(len(index), 0, -1, dtype=np.int64)
|
| 596 |
+
|
| 597 |
+
if index.empty:
|
| 598 |
+
# to match proper result coercion for uints
|
| 599 |
+
expected = Index([])
|
| 600 |
+
elif is_numeric_dtype(index.dtype):
|
| 601 |
+
expected = index._constructor(rng, dtype=index.dtype)
|
| 602 |
+
elif type(index) is Index and index.dtype != object:
|
| 603 |
+
# i.e. EA-backed, for now just Nullable
|
| 604 |
+
expected = Index(rng, dtype=index.dtype)
|
| 605 |
+
else:
|
| 606 |
+
expected = Index(rng)
|
| 607 |
+
|
| 608 |
+
result = index.map(mapper(expected, index))
|
| 609 |
+
tm.assert_index_equal(result, expected)
|
| 610 |
+
|
| 611 |
+
@pytest.mark.parametrize(
|
| 612 |
+
"mapper",
|
| 613 |
+
[Series(["foo", 2.0, "baz"], index=[0, 2, -1]), {0: "foo", 2: 2.0, -1: "baz"}],
|
| 614 |
+
)
|
| 615 |
+
def test_map_with_non_function_missing_values(self, mapper):
|
| 616 |
+
# GH 12756
|
| 617 |
+
expected = Index([2.0, np.nan, "foo"])
|
| 618 |
+
result = Index([2, 1, 0]).map(mapper)
|
| 619 |
+
|
| 620 |
+
tm.assert_index_equal(expected, result)
|
| 621 |
+
|
| 622 |
+
def test_map_na_exclusion(self):
|
| 623 |
+
index = Index([1.5, np.nan, 3, np.nan, 5])
|
| 624 |
+
|
| 625 |
+
result = index.map(lambda x: x * 2, na_action="ignore")
|
| 626 |
+
expected = index * 2
|
| 627 |
+
tm.assert_index_equal(result, expected)
|
| 628 |
+
|
| 629 |
+
def test_map_defaultdict(self):
|
| 630 |
+
index = Index([1, 2, 3])
|
| 631 |
+
default_dict = defaultdict(lambda: "blank")
|
| 632 |
+
default_dict[1] = "stuff"
|
| 633 |
+
result = index.map(default_dict)
|
| 634 |
+
expected = Index(["stuff", "blank", "blank"])
|
| 635 |
+
tm.assert_index_equal(result, expected)
|
| 636 |
+
|
| 637 |
+
@pytest.mark.parametrize("name,expected", [("foo", "foo"), ("bar", None)])
|
| 638 |
+
def test_append_empty_preserve_name(self, name, expected):
|
| 639 |
+
left = Index([], name="foo")
|
| 640 |
+
right = Index([1, 2, 3], name=name)
|
| 641 |
+
|
| 642 |
+
msg = "The behavior of array concatenation with empty entries is deprecated"
|
| 643 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 644 |
+
result = left.append(right)
|
| 645 |
+
assert result.name == expected
|
| 646 |
+
|
| 647 |
+
@pytest.mark.parametrize(
|
| 648 |
+
"index, expected",
|
| 649 |
+
[
|
| 650 |
+
("string", False),
|
| 651 |
+
("bool-object", False),
|
| 652 |
+
("bool-dtype", False),
|
| 653 |
+
("categorical", False),
|
| 654 |
+
("int64", True),
|
| 655 |
+
("int32", True),
|
| 656 |
+
("uint64", True),
|
| 657 |
+
("uint32", True),
|
| 658 |
+
("datetime", False),
|
| 659 |
+
("float64", True),
|
| 660 |
+
("float32", True),
|
| 661 |
+
],
|
| 662 |
+
indirect=["index"],
|
| 663 |
+
)
|
| 664 |
+
def test_is_numeric(self, index, expected):
|
| 665 |
+
assert is_any_real_numeric_dtype(index) is expected
|
| 666 |
+
|
| 667 |
+
@pytest.mark.parametrize(
|
| 668 |
+
"index, expected",
|
| 669 |
+
[
|
| 670 |
+
("string", True),
|
| 671 |
+
("bool-object", True),
|
| 672 |
+
("bool-dtype", False),
|
| 673 |
+
("categorical", False),
|
| 674 |
+
("int64", False),
|
| 675 |
+
("int32", False),
|
| 676 |
+
("uint64", False),
|
| 677 |
+
("uint32", False),
|
| 678 |
+
("datetime", False),
|
| 679 |
+
("float64", False),
|
| 680 |
+
("float32", False),
|
| 681 |
+
],
|
| 682 |
+
indirect=["index"],
|
| 683 |
+
)
|
| 684 |
+
def test_is_object(self, index, expected, using_infer_string):
|
| 685 |
+
if using_infer_string and index.dtype == "string" and expected:
|
| 686 |
+
expected = False
|
| 687 |
+
assert is_object_dtype(index) is expected
|
| 688 |
+
|
| 689 |
+
def test_summary(self, index):
|
| 690 |
+
index._summary()
|
| 691 |
+
|
| 692 |
+
def test_format_bug(self):
|
| 693 |
+
# GH 14626
|
| 694 |
+
# windows has different precision on datetime.datetime.now (it doesn't
|
| 695 |
+
# include us since the default for Timestamp shows these but Index
|
| 696 |
+
# formatting does not we are skipping)
|
| 697 |
+
now = datetime.now()
|
| 698 |
+
msg = r"Index\.format is deprecated"
|
| 699 |
+
|
| 700 |
+
if not str(now).endswith("000"):
|
| 701 |
+
index = Index([now])
|
| 702 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 703 |
+
formatted = index.format()
|
| 704 |
+
expected = [str(index[0])]
|
| 705 |
+
assert formatted == expected
|
| 706 |
+
|
| 707 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 708 |
+
Index([]).format()
|
| 709 |
+
|
| 710 |
+
@pytest.mark.parametrize("vals", [[1, 2.0 + 3.0j, 4.0], ["a", "b", "c"]])
|
| 711 |
+
def test_format_missing(self, vals, nulls_fixture):
|
| 712 |
+
# 2845
|
| 713 |
+
vals = list(vals) # Copy for each iteration
|
| 714 |
+
vals.append(nulls_fixture)
|
| 715 |
+
index = Index(vals, dtype=object)
|
| 716 |
+
# TODO: case with complex dtype?
|
| 717 |
+
|
| 718 |
+
msg = r"Index\.format is deprecated"
|
| 719 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 720 |
+
formatted = index.format()
|
| 721 |
+
null_repr = "NaN" if isinstance(nulls_fixture, float) else str(nulls_fixture)
|
| 722 |
+
expected = [str(index[0]), str(index[1]), str(index[2]), null_repr]
|
| 723 |
+
|
| 724 |
+
assert formatted == expected
|
| 725 |
+
assert index[3] is nulls_fixture
|
| 726 |
+
|
| 727 |
+
@pytest.mark.parametrize("op", ["any", "all"])
|
| 728 |
+
def test_logical_compat(self, op, simple_index):
|
| 729 |
+
index = simple_index
|
| 730 |
+
left = getattr(index, op)()
|
| 731 |
+
assert left == getattr(index.values, op)()
|
| 732 |
+
right = getattr(index.to_series(), op)()
|
| 733 |
+
# left might not match right exactly in e.g. string cases where the
|
| 734 |
+
# because we use np.any/all instead of .any/all
|
| 735 |
+
assert bool(left) == bool(right)
|
| 736 |
+
|
| 737 |
+
@pytest.mark.parametrize(
|
| 738 |
+
"index", ["string", "int64", "int32", "float64", "float32"], indirect=True
|
| 739 |
+
)
|
| 740 |
+
def test_drop_by_str_label(self, index):
|
| 741 |
+
n = len(index)
|
| 742 |
+
drop = index[list(range(5, 10))]
|
| 743 |
+
dropped = index.drop(drop)
|
| 744 |
+
|
| 745 |
+
expected = index[list(range(5)) + list(range(10, n))]
|
| 746 |
+
tm.assert_index_equal(dropped, expected)
|
| 747 |
+
|
| 748 |
+
dropped = index.drop(index[0])
|
| 749 |
+
expected = index[1:]
|
| 750 |
+
tm.assert_index_equal(dropped, expected)
|
| 751 |
+
|
| 752 |
+
@pytest.mark.parametrize(
|
| 753 |
+
"index", ["string", "int64", "int32", "float64", "float32"], indirect=True
|
| 754 |
+
)
|
| 755 |
+
@pytest.mark.parametrize("keys", [["foo", "bar"], ["1", "bar"]])
|
| 756 |
+
def test_drop_by_str_label_raises_missing_keys(self, index, keys):
|
| 757 |
+
with pytest.raises(KeyError, match=""):
|
| 758 |
+
index.drop(keys)
|
| 759 |
+
|
| 760 |
+
@pytest.mark.parametrize(
|
| 761 |
+
"index", ["string", "int64", "int32", "float64", "float32"], indirect=True
|
| 762 |
+
)
|
| 763 |
+
def test_drop_by_str_label_errors_ignore(self, index):
|
| 764 |
+
n = len(index)
|
| 765 |
+
drop = index[list(range(5, 10))]
|
| 766 |
+
mixed = drop.tolist() + ["foo"]
|
| 767 |
+
dropped = index.drop(mixed, errors="ignore")
|
| 768 |
+
|
| 769 |
+
expected = index[list(range(5)) + list(range(10, n))]
|
| 770 |
+
tm.assert_index_equal(dropped, expected)
|
| 771 |
+
|
| 772 |
+
dropped = index.drop(["foo", "bar"], errors="ignore")
|
| 773 |
+
expected = index[list(range(n))]
|
| 774 |
+
tm.assert_index_equal(dropped, expected)
|
| 775 |
+
|
| 776 |
+
def test_drop_by_numeric_label_loc(self):
|
| 777 |
+
# TODO: Parametrize numeric and str tests after self.strIndex fixture
|
| 778 |
+
index = Index([1, 2, 3])
|
| 779 |
+
dropped = index.drop(1)
|
| 780 |
+
expected = Index([2, 3])
|
| 781 |
+
|
| 782 |
+
tm.assert_index_equal(dropped, expected)
|
| 783 |
+
|
| 784 |
+
def test_drop_by_numeric_label_raises_missing_keys(self):
|
| 785 |
+
index = Index([1, 2, 3])
|
| 786 |
+
with pytest.raises(KeyError, match=""):
|
| 787 |
+
index.drop([3, 4])
|
| 788 |
+
|
| 789 |
+
@pytest.mark.parametrize(
|
| 790 |
+
"key,expected", [(4, Index([1, 2, 3])), ([3, 4, 5], Index([1, 2]))]
|
| 791 |
+
)
|
| 792 |
+
def test_drop_by_numeric_label_errors_ignore(self, key, expected):
|
| 793 |
+
index = Index([1, 2, 3])
|
| 794 |
+
dropped = index.drop(key, errors="ignore")
|
| 795 |
+
|
| 796 |
+
tm.assert_index_equal(dropped, expected)
|
| 797 |
+
|
| 798 |
+
@pytest.mark.parametrize(
|
| 799 |
+
"values",
|
| 800 |
+
[["a", "b", ("c", "d")], ["a", ("c", "d"), "b"], [("c", "d"), "a", "b"]],
|
| 801 |
+
)
|
| 802 |
+
@pytest.mark.parametrize("to_drop", [[("c", "d"), "a"], ["a", ("c", "d")]])
|
| 803 |
+
def test_drop_tuple(self, values, to_drop):
|
| 804 |
+
# GH 18304
|
| 805 |
+
index = Index(values)
|
| 806 |
+
expected = Index(["b"], dtype=object)
|
| 807 |
+
|
| 808 |
+
result = index.drop(to_drop)
|
| 809 |
+
tm.assert_index_equal(result, expected)
|
| 810 |
+
|
| 811 |
+
removed = index.drop(to_drop[0])
|
| 812 |
+
for drop_me in to_drop[1], [to_drop[1]]:
|
| 813 |
+
result = removed.drop(drop_me)
|
| 814 |
+
tm.assert_index_equal(result, expected)
|
| 815 |
+
|
| 816 |
+
removed = index.drop(to_drop[1])
|
| 817 |
+
msg = rf"\"\[{re.escape(to_drop[1].__repr__())}\] not found in axis\""
|
| 818 |
+
for drop_me in to_drop[1], [to_drop[1]]:
|
| 819 |
+
with pytest.raises(KeyError, match=msg):
|
| 820 |
+
removed.drop(drop_me)
|
| 821 |
+
|
| 822 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
| 823 |
+
def test_drop_with_duplicates_in_index(self, index):
|
| 824 |
+
# GH38051
|
| 825 |
+
if len(index) == 0 or isinstance(index, MultiIndex):
|
| 826 |
+
pytest.skip("Test doesn't make sense for empty MultiIndex")
|
| 827 |
+
if isinstance(index, IntervalIndex) and not IS64:
|
| 828 |
+
pytest.skip("Cannot test IntervalIndex with int64 dtype on 32 bit platform")
|
| 829 |
+
index = index.unique().repeat(2)
|
| 830 |
+
expected = index[2:]
|
| 831 |
+
result = index.drop(index[0])
|
| 832 |
+
tm.assert_index_equal(result, expected)
|
| 833 |
+
|
| 834 |
+
@pytest.mark.parametrize(
|
| 835 |
+
"attr",
|
| 836 |
+
[
|
| 837 |
+
"is_monotonic_increasing",
|
| 838 |
+
"is_monotonic_decreasing",
|
| 839 |
+
"_is_strictly_monotonic_increasing",
|
| 840 |
+
"_is_strictly_monotonic_decreasing",
|
| 841 |
+
],
|
| 842 |
+
)
|
| 843 |
+
def test_is_monotonic_incomparable(self, attr):
|
| 844 |
+
index = Index([5, datetime.now(), 7])
|
| 845 |
+
assert not getattr(index, attr)
|
| 846 |
+
|
| 847 |
+
@pytest.mark.parametrize("values", [["foo", "bar", "quux"], {"foo", "bar", "quux"}])
|
| 848 |
+
@pytest.mark.parametrize(
|
| 849 |
+
"index,expected",
|
| 850 |
+
[
|
| 851 |
+
(Index(["qux", "baz", "foo", "bar"]), np.array([False, False, True, True])),
|
| 852 |
+
(Index([]), np.array([], dtype=bool)), # empty
|
| 853 |
+
],
|
| 854 |
+
)
|
| 855 |
+
def test_isin(self, values, index, expected):
|
| 856 |
+
result = index.isin(values)
|
| 857 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 858 |
+
|
| 859 |
+
def test_isin_nan_common_object(
|
| 860 |
+
self, nulls_fixture, nulls_fixture2, using_infer_string
|
| 861 |
+
):
|
| 862 |
+
# Test cartesian product of null fixtures and ensure that we don't
|
| 863 |
+
# mangle the various types (save a corner case with PyPy)
|
| 864 |
+
idx = Index(["a", nulls_fixture])
|
| 865 |
+
|
| 866 |
+
# all nans are the same
|
| 867 |
+
if (
|
| 868 |
+
isinstance(nulls_fixture, float)
|
| 869 |
+
and isinstance(nulls_fixture2, float)
|
| 870 |
+
and math.isnan(nulls_fixture)
|
| 871 |
+
and math.isnan(nulls_fixture2)
|
| 872 |
+
):
|
| 873 |
+
tm.assert_numpy_array_equal(
|
| 874 |
+
idx.isin([nulls_fixture2]),
|
| 875 |
+
np.array([False, True]),
|
| 876 |
+
)
|
| 877 |
+
|
| 878 |
+
elif nulls_fixture is nulls_fixture2: # should preserve NA type
|
| 879 |
+
tm.assert_numpy_array_equal(
|
| 880 |
+
idx.isin([nulls_fixture2]),
|
| 881 |
+
np.array([False, True]),
|
| 882 |
+
)
|
| 883 |
+
|
| 884 |
+
elif using_infer_string and idx.dtype == "string":
|
| 885 |
+
tm.assert_numpy_array_equal(
|
| 886 |
+
idx.isin([nulls_fixture2]),
|
| 887 |
+
np.array([False, True]),
|
| 888 |
+
)
|
| 889 |
+
|
| 890 |
+
else:
|
| 891 |
+
tm.assert_numpy_array_equal(
|
| 892 |
+
idx.isin([nulls_fixture2]),
|
| 893 |
+
np.array([False, False]),
|
| 894 |
+
)
|
| 895 |
+
|
| 896 |
+
def test_isin_nan_common_float64(self, nulls_fixture, float_numpy_dtype):
|
| 897 |
+
dtype = float_numpy_dtype
|
| 898 |
+
|
| 899 |
+
if nulls_fixture is pd.NaT or nulls_fixture is pd.NA:
|
| 900 |
+
# Check 1) that we cannot construct a float64 Index with this value
|
| 901 |
+
# and 2) that with an NaN we do not have .isin(nulls_fixture)
|
| 902 |
+
msg = (
|
| 903 |
+
r"float\(\) argument must be a string or a (real )?number, "
|
| 904 |
+
f"not {repr(type(nulls_fixture).__name__)}"
|
| 905 |
+
)
|
| 906 |
+
with pytest.raises(TypeError, match=msg):
|
| 907 |
+
Index([1.0, nulls_fixture], dtype=dtype)
|
| 908 |
+
|
| 909 |
+
idx = Index([1.0, np.nan], dtype=dtype)
|
| 910 |
+
assert not idx.isin([nulls_fixture]).any()
|
| 911 |
+
return
|
| 912 |
+
|
| 913 |
+
idx = Index([1.0, nulls_fixture], dtype=dtype)
|
| 914 |
+
res = idx.isin([np.nan])
|
| 915 |
+
tm.assert_numpy_array_equal(res, np.array([False, True]))
|
| 916 |
+
|
| 917 |
+
# we cannot compare NaT with NaN
|
| 918 |
+
res = idx.isin([pd.NaT])
|
| 919 |
+
tm.assert_numpy_array_equal(res, np.array([False, False]))
|
| 920 |
+
|
| 921 |
+
@pytest.mark.parametrize("level", [0, -1])
|
| 922 |
+
@pytest.mark.parametrize(
|
| 923 |
+
"index",
|
| 924 |
+
[
|
| 925 |
+
Index(["qux", "baz", "foo", "bar"]),
|
| 926 |
+
Index([1.0, 2.0, 3.0, 4.0], dtype=np.float64),
|
| 927 |
+
],
|
| 928 |
+
)
|
| 929 |
+
def test_isin_level_kwarg(self, level, index):
|
| 930 |
+
values = index.tolist()[-2:] + ["nonexisting"]
|
| 931 |
+
|
| 932 |
+
expected = np.array([False, False, True, True])
|
| 933 |
+
tm.assert_numpy_array_equal(expected, index.isin(values, level=level))
|
| 934 |
+
|
| 935 |
+
index.name = "foobar"
|
| 936 |
+
tm.assert_numpy_array_equal(expected, index.isin(values, level="foobar"))
|
| 937 |
+
|
| 938 |
+
def test_isin_level_kwarg_bad_level_raises(self, index):
|
| 939 |
+
for level in [10, index.nlevels, -(index.nlevels + 1)]:
|
| 940 |
+
with pytest.raises(IndexError, match="Too many levels"):
|
| 941 |
+
index.isin([], level=level)
|
| 942 |
+
|
| 943 |
+
@pytest.mark.parametrize("label", [1.0, "foobar", "xyzzy", np.nan])
|
| 944 |
+
def test_isin_level_kwarg_bad_label_raises(self, label, index):
|
| 945 |
+
if isinstance(index, MultiIndex):
|
| 946 |
+
index = index.rename(["foo", "bar"] + index.names[2:])
|
| 947 |
+
msg = f"'Level {label} not found'"
|
| 948 |
+
else:
|
| 949 |
+
index = index.rename("foo")
|
| 950 |
+
msg = rf"Requested level \({label}\) does not match index name \(foo\)"
|
| 951 |
+
with pytest.raises(KeyError, match=msg):
|
| 952 |
+
index.isin([], level=label)
|
| 953 |
+
|
| 954 |
+
@pytest.mark.parametrize("empty", [[], Series(dtype=object), np.array([])])
|
| 955 |
+
def test_isin_empty(self, empty):
|
| 956 |
+
# see gh-16991
|
| 957 |
+
index = Index(["a", "b"])
|
| 958 |
+
expected = np.array([False, False])
|
| 959 |
+
|
| 960 |
+
result = index.isin(empty)
|
| 961 |
+
tm.assert_numpy_array_equal(expected, result)
|
| 962 |
+
|
| 963 |
+
@td.skip_if_no("pyarrow")
|
| 964 |
+
def test_isin_arrow_string_null(self):
|
| 965 |
+
# GH#55821
|
| 966 |
+
index = Index(["a", "b"], dtype="string[pyarrow_numpy]")
|
| 967 |
+
result = index.isin([None])
|
| 968 |
+
expected = np.array([False, False])
|
| 969 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 970 |
+
|
| 971 |
+
@pytest.mark.parametrize(
|
| 972 |
+
"values",
|
| 973 |
+
[
|
| 974 |
+
[1, 2, 3, 4],
|
| 975 |
+
[1.0, 2.0, 3.0, 4.0],
|
| 976 |
+
[True, True, True, True],
|
| 977 |
+
["foo", "bar", "baz", "qux"],
|
| 978 |
+
date_range("2018-01-01", freq="D", periods=4),
|
| 979 |
+
],
|
| 980 |
+
)
|
| 981 |
+
def test_boolean_cmp(self, values):
|
| 982 |
+
index = Index(values)
|
| 983 |
+
result = index == values
|
| 984 |
+
expected = np.array([True, True, True, True], dtype=bool)
|
| 985 |
+
|
| 986 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 987 |
+
|
| 988 |
+
@pytest.mark.parametrize("index", ["string"], indirect=True)
|
| 989 |
+
@pytest.mark.parametrize("name,level", [(None, 0), ("a", "a")])
|
| 990 |
+
def test_get_level_values(self, index, name, level):
|
| 991 |
+
expected = index.copy()
|
| 992 |
+
if name:
|
| 993 |
+
expected.name = name
|
| 994 |
+
|
| 995 |
+
result = expected.get_level_values(level)
|
| 996 |
+
tm.assert_index_equal(result, expected)
|
| 997 |
+
|
| 998 |
+
def test_slice_keep_name(self):
|
| 999 |
+
index = Index(["a", "b"], name="asdf")
|
| 1000 |
+
assert index.name == index[1:].name
|
| 1001 |
+
|
| 1002 |
+
@pytest.mark.parametrize(
|
| 1003 |
+
"index",
|
| 1004 |
+
[
|
| 1005 |
+
"string",
|
| 1006 |
+
"datetime",
|
| 1007 |
+
"int64",
|
| 1008 |
+
"int32",
|
| 1009 |
+
"uint64",
|
| 1010 |
+
"uint32",
|
| 1011 |
+
"float64",
|
| 1012 |
+
"float32",
|
| 1013 |
+
],
|
| 1014 |
+
indirect=True,
|
| 1015 |
+
)
|
| 1016 |
+
def test_join_self(self, index, join_type):
|
| 1017 |
+
result = index.join(index, how=join_type)
|
| 1018 |
+
expected = index
|
| 1019 |
+
if join_type == "outer":
|
| 1020 |
+
expected = expected.sort_values()
|
| 1021 |
+
tm.assert_index_equal(result, expected)
|
| 1022 |
+
|
| 1023 |
+
@pytest.mark.parametrize("method", ["strip", "rstrip", "lstrip"])
|
| 1024 |
+
def test_str_attribute(self, method):
|
| 1025 |
+
# GH9068
|
| 1026 |
+
index = Index([" jack", "jill ", " jesse ", "frank"])
|
| 1027 |
+
expected = Index([getattr(str, method)(x) for x in index.values])
|
| 1028 |
+
|
| 1029 |
+
result = getattr(index.str, method)()
|
| 1030 |
+
tm.assert_index_equal(result, expected)
|
| 1031 |
+
|
| 1032 |
+
@pytest.mark.parametrize(
|
| 1033 |
+
"index",
|
| 1034 |
+
[
|
| 1035 |
+
Index(range(5)),
|
| 1036 |
+
date_range("2020-01-01", periods=10),
|
| 1037 |
+
MultiIndex.from_tuples([("foo", "1"), ("bar", "3")]),
|
| 1038 |
+
period_range(start="2000", end="2010", freq="Y"),
|
| 1039 |
+
],
|
| 1040 |
+
)
|
| 1041 |
+
def test_str_attribute_raises(self, index):
|
| 1042 |
+
with pytest.raises(AttributeError, match="only use .str accessor"):
|
| 1043 |
+
index.str.repeat(2)
|
| 1044 |
+
|
| 1045 |
+
@pytest.mark.parametrize(
|
| 1046 |
+
"expand,expected",
|
| 1047 |
+
[
|
| 1048 |
+
(None, Index([["a", "b", "c"], ["d", "e"], ["f"]])),
|
| 1049 |
+
(False, Index([["a", "b", "c"], ["d", "e"], ["f"]])),
|
| 1050 |
+
(
|
| 1051 |
+
True,
|
| 1052 |
+
MultiIndex.from_tuples(
|
| 1053 |
+
[("a", "b", "c"), ("d", "e", np.nan), ("f", np.nan, np.nan)]
|
| 1054 |
+
),
|
| 1055 |
+
),
|
| 1056 |
+
],
|
| 1057 |
+
)
|
| 1058 |
+
def test_str_split(self, expand, expected):
|
| 1059 |
+
index = Index(["a b c", "d e", "f"])
|
| 1060 |
+
if expand is not None:
|
| 1061 |
+
result = index.str.split(expand=expand)
|
| 1062 |
+
else:
|
| 1063 |
+
result = index.str.split()
|
| 1064 |
+
|
| 1065 |
+
tm.assert_index_equal(result, expected)
|
| 1066 |
+
|
| 1067 |
+
def test_str_bool_return(self):
|
| 1068 |
+
# test boolean case, should return np.array instead of boolean Index
|
| 1069 |
+
index = Index(["a1", "a2", "b1", "b2"])
|
| 1070 |
+
result = index.str.startswith("a")
|
| 1071 |
+
expected = np.array([True, True, False, False])
|
| 1072 |
+
|
| 1073 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 1074 |
+
assert isinstance(result, np.ndarray)
|
| 1075 |
+
|
| 1076 |
+
def test_str_bool_series_indexing(self):
|
| 1077 |
+
index = Index(["a1", "a2", "b1", "b2"])
|
| 1078 |
+
s = Series(range(4), index=index)
|
| 1079 |
+
|
| 1080 |
+
result = s[s.index.str.startswith("a")]
|
| 1081 |
+
expected = Series(range(2), index=["a1", "a2"])
|
| 1082 |
+
tm.assert_series_equal(result, expected)
|
| 1083 |
+
|
| 1084 |
+
@pytest.mark.parametrize(
|
| 1085 |
+
"index,expected", [(Index(list("abcd")), True), (Index(range(4)), False)]
|
| 1086 |
+
)
|
| 1087 |
+
def test_tab_completion(self, index, expected):
|
| 1088 |
+
# GH 9910
|
| 1089 |
+
result = "str" in dir(index)
|
| 1090 |
+
assert result == expected
|
| 1091 |
+
|
| 1092 |
+
def test_indexing_doesnt_change_class(self):
|
| 1093 |
+
index = Index([1, 2, 3, "a", "b", "c"])
|
| 1094 |
+
|
| 1095 |
+
assert index[1:3].identical(Index([2, 3], dtype=np.object_))
|
| 1096 |
+
assert index[[0, 1]].identical(Index([1, 2], dtype=np.object_))
|
| 1097 |
+
|
| 1098 |
+
def test_outer_join_sort(self):
|
| 1099 |
+
left_index = Index(np.random.default_rng(2).permutation(15))
|
| 1100 |
+
right_index = date_range("2020-01-01", periods=10)
|
| 1101 |
+
|
| 1102 |
+
with tm.assert_produces_warning(RuntimeWarning):
|
| 1103 |
+
result = left_index.join(right_index, how="outer")
|
| 1104 |
+
|
| 1105 |
+
with tm.assert_produces_warning(RuntimeWarning):
|
| 1106 |
+
expected = left_index.astype(object).union(right_index.astype(object))
|
| 1107 |
+
|
| 1108 |
+
tm.assert_index_equal(result, expected)
|
| 1109 |
+
|
| 1110 |
+
def test_take_fill_value(self):
|
| 1111 |
+
# GH 12631
|
| 1112 |
+
index = Index(list("ABC"), name="xxx")
|
| 1113 |
+
result = index.take(np.array([1, 0, -1]))
|
| 1114 |
+
expected = Index(list("BAC"), name="xxx")
|
| 1115 |
+
tm.assert_index_equal(result, expected)
|
| 1116 |
+
|
| 1117 |
+
# fill_value
|
| 1118 |
+
result = index.take(np.array([1, 0, -1]), fill_value=True)
|
| 1119 |
+
expected = Index(["B", "A", np.nan], name="xxx")
|
| 1120 |
+
tm.assert_index_equal(result, expected)
|
| 1121 |
+
|
| 1122 |
+
# allow_fill=False
|
| 1123 |
+
result = index.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True)
|
| 1124 |
+
expected = Index(["B", "A", "C"], name="xxx")
|
| 1125 |
+
tm.assert_index_equal(result, expected)
|
| 1126 |
+
|
| 1127 |
+
def test_take_fill_value_none_raises(self):
|
| 1128 |
+
index = Index(list("ABC"), name="xxx")
|
| 1129 |
+
msg = (
|
| 1130 |
+
"When allow_fill=True and fill_value is not None, "
|
| 1131 |
+
"all indices must be >= -1"
|
| 1132 |
+
)
|
| 1133 |
+
|
| 1134 |
+
with pytest.raises(ValueError, match=msg):
|
| 1135 |
+
index.take(np.array([1, 0, -2]), fill_value=True)
|
| 1136 |
+
with pytest.raises(ValueError, match=msg):
|
| 1137 |
+
index.take(np.array([1, 0, -5]), fill_value=True)
|
| 1138 |
+
|
| 1139 |
+
def test_take_bad_bounds_raises(self):
|
| 1140 |
+
index = Index(list("ABC"), name="xxx")
|
| 1141 |
+
with pytest.raises(IndexError, match="out of bounds"):
|
| 1142 |
+
index.take(np.array([1, -5]))
|
| 1143 |
+
|
| 1144 |
+
@pytest.mark.parametrize("name", [None, "foobar"])
|
| 1145 |
+
@pytest.mark.parametrize(
|
| 1146 |
+
"labels",
|
| 1147 |
+
[
|
| 1148 |
+
[],
|
| 1149 |
+
np.array([]),
|
| 1150 |
+
["A", "B", "C"],
|
| 1151 |
+
["C", "B", "A"],
|
| 1152 |
+
np.array(["A", "B", "C"]),
|
| 1153 |
+
np.array(["C", "B", "A"]),
|
| 1154 |
+
# Must preserve name even if dtype changes
|
| 1155 |
+
date_range("20130101", periods=3).values,
|
| 1156 |
+
date_range("20130101", periods=3).tolist(),
|
| 1157 |
+
],
|
| 1158 |
+
)
|
| 1159 |
+
def test_reindex_preserves_name_if_target_is_list_or_ndarray(self, name, labels):
|
| 1160 |
+
# GH6552
|
| 1161 |
+
index = Index([0, 1, 2])
|
| 1162 |
+
index.name = name
|
| 1163 |
+
assert index.reindex(labels)[0].name == name
|
| 1164 |
+
|
| 1165 |
+
@pytest.mark.parametrize("labels", [[], np.array([]), np.array([], dtype=np.int64)])
|
| 1166 |
+
def test_reindex_preserves_type_if_target_is_empty_list_or_array(self, labels):
|
| 1167 |
+
# GH7774
|
| 1168 |
+
index = Index(list("abc"))
|
| 1169 |
+
assert index.reindex(labels)[0].dtype.type == index.dtype.type
|
| 1170 |
+
|
| 1171 |
+
@pytest.mark.parametrize(
|
| 1172 |
+
"labels,dtype",
|
| 1173 |
+
[
|
| 1174 |
+
(DatetimeIndex([]), np.datetime64),
|
| 1175 |
+
],
|
| 1176 |
+
)
|
| 1177 |
+
def test_reindex_doesnt_preserve_type_if_target_is_empty_index(self, labels, dtype):
|
| 1178 |
+
# GH7774
|
| 1179 |
+
index = Index(list("abc"))
|
| 1180 |
+
assert index.reindex(labels)[0].dtype.type == dtype
|
| 1181 |
+
|
| 1182 |
+
def test_reindex_doesnt_preserve_type_if_target_is_empty_index_numeric(
|
| 1183 |
+
self, any_real_numpy_dtype
|
| 1184 |
+
):
|
| 1185 |
+
# GH7774
|
| 1186 |
+
dtype = any_real_numpy_dtype
|
| 1187 |
+
index = Index(list("abc"))
|
| 1188 |
+
labels = Index([], dtype=dtype)
|
| 1189 |
+
assert index.reindex(labels)[0].dtype == dtype
|
| 1190 |
+
|
| 1191 |
+
def test_reindex_no_type_preserve_target_empty_mi(self):
|
| 1192 |
+
index = Index(list("abc"))
|
| 1193 |
+
result = index.reindex(
|
| 1194 |
+
MultiIndex([Index([], np.int64), Index([], np.float64)], [[], []])
|
| 1195 |
+
)[0]
|
| 1196 |
+
assert result.levels[0].dtype.type == np.int64
|
| 1197 |
+
assert result.levels[1].dtype.type == np.float64
|
| 1198 |
+
|
| 1199 |
+
def test_reindex_ignoring_level(self):
|
| 1200 |
+
# GH#35132
|
| 1201 |
+
idx = Index([1, 2, 3], name="x")
|
| 1202 |
+
idx2 = Index([1, 2, 3, 4], name="x")
|
| 1203 |
+
expected = Index([1, 2, 3, 4], name="x")
|
| 1204 |
+
result, _ = idx.reindex(idx2, level="x")
|
| 1205 |
+
tm.assert_index_equal(result, expected)
|
| 1206 |
+
|
| 1207 |
+
def test_groupby(self):
|
| 1208 |
+
index = Index(range(5))
|
| 1209 |
+
result = index.groupby(np.array([1, 1, 2, 2, 2]))
|
| 1210 |
+
expected = {1: Index([0, 1]), 2: Index([2, 3, 4])}
|
| 1211 |
+
|
| 1212 |
+
tm.assert_dict_equal(result, expected)
|
| 1213 |
+
|
| 1214 |
+
@pytest.mark.parametrize(
|
| 1215 |
+
"mi,expected",
|
| 1216 |
+
[
|
| 1217 |
+
(MultiIndex.from_tuples([(1, 2), (4, 5)]), np.array([True, True])),
|
| 1218 |
+
(MultiIndex.from_tuples([(1, 2), (4, 6)]), np.array([True, False])),
|
| 1219 |
+
],
|
| 1220 |
+
)
|
| 1221 |
+
def test_equals_op_multiindex(self, mi, expected):
|
| 1222 |
+
# GH9785
|
| 1223 |
+
# test comparisons of multiindex
|
| 1224 |
+
df = DataFrame(
|
| 1225 |
+
[3, 6],
|
| 1226 |
+
columns=["c"],
|
| 1227 |
+
index=MultiIndex.from_arrays([[1, 4], [2, 5]], names=["a", "b"]),
|
| 1228 |
+
)
|
| 1229 |
+
|
| 1230 |
+
result = df.index == mi
|
| 1231 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 1232 |
+
|
| 1233 |
+
def test_equals_op_multiindex_identify(self):
|
| 1234 |
+
df = DataFrame(
|
| 1235 |
+
[3, 6],
|
| 1236 |
+
columns=["c"],
|
| 1237 |
+
index=MultiIndex.from_arrays([[1, 4], [2, 5]], names=["a", "b"]),
|
| 1238 |
+
)
|
| 1239 |
+
|
| 1240 |
+
result = df.index == df.index
|
| 1241 |
+
expected = np.array([True, True])
|
| 1242 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 1243 |
+
|
| 1244 |
+
@pytest.mark.parametrize(
|
| 1245 |
+
"index",
|
| 1246 |
+
[
|
| 1247 |
+
MultiIndex.from_tuples([(1, 2), (4, 5), (8, 9)]),
|
| 1248 |
+
Index(["foo", "bar", "baz"]),
|
| 1249 |
+
],
|
| 1250 |
+
)
|
| 1251 |
+
def test_equals_op_mismatched_multiindex_raises(self, index):
|
| 1252 |
+
df = DataFrame(
|
| 1253 |
+
[3, 6],
|
| 1254 |
+
columns=["c"],
|
| 1255 |
+
index=MultiIndex.from_arrays([[1, 4], [2, 5]], names=["a", "b"]),
|
| 1256 |
+
)
|
| 1257 |
+
|
| 1258 |
+
with pytest.raises(ValueError, match="Lengths must match"):
|
| 1259 |
+
df.index == index
|
| 1260 |
+
|
| 1261 |
+
def test_equals_op_index_vs_mi_same_length(self, using_infer_string):
|
| 1262 |
+
mi = MultiIndex.from_tuples([(1, 2), (4, 5), (8, 9)])
|
| 1263 |
+
index = Index(["foo", "bar", "baz"])
|
| 1264 |
+
|
| 1265 |
+
result = mi == index
|
| 1266 |
+
expected = np.array([False, False, False])
|
| 1267 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 1268 |
+
|
| 1269 |
+
@pytest.mark.parametrize(
|
| 1270 |
+
"dt_conv, arg",
|
| 1271 |
+
[
|
| 1272 |
+
(pd.to_datetime, ["2000-01-01", "2000-01-02"]),
|
| 1273 |
+
(pd.to_timedelta, ["01:02:03", "01:02:04"]),
|
| 1274 |
+
],
|
| 1275 |
+
)
|
| 1276 |
+
def test_dt_conversion_preserves_name(self, dt_conv, arg):
|
| 1277 |
+
# GH 10875
|
| 1278 |
+
index = Index(arg, name="label")
|
| 1279 |
+
assert index.name == dt_conv(index).name
|
| 1280 |
+
|
| 1281 |
+
def test_cached_properties_not_settable(self):
|
| 1282 |
+
index = Index([1, 2, 3])
|
| 1283 |
+
with pytest.raises(AttributeError, match="Can't set attribute"):
|
| 1284 |
+
index.is_unique = False
|
| 1285 |
+
|
| 1286 |
+
def test_tab_complete_warning(self, ip):
|
| 1287 |
+
# https://github.com/pandas-dev/pandas/issues/16409
|
| 1288 |
+
pytest.importorskip("IPython", minversion="6.0.0")
|
| 1289 |
+
from IPython.core.completer import provisionalcompleter
|
| 1290 |
+
|
| 1291 |
+
code = "import pandas as pd; idx = pd.Index([1, 2])"
|
| 1292 |
+
ip.run_cell(code)
|
| 1293 |
+
|
| 1294 |
+
# GH 31324 newer jedi version raises Deprecation warning;
|
| 1295 |
+
# appears resolved 2021-02-02
|
| 1296 |
+
with tm.assert_produces_warning(None, raise_on_extra_warnings=False):
|
| 1297 |
+
with provisionalcompleter("ignore"):
|
| 1298 |
+
list(ip.Completer.completions("idx.", 4))
|
| 1299 |
+
|
| 1300 |
+
def test_contains_method_removed(self, index):
|
| 1301 |
+
# GH#30103 method removed for all types except IntervalIndex
|
| 1302 |
+
if isinstance(index, IntervalIndex):
|
| 1303 |
+
index.contains(1)
|
| 1304 |
+
else:
|
| 1305 |
+
msg = f"'{type(index).__name__}' object has no attribute 'contains'"
|
| 1306 |
+
with pytest.raises(AttributeError, match=msg):
|
| 1307 |
+
index.contains(1)
|
| 1308 |
+
|
| 1309 |
+
def test_sortlevel(self):
|
| 1310 |
+
index = Index([5, 4, 3, 2, 1])
|
| 1311 |
+
with pytest.raises(Exception, match="ascending must be a single bool value or"):
|
| 1312 |
+
index.sortlevel(ascending="True")
|
| 1313 |
+
|
| 1314 |
+
with pytest.raises(
|
| 1315 |
+
Exception, match="ascending must be a list of bool values of length 1"
|
| 1316 |
+
):
|
| 1317 |
+
index.sortlevel(ascending=[True, True])
|
| 1318 |
+
|
| 1319 |
+
with pytest.raises(Exception, match="ascending must be a bool value"):
|
| 1320 |
+
index.sortlevel(ascending=["True"])
|
| 1321 |
+
|
| 1322 |
+
expected = Index([1, 2, 3, 4, 5])
|
| 1323 |
+
result = index.sortlevel(ascending=[True])
|
| 1324 |
+
tm.assert_index_equal(result[0], expected)
|
| 1325 |
+
|
| 1326 |
+
expected = Index([1, 2, 3, 4, 5])
|
| 1327 |
+
result = index.sortlevel(ascending=True)
|
| 1328 |
+
tm.assert_index_equal(result[0], expected)
|
| 1329 |
+
|
| 1330 |
+
expected = Index([5, 4, 3, 2, 1])
|
| 1331 |
+
result = index.sortlevel(ascending=False)
|
| 1332 |
+
tm.assert_index_equal(result[0], expected)
|
| 1333 |
+
|
| 1334 |
+
def test_sortlevel_na_position(self):
|
| 1335 |
+
# GH#51612
|
| 1336 |
+
idx = Index([1, np.nan])
|
| 1337 |
+
result = idx.sortlevel(na_position="first")[0]
|
| 1338 |
+
expected = Index([np.nan, 1])
|
| 1339 |
+
tm.assert_index_equal(result, expected)
|
| 1340 |
+
|
| 1341 |
+
@pytest.mark.parametrize(
|
| 1342 |
+
"periods, expected_results",
|
| 1343 |
+
[
|
| 1344 |
+
(1, [np.nan, 10, 10, 10, 10]),
|
| 1345 |
+
(2, [np.nan, np.nan, 20, 20, 20]),
|
| 1346 |
+
(3, [np.nan, np.nan, np.nan, 30, 30]),
|
| 1347 |
+
],
|
| 1348 |
+
)
|
| 1349 |
+
def test_index_diff(self, periods, expected_results):
|
| 1350 |
+
# GH#19708
|
| 1351 |
+
idx = Index([10, 20, 30, 40, 50])
|
| 1352 |
+
result = idx.diff(periods)
|
| 1353 |
+
expected = Index(expected_results)
|
| 1354 |
+
|
| 1355 |
+
tm.assert_index_equal(result, expected)
|
| 1356 |
+
|
| 1357 |
+
@pytest.mark.parametrize(
|
| 1358 |
+
"decimals, expected_results",
|
| 1359 |
+
[
|
| 1360 |
+
(0, [1.0, 2.0, 3.0]),
|
| 1361 |
+
(1, [1.2, 2.3, 3.5]),
|
| 1362 |
+
(2, [1.23, 2.35, 3.46]),
|
| 1363 |
+
],
|
| 1364 |
+
)
|
| 1365 |
+
def test_index_round(self, decimals, expected_results):
|
| 1366 |
+
# GH#19708
|
| 1367 |
+
idx = Index([1.234, 2.345, 3.456])
|
| 1368 |
+
result = idx.round(decimals)
|
| 1369 |
+
expected = Index(expected_results)
|
| 1370 |
+
|
| 1371 |
+
tm.assert_index_equal(result, expected)
|
| 1372 |
+
|
| 1373 |
+
|
| 1374 |
+
class TestMixedIntIndex:
|
| 1375 |
+
# Mostly the tests from common.py for which the results differ
|
| 1376 |
+
# in py2 and py3 because ints and strings are uncomparable in py3
|
| 1377 |
+
# (GH 13514)
|
| 1378 |
+
@pytest.fixture
|
| 1379 |
+
def simple_index(self) -> Index:
|
| 1380 |
+
return Index([0, "a", 1, "b", 2, "c"])
|
| 1381 |
+
|
| 1382 |
+
def test_argsort(self, simple_index):
|
| 1383 |
+
index = simple_index
|
| 1384 |
+
with pytest.raises(TypeError, match="'>|<' not supported"):
|
| 1385 |
+
index.argsort()
|
| 1386 |
+
|
| 1387 |
+
def test_numpy_argsort(self, simple_index):
|
| 1388 |
+
index = simple_index
|
| 1389 |
+
with pytest.raises(TypeError, match="'>|<' not supported"):
|
| 1390 |
+
np.argsort(index)
|
| 1391 |
+
|
| 1392 |
+
def test_copy_name(self, simple_index):
|
| 1393 |
+
# Check that "name" argument passed at initialization is honoured
|
| 1394 |
+
# GH12309
|
| 1395 |
+
index = simple_index
|
| 1396 |
+
|
| 1397 |
+
first = type(index)(index, copy=True, name="mario")
|
| 1398 |
+
second = type(first)(first, copy=False)
|
| 1399 |
+
|
| 1400 |
+
# Even though "copy=False", we want a new object.
|
| 1401 |
+
assert first is not second
|
| 1402 |
+
tm.assert_index_equal(first, second)
|
| 1403 |
+
|
| 1404 |
+
assert first.name == "mario"
|
| 1405 |
+
assert second.name == "mario"
|
| 1406 |
+
|
| 1407 |
+
s1 = Series(2, index=first)
|
| 1408 |
+
s2 = Series(3, index=second[:-1])
|
| 1409 |
+
|
| 1410 |
+
s3 = s1 * s2
|
| 1411 |
+
|
| 1412 |
+
assert s3.index.name == "mario"
|
| 1413 |
+
|
| 1414 |
+
def test_copy_name2(self):
|
| 1415 |
+
# Check that adding a "name" parameter to the copy is honored
|
| 1416 |
+
# GH14302
|
| 1417 |
+
index = Index([1, 2], name="MyName")
|
| 1418 |
+
index1 = index.copy()
|
| 1419 |
+
|
| 1420 |
+
tm.assert_index_equal(index, index1)
|
| 1421 |
+
|
| 1422 |
+
index2 = index.copy(name="NewName")
|
| 1423 |
+
tm.assert_index_equal(index, index2, check_names=False)
|
| 1424 |
+
assert index.name == "MyName"
|
| 1425 |
+
assert index2.name == "NewName"
|
| 1426 |
+
|
| 1427 |
+
def test_unique_na(self):
|
| 1428 |
+
idx = Index([2, np.nan, 2, 1], name="my_index")
|
| 1429 |
+
expected = Index([2, np.nan, 1], name="my_index")
|
| 1430 |
+
result = idx.unique()
|
| 1431 |
+
tm.assert_index_equal(result, expected)
|
| 1432 |
+
|
| 1433 |
+
def test_logical_compat(self, simple_index):
|
| 1434 |
+
index = simple_index
|
| 1435 |
+
assert index.all() == index.values.all()
|
| 1436 |
+
assert index.any() == index.values.any()
|
| 1437 |
+
|
| 1438 |
+
@pytest.mark.parametrize("how", ["any", "all"])
|
| 1439 |
+
@pytest.mark.parametrize("dtype", [None, object, "category"])
|
| 1440 |
+
@pytest.mark.parametrize(
|
| 1441 |
+
"vals,expected",
|
| 1442 |
+
[
|
| 1443 |
+
([1, 2, 3], [1, 2, 3]),
|
| 1444 |
+
([1.0, 2.0, 3.0], [1.0, 2.0, 3.0]),
|
| 1445 |
+
([1.0, 2.0, np.nan, 3.0], [1.0, 2.0, 3.0]),
|
| 1446 |
+
(["A", "B", "C"], ["A", "B", "C"]),
|
| 1447 |
+
(["A", np.nan, "B", "C"], ["A", "B", "C"]),
|
| 1448 |
+
],
|
| 1449 |
+
)
|
| 1450 |
+
def test_dropna(self, how, dtype, vals, expected):
|
| 1451 |
+
# GH 6194
|
| 1452 |
+
index = Index(vals, dtype=dtype)
|
| 1453 |
+
result = index.dropna(how=how)
|
| 1454 |
+
expected = Index(expected, dtype=dtype)
|
| 1455 |
+
tm.assert_index_equal(result, expected)
|
| 1456 |
+
|
| 1457 |
+
@pytest.mark.parametrize("how", ["any", "all"])
|
| 1458 |
+
@pytest.mark.parametrize(
|
| 1459 |
+
"index,expected",
|
| 1460 |
+
[
|
| 1461 |
+
(
|
| 1462 |
+
DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03"]),
|
| 1463 |
+
DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03"]),
|
| 1464 |
+
),
|
| 1465 |
+
(
|
| 1466 |
+
DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03", pd.NaT]),
|
| 1467 |
+
DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03"]),
|
| 1468 |
+
),
|
| 1469 |
+
(
|
| 1470 |
+
TimedeltaIndex(["1 days", "2 days", "3 days"]),
|
| 1471 |
+
TimedeltaIndex(["1 days", "2 days", "3 days"]),
|
| 1472 |
+
),
|
| 1473 |
+
(
|
| 1474 |
+
TimedeltaIndex([pd.NaT, "1 days", "2 days", "3 days", pd.NaT]),
|
| 1475 |
+
TimedeltaIndex(["1 days", "2 days", "3 days"]),
|
| 1476 |
+
),
|
| 1477 |
+
(
|
| 1478 |
+
PeriodIndex(["2012-02", "2012-04", "2012-05"], freq="M"),
|
| 1479 |
+
PeriodIndex(["2012-02", "2012-04", "2012-05"], freq="M"),
|
| 1480 |
+
),
|
| 1481 |
+
(
|
| 1482 |
+
PeriodIndex(["2012-02", "2012-04", "NaT", "2012-05"], freq="M"),
|
| 1483 |
+
PeriodIndex(["2012-02", "2012-04", "2012-05"], freq="M"),
|
| 1484 |
+
),
|
| 1485 |
+
],
|
| 1486 |
+
)
|
| 1487 |
+
def test_dropna_dt_like(self, how, index, expected):
|
| 1488 |
+
result = index.dropna(how=how)
|
| 1489 |
+
tm.assert_index_equal(result, expected)
|
| 1490 |
+
|
| 1491 |
+
def test_dropna_invalid_how_raises(self):
|
| 1492 |
+
msg = "invalid how option: xxx"
|
| 1493 |
+
with pytest.raises(ValueError, match=msg):
|
| 1494 |
+
Index([1, 2, 3]).dropna(how="xxx")
|
| 1495 |
+
|
| 1496 |
+
@pytest.mark.parametrize(
|
| 1497 |
+
"index",
|
| 1498 |
+
[
|
| 1499 |
+
Index([np.nan]),
|
| 1500 |
+
Index([np.nan, 1]),
|
| 1501 |
+
Index([1, 2, np.nan]),
|
| 1502 |
+
Index(["a", "b", np.nan]),
|
| 1503 |
+
pd.to_datetime(["NaT"]),
|
| 1504 |
+
pd.to_datetime(["NaT", "2000-01-01"]),
|
| 1505 |
+
pd.to_datetime(["2000-01-01", "NaT", "2000-01-02"]),
|
| 1506 |
+
pd.to_timedelta(["1 day", "NaT"]),
|
| 1507 |
+
],
|
| 1508 |
+
)
|
| 1509 |
+
def test_is_monotonic_na(self, index):
|
| 1510 |
+
assert index.is_monotonic_increasing is False
|
| 1511 |
+
assert index.is_monotonic_decreasing is False
|
| 1512 |
+
assert index._is_strictly_monotonic_increasing is False
|
| 1513 |
+
assert index._is_strictly_monotonic_decreasing is False
|
| 1514 |
+
|
| 1515 |
+
@pytest.mark.parametrize("dtype", ["f8", "m8[ns]", "M8[us]"])
|
| 1516 |
+
@pytest.mark.parametrize("unique_first", [True, False])
|
| 1517 |
+
def test_is_monotonic_unique_na(self, dtype, unique_first):
|
| 1518 |
+
# GH 55755
|
| 1519 |
+
index = Index([None, 1, 1], dtype=dtype)
|
| 1520 |
+
if unique_first:
|
| 1521 |
+
assert index.is_unique is False
|
| 1522 |
+
assert index.is_monotonic_increasing is False
|
| 1523 |
+
assert index.is_monotonic_decreasing is False
|
| 1524 |
+
else:
|
| 1525 |
+
assert index.is_monotonic_increasing is False
|
| 1526 |
+
assert index.is_monotonic_decreasing is False
|
| 1527 |
+
assert index.is_unique is False
|
| 1528 |
+
|
| 1529 |
+
def test_int_name_format(self, frame_or_series):
|
| 1530 |
+
index = Index(["a", "b", "c"], name=0)
|
| 1531 |
+
result = frame_or_series(list(range(3)), index=index)
|
| 1532 |
+
assert "0" in repr(result)
|
| 1533 |
+
|
| 1534 |
+
def test_str_to_bytes_raises(self):
|
| 1535 |
+
# GH 26447
|
| 1536 |
+
index = Index([str(x) for x in range(10)])
|
| 1537 |
+
msg = "^'str' object cannot be interpreted as an integer$"
|
| 1538 |
+
with pytest.raises(TypeError, match=msg):
|
| 1539 |
+
bytes(index)
|
| 1540 |
+
|
| 1541 |
+
@pytest.mark.filterwarnings("ignore:elementwise comparison failed:FutureWarning")
|
| 1542 |
+
def test_index_with_tuple_bool(self):
|
| 1543 |
+
# GH34123
|
| 1544 |
+
# TODO: also this op right now produces FutureWarning from numpy
|
| 1545 |
+
# https://github.com/numpy/numpy/issues/11521
|
| 1546 |
+
idx = Index([("a", "b"), ("b", "c"), ("c", "a")])
|
| 1547 |
+
result = idx == ("c", "a")
|
| 1548 |
+
expected = np.array([False, False, True])
|
| 1549 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 1550 |
+
|
| 1551 |
+
|
| 1552 |
+
class TestIndexUtils:
|
| 1553 |
+
@pytest.mark.parametrize(
|
| 1554 |
+
"data, names, expected",
|
| 1555 |
+
[
|
| 1556 |
+
([[1, 2, 3]], None, Index([1, 2, 3])),
|
| 1557 |
+
([[1, 2, 3]], ["name"], Index([1, 2, 3], name="name")),
|
| 1558 |
+
(
|
| 1559 |
+
[["a", "a"], ["c", "d"]],
|
| 1560 |
+
None,
|
| 1561 |
+
MultiIndex([["a"], ["c", "d"]], [[0, 0], [0, 1]]),
|
| 1562 |
+
),
|
| 1563 |
+
(
|
| 1564 |
+
[["a", "a"], ["c", "d"]],
|
| 1565 |
+
["L1", "L2"],
|
| 1566 |
+
MultiIndex([["a"], ["c", "d"]], [[0, 0], [0, 1]], names=["L1", "L2"]),
|
| 1567 |
+
),
|
| 1568 |
+
],
|
| 1569 |
+
)
|
| 1570 |
+
def test_ensure_index_from_sequences(self, data, names, expected):
|
| 1571 |
+
result = ensure_index_from_sequences(data, names)
|
| 1572 |
+
tm.assert_index_equal(result, expected)
|
| 1573 |
+
|
| 1574 |
+
def test_ensure_index_mixed_closed_intervals(self):
|
| 1575 |
+
# GH27172
|
| 1576 |
+
intervals = [
|
| 1577 |
+
pd.Interval(0, 1, closed="left"),
|
| 1578 |
+
pd.Interval(1, 2, closed="right"),
|
| 1579 |
+
pd.Interval(2, 3, closed="neither"),
|
| 1580 |
+
pd.Interval(3, 4, closed="both"),
|
| 1581 |
+
]
|
| 1582 |
+
result = ensure_index(intervals)
|
| 1583 |
+
expected = Index(intervals, dtype=object)
|
| 1584 |
+
tm.assert_index_equal(result, expected)
|
| 1585 |
+
|
| 1586 |
+
def test_ensure_index_uint64(self):
|
| 1587 |
+
# with both 0 and a large-uint64, np.array will infer to float64
|
| 1588 |
+
# https://github.com/numpy/numpy/issues/19146
|
| 1589 |
+
# but a more accurate choice would be uint64
|
| 1590 |
+
values = [0, np.iinfo(np.uint64).max]
|
| 1591 |
+
|
| 1592 |
+
result = ensure_index(values)
|
| 1593 |
+
assert list(result) == values
|
| 1594 |
+
|
| 1595 |
+
expected = Index(values, dtype="uint64")
|
| 1596 |
+
tm.assert_index_equal(result, expected)
|
| 1597 |
+
|
| 1598 |
+
def test_get_combined_index(self):
|
| 1599 |
+
result = _get_combined_index([])
|
| 1600 |
+
expected = Index([])
|
| 1601 |
+
tm.assert_index_equal(result, expected)
|
| 1602 |
+
|
| 1603 |
+
|
| 1604 |
+
@pytest.mark.parametrize(
|
| 1605 |
+
"opname",
|
| 1606 |
+
[
|
| 1607 |
+
"eq",
|
| 1608 |
+
"ne",
|
| 1609 |
+
"le",
|
| 1610 |
+
"lt",
|
| 1611 |
+
"ge",
|
| 1612 |
+
"gt",
|
| 1613 |
+
"add",
|
| 1614 |
+
"radd",
|
| 1615 |
+
"sub",
|
| 1616 |
+
"rsub",
|
| 1617 |
+
"mul",
|
| 1618 |
+
"rmul",
|
| 1619 |
+
"truediv",
|
| 1620 |
+
"rtruediv",
|
| 1621 |
+
"floordiv",
|
| 1622 |
+
"rfloordiv",
|
| 1623 |
+
"pow",
|
| 1624 |
+
"rpow",
|
| 1625 |
+
"mod",
|
| 1626 |
+
"divmod",
|
| 1627 |
+
],
|
| 1628 |
+
)
|
| 1629 |
+
def test_generated_op_names(opname, index):
|
| 1630 |
+
opname = f"__{opname}__"
|
| 1631 |
+
method = getattr(index, opname)
|
| 1632 |
+
assert method.__name__ == opname
|
| 1633 |
+
|
| 1634 |
+
|
| 1635 |
+
@pytest.mark.parametrize(
|
| 1636 |
+
"klass",
|
| 1637 |
+
[
|
| 1638 |
+
partial(CategoricalIndex, data=[1]),
|
| 1639 |
+
partial(DatetimeIndex, data=["2020-01-01"]),
|
| 1640 |
+
partial(PeriodIndex, data=["2020-01-01"]),
|
| 1641 |
+
partial(TimedeltaIndex, data=["1 day"]),
|
| 1642 |
+
partial(RangeIndex, data=range(1)),
|
| 1643 |
+
partial(IntervalIndex, data=[pd.Interval(0, 1)]),
|
| 1644 |
+
partial(Index, data=["a"], dtype=object),
|
| 1645 |
+
partial(MultiIndex, levels=[1], codes=[0]),
|
| 1646 |
+
],
|
| 1647 |
+
)
|
| 1648 |
+
def test_index_subclass_constructor_wrong_kwargs(klass):
|
| 1649 |
+
# GH #19348
|
| 1650 |
+
with pytest.raises(TypeError, match="unexpected keyword argument"):
|
| 1651 |
+
klass(foo="bar")
|
| 1652 |
+
|
| 1653 |
+
|
| 1654 |
+
def test_deprecated_fastpath():
|
| 1655 |
+
msg = "[Uu]nexpected keyword argument"
|
| 1656 |
+
with pytest.raises(TypeError, match=msg):
|
| 1657 |
+
Index(np.array(["a", "b"], dtype=object), name="test", fastpath=True)
|
| 1658 |
+
|
| 1659 |
+
with pytest.raises(TypeError, match=msg):
|
| 1660 |
+
Index(np.array([1, 2, 3], dtype="int64"), name="test", fastpath=True)
|
| 1661 |
+
|
| 1662 |
+
with pytest.raises(TypeError, match=msg):
|
| 1663 |
+
RangeIndex(0, 5, 2, name="test", fastpath=True)
|
| 1664 |
+
|
| 1665 |
+
with pytest.raises(TypeError, match=msg):
|
| 1666 |
+
CategoricalIndex(["a", "b", "c"], name="test", fastpath=True)
|
| 1667 |
+
|
| 1668 |
+
|
| 1669 |
+
def test_shape_of_invalid_index():
|
| 1670 |
+
# Pre-2.0, it was possible to create "invalid" index objects backed by
|
| 1671 |
+
# a multi-dimensional array (see https://github.com/pandas-dev/pandas/issues/27125
|
| 1672 |
+
# about this). However, as long as this is not solved in general,this test ensures
|
| 1673 |
+
# that the returned shape is consistent with this underlying array for
|
| 1674 |
+
# compat with matplotlib (see https://github.com/pandas-dev/pandas/issues/27775)
|
| 1675 |
+
idx = Index([0, 1, 2, 3])
|
| 1676 |
+
with pytest.raises(ValueError, match="Multi-dimensional indexing"):
|
| 1677 |
+
# GH#30588 multi-dimensional indexing deprecated
|
| 1678 |
+
idx[:, None]
|
| 1679 |
+
|
| 1680 |
+
|
| 1681 |
+
@pytest.mark.parametrize("dtype", [None, np.int64, np.uint64, np.float64])
|
| 1682 |
+
def test_validate_1d_input(dtype):
|
| 1683 |
+
# GH#27125 check that we do not have >1-dimensional input
|
| 1684 |
+
msg = "Index data must be 1-dimensional"
|
| 1685 |
+
|
| 1686 |
+
arr = np.arange(8).reshape(2, 2, 2)
|
| 1687 |
+
with pytest.raises(ValueError, match=msg):
|
| 1688 |
+
Index(arr, dtype=dtype)
|
| 1689 |
+
|
| 1690 |
+
df = DataFrame(arr.reshape(4, 2))
|
| 1691 |
+
with pytest.raises(ValueError, match=msg):
|
| 1692 |
+
Index(df, dtype=dtype)
|
| 1693 |
+
|
| 1694 |
+
# GH#13601 trying to assign a multi-dimensional array to an index is not allowed
|
| 1695 |
+
ser = Series(0, range(4))
|
| 1696 |
+
with pytest.raises(ValueError, match=msg):
|
| 1697 |
+
ser.index = np.array([[2, 3]] * 4, dtype=dtype)
|
| 1698 |
+
|
| 1699 |
+
|
| 1700 |
+
@pytest.mark.parametrize(
|
| 1701 |
+
"klass, extra_kwargs",
|
| 1702 |
+
[
|
| 1703 |
+
[Index, {}],
|
| 1704 |
+
*[[lambda x: Index(x, dtype=dtyp), {}] for dtyp in tm.ALL_REAL_NUMPY_DTYPES],
|
| 1705 |
+
[DatetimeIndex, {}],
|
| 1706 |
+
[TimedeltaIndex, {}],
|
| 1707 |
+
[PeriodIndex, {"freq": "Y"}],
|
| 1708 |
+
],
|
| 1709 |
+
)
|
| 1710 |
+
def test_construct_from_memoryview(klass, extra_kwargs):
|
| 1711 |
+
# GH 13120
|
| 1712 |
+
result = klass(memoryview(np.arange(2000, 2005)), **extra_kwargs)
|
| 1713 |
+
expected = klass(list(range(2000, 2005)), **extra_kwargs)
|
| 1714 |
+
tm.assert_index_equal(result, expected, exact=True)
|
| 1715 |
+
|
| 1716 |
+
|
| 1717 |
+
@pytest.mark.parametrize("op", [operator.lt, operator.gt])
|
| 1718 |
+
def test_nan_comparison_same_object(op):
|
| 1719 |
+
# GH#47105
|
| 1720 |
+
idx = Index([np.nan])
|
| 1721 |
+
expected = np.array([False])
|
| 1722 |
+
|
| 1723 |
+
result = op(idx, idx)
|
| 1724 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 1725 |
+
|
| 1726 |
+
result = op(idx, idx.copy())
|
| 1727 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 1728 |
+
|
| 1729 |
+
|
| 1730 |
+
@td.skip_if_no("pyarrow")
|
| 1731 |
+
def test_is_monotonic_pyarrow_list_type():
|
| 1732 |
+
# GH 57333
|
| 1733 |
+
import pyarrow as pa
|
| 1734 |
+
|
| 1735 |
+
idx = Index([[1], [2, 3]], dtype=pd.ArrowDtype(pa.list_(pa.int64())))
|
| 1736 |
+
assert not idx.is_monotonic_increasing
|
| 1737 |
+
assert not idx.is_monotonic_decreasing
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/test_common.py
ADDED
|
@@ -0,0 +1,512 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Collection of tests asserting things that should be true for
|
| 3 |
+
any index subclass except for MultiIndex. Makes use of the `index_flat`
|
| 4 |
+
fixture defined in pandas/conftest.py.
|
| 5 |
+
"""
|
| 6 |
+
from copy import (
|
| 7 |
+
copy,
|
| 8 |
+
deepcopy,
|
| 9 |
+
)
|
| 10 |
+
import re
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
import pytest
|
| 14 |
+
|
| 15 |
+
from pandas.compat import IS64
|
| 16 |
+
from pandas.compat.numpy import np_version_gte1p25
|
| 17 |
+
|
| 18 |
+
from pandas.core.dtypes.common import (
|
| 19 |
+
is_integer_dtype,
|
| 20 |
+
is_numeric_dtype,
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
import pandas as pd
|
| 24 |
+
from pandas import (
|
| 25 |
+
CategoricalIndex,
|
| 26 |
+
MultiIndex,
|
| 27 |
+
PeriodIndex,
|
| 28 |
+
RangeIndex,
|
| 29 |
+
)
|
| 30 |
+
import pandas._testing as tm
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class TestCommon:
|
| 34 |
+
@pytest.mark.parametrize("name", [None, "new_name"])
|
| 35 |
+
def test_to_frame(self, name, index_flat, using_copy_on_write):
|
| 36 |
+
# see GH#15230, GH#22580
|
| 37 |
+
idx = index_flat
|
| 38 |
+
|
| 39 |
+
if name:
|
| 40 |
+
idx_name = name
|
| 41 |
+
else:
|
| 42 |
+
idx_name = idx.name or 0
|
| 43 |
+
|
| 44 |
+
df = idx.to_frame(name=idx_name)
|
| 45 |
+
|
| 46 |
+
assert df.index is idx
|
| 47 |
+
assert len(df.columns) == 1
|
| 48 |
+
assert df.columns[0] == idx_name
|
| 49 |
+
if not using_copy_on_write:
|
| 50 |
+
assert df[idx_name].values is not idx.values
|
| 51 |
+
|
| 52 |
+
df = idx.to_frame(index=False, name=idx_name)
|
| 53 |
+
assert df.index is not idx
|
| 54 |
+
|
| 55 |
+
def test_droplevel(self, index_flat):
|
| 56 |
+
# GH 21115
|
| 57 |
+
# MultiIndex is tested separately in test_multi.py
|
| 58 |
+
index = index_flat
|
| 59 |
+
|
| 60 |
+
assert index.droplevel([]).equals(index)
|
| 61 |
+
|
| 62 |
+
for level in [index.name, [index.name]]:
|
| 63 |
+
if isinstance(index.name, tuple) and level is index.name:
|
| 64 |
+
# GH 21121 : droplevel with tuple name
|
| 65 |
+
continue
|
| 66 |
+
msg = (
|
| 67 |
+
"Cannot remove 1 levels from an index with 1 levels: at least one "
|
| 68 |
+
"level must be left."
|
| 69 |
+
)
|
| 70 |
+
with pytest.raises(ValueError, match=msg):
|
| 71 |
+
index.droplevel(level)
|
| 72 |
+
|
| 73 |
+
for level in "wrong", ["wrong"]:
|
| 74 |
+
with pytest.raises(
|
| 75 |
+
KeyError,
|
| 76 |
+
match=r"'Requested level \(wrong\) does not match index name \(None\)'",
|
| 77 |
+
):
|
| 78 |
+
index.droplevel(level)
|
| 79 |
+
|
| 80 |
+
def test_constructor_non_hashable_name(self, index_flat):
|
| 81 |
+
# GH 20527
|
| 82 |
+
index = index_flat
|
| 83 |
+
|
| 84 |
+
message = "Index.name must be a hashable type"
|
| 85 |
+
renamed = [["1"]]
|
| 86 |
+
|
| 87 |
+
# With .rename()
|
| 88 |
+
with pytest.raises(TypeError, match=message):
|
| 89 |
+
index.rename(name=renamed)
|
| 90 |
+
|
| 91 |
+
# With .set_names()
|
| 92 |
+
with pytest.raises(TypeError, match=message):
|
| 93 |
+
index.set_names(names=renamed)
|
| 94 |
+
|
| 95 |
+
def test_constructor_unwraps_index(self, index_flat):
|
| 96 |
+
a = index_flat
|
| 97 |
+
# Passing dtype is necessary for Index([True, False], dtype=object)
|
| 98 |
+
# case.
|
| 99 |
+
b = type(a)(a, dtype=a.dtype)
|
| 100 |
+
tm.assert_equal(a._data, b._data)
|
| 101 |
+
|
| 102 |
+
def test_to_flat_index(self, index_flat):
|
| 103 |
+
# 22866
|
| 104 |
+
index = index_flat
|
| 105 |
+
|
| 106 |
+
result = index.to_flat_index()
|
| 107 |
+
tm.assert_index_equal(result, index)
|
| 108 |
+
|
| 109 |
+
def test_set_name_methods(self, index_flat):
|
| 110 |
+
# MultiIndex tested separately
|
| 111 |
+
index = index_flat
|
| 112 |
+
new_name = "This is the new name for this index"
|
| 113 |
+
|
| 114 |
+
original_name = index.name
|
| 115 |
+
new_ind = index.set_names([new_name])
|
| 116 |
+
assert new_ind.name == new_name
|
| 117 |
+
assert index.name == original_name
|
| 118 |
+
res = index.rename(new_name, inplace=True)
|
| 119 |
+
|
| 120 |
+
# should return None
|
| 121 |
+
assert res is None
|
| 122 |
+
assert index.name == new_name
|
| 123 |
+
assert index.names == [new_name]
|
| 124 |
+
with pytest.raises(ValueError, match="Level must be None"):
|
| 125 |
+
index.set_names("a", level=0)
|
| 126 |
+
|
| 127 |
+
# rename in place just leaves tuples and other containers alone
|
| 128 |
+
name = ("A", "B")
|
| 129 |
+
index.rename(name, inplace=True)
|
| 130 |
+
assert index.name == name
|
| 131 |
+
assert index.names == [name]
|
| 132 |
+
|
| 133 |
+
@pytest.mark.xfail
|
| 134 |
+
def test_set_names_single_label_no_level(self, index_flat):
|
| 135 |
+
with pytest.raises(TypeError, match="list-like"):
|
| 136 |
+
# should still fail even if it would be the right length
|
| 137 |
+
index_flat.set_names("a")
|
| 138 |
+
|
| 139 |
+
def test_copy_and_deepcopy(self, index_flat):
|
| 140 |
+
index = index_flat
|
| 141 |
+
|
| 142 |
+
for func in (copy, deepcopy):
|
| 143 |
+
idx_copy = func(index)
|
| 144 |
+
assert idx_copy is not index
|
| 145 |
+
assert idx_copy.equals(index)
|
| 146 |
+
|
| 147 |
+
new_copy = index.copy(deep=True, name="banana")
|
| 148 |
+
assert new_copy.name == "banana"
|
| 149 |
+
|
| 150 |
+
def test_copy_name(self, index_flat):
|
| 151 |
+
# GH#12309: Check that the "name" argument
|
| 152 |
+
# passed at initialization is honored.
|
| 153 |
+
index = index_flat
|
| 154 |
+
|
| 155 |
+
first = type(index)(index, copy=True, name="mario")
|
| 156 |
+
second = type(first)(first, copy=False)
|
| 157 |
+
|
| 158 |
+
# Even though "copy=False", we want a new object.
|
| 159 |
+
assert first is not second
|
| 160 |
+
tm.assert_index_equal(first, second)
|
| 161 |
+
|
| 162 |
+
# Not using tm.assert_index_equal() since names differ.
|
| 163 |
+
assert index.equals(first)
|
| 164 |
+
|
| 165 |
+
assert first.name == "mario"
|
| 166 |
+
assert second.name == "mario"
|
| 167 |
+
|
| 168 |
+
# TODO: belongs in series arithmetic tests?
|
| 169 |
+
s1 = pd.Series(2, index=first)
|
| 170 |
+
s2 = pd.Series(3, index=second[:-1])
|
| 171 |
+
# See GH#13365
|
| 172 |
+
s3 = s1 * s2
|
| 173 |
+
assert s3.index.name == "mario"
|
| 174 |
+
|
| 175 |
+
def test_copy_name2(self, index_flat):
|
| 176 |
+
# GH#35592
|
| 177 |
+
index = index_flat
|
| 178 |
+
|
| 179 |
+
assert index.copy(name="mario").name == "mario"
|
| 180 |
+
|
| 181 |
+
with pytest.raises(ValueError, match="Length of new names must be 1, got 2"):
|
| 182 |
+
index.copy(name=["mario", "luigi"])
|
| 183 |
+
|
| 184 |
+
msg = f"{type(index).__name__}.name must be a hashable type"
|
| 185 |
+
with pytest.raises(TypeError, match=msg):
|
| 186 |
+
index.copy(name=[["mario"]])
|
| 187 |
+
|
| 188 |
+
def test_unique_level(self, index_flat):
|
| 189 |
+
# don't test a MultiIndex here (as its tested separated)
|
| 190 |
+
index = index_flat
|
| 191 |
+
|
| 192 |
+
# GH 17896
|
| 193 |
+
expected = index.drop_duplicates()
|
| 194 |
+
for level in [0, index.name, None]:
|
| 195 |
+
result = index.unique(level=level)
|
| 196 |
+
tm.assert_index_equal(result, expected)
|
| 197 |
+
|
| 198 |
+
msg = "Too many levels: Index has only 1 level, not 4"
|
| 199 |
+
with pytest.raises(IndexError, match=msg):
|
| 200 |
+
index.unique(level=3)
|
| 201 |
+
|
| 202 |
+
msg = (
|
| 203 |
+
rf"Requested level \(wrong\) does not match index name "
|
| 204 |
+
rf"\({re.escape(index.name.__repr__())}\)"
|
| 205 |
+
)
|
| 206 |
+
with pytest.raises(KeyError, match=msg):
|
| 207 |
+
index.unique(level="wrong")
|
| 208 |
+
|
| 209 |
+
def test_unique(self, index_flat):
|
| 210 |
+
# MultiIndex tested separately
|
| 211 |
+
index = index_flat
|
| 212 |
+
if not len(index):
|
| 213 |
+
pytest.skip("Skip check for empty Index and MultiIndex")
|
| 214 |
+
|
| 215 |
+
idx = index[[0] * 5]
|
| 216 |
+
idx_unique = index[[0]]
|
| 217 |
+
|
| 218 |
+
# We test against `idx_unique`, so first we make sure it's unique
|
| 219 |
+
# and doesn't contain nans.
|
| 220 |
+
assert idx_unique.is_unique is True
|
| 221 |
+
try:
|
| 222 |
+
assert idx_unique.hasnans is False
|
| 223 |
+
except NotImplementedError:
|
| 224 |
+
pass
|
| 225 |
+
|
| 226 |
+
result = idx.unique()
|
| 227 |
+
tm.assert_index_equal(result, idx_unique)
|
| 228 |
+
|
| 229 |
+
# nans:
|
| 230 |
+
if not index._can_hold_na:
|
| 231 |
+
pytest.skip("Skip na-check if index cannot hold na")
|
| 232 |
+
|
| 233 |
+
vals = index._values[[0] * 5]
|
| 234 |
+
vals[0] = np.nan
|
| 235 |
+
|
| 236 |
+
vals_unique = vals[:2]
|
| 237 |
+
idx_nan = index._shallow_copy(vals)
|
| 238 |
+
idx_unique_nan = index._shallow_copy(vals_unique)
|
| 239 |
+
assert idx_unique_nan.is_unique is True
|
| 240 |
+
|
| 241 |
+
assert idx_nan.dtype == index.dtype
|
| 242 |
+
assert idx_unique_nan.dtype == index.dtype
|
| 243 |
+
|
| 244 |
+
expected = idx_unique_nan
|
| 245 |
+
for pos, i in enumerate([idx_nan, idx_unique_nan]):
|
| 246 |
+
result = i.unique()
|
| 247 |
+
tm.assert_index_equal(result, expected)
|
| 248 |
+
|
| 249 |
+
@pytest.mark.filterwarnings("ignore:Period with BDay freq:FutureWarning")
|
| 250 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
| 251 |
+
def test_searchsorted_monotonic(self, index_flat, request):
|
| 252 |
+
# GH17271
|
| 253 |
+
index = index_flat
|
| 254 |
+
# not implemented for tuple searches in MultiIndex
|
| 255 |
+
# or Intervals searches in IntervalIndex
|
| 256 |
+
if isinstance(index, pd.IntervalIndex):
|
| 257 |
+
mark = pytest.mark.xfail(
|
| 258 |
+
reason="IntervalIndex.searchsorted does not support Interval arg",
|
| 259 |
+
raises=NotImplementedError,
|
| 260 |
+
)
|
| 261 |
+
request.applymarker(mark)
|
| 262 |
+
|
| 263 |
+
# nothing to test if the index is empty
|
| 264 |
+
if index.empty:
|
| 265 |
+
pytest.skip("Skip check for empty Index")
|
| 266 |
+
value = index[0]
|
| 267 |
+
|
| 268 |
+
# determine the expected results (handle dupes for 'right')
|
| 269 |
+
expected_left, expected_right = 0, (index == value).argmin()
|
| 270 |
+
if expected_right == 0:
|
| 271 |
+
# all values are the same, expected_right should be length
|
| 272 |
+
expected_right = len(index)
|
| 273 |
+
|
| 274 |
+
# test _searchsorted_monotonic in all cases
|
| 275 |
+
# test searchsorted only for increasing
|
| 276 |
+
if index.is_monotonic_increasing:
|
| 277 |
+
ssm_left = index._searchsorted_monotonic(value, side="left")
|
| 278 |
+
assert expected_left == ssm_left
|
| 279 |
+
|
| 280 |
+
ssm_right = index._searchsorted_monotonic(value, side="right")
|
| 281 |
+
assert expected_right == ssm_right
|
| 282 |
+
|
| 283 |
+
ss_left = index.searchsorted(value, side="left")
|
| 284 |
+
assert expected_left == ss_left
|
| 285 |
+
|
| 286 |
+
ss_right = index.searchsorted(value, side="right")
|
| 287 |
+
assert expected_right == ss_right
|
| 288 |
+
|
| 289 |
+
elif index.is_monotonic_decreasing:
|
| 290 |
+
ssm_left = index._searchsorted_monotonic(value, side="left")
|
| 291 |
+
assert expected_left == ssm_left
|
| 292 |
+
|
| 293 |
+
ssm_right = index._searchsorted_monotonic(value, side="right")
|
| 294 |
+
assert expected_right == ssm_right
|
| 295 |
+
else:
|
| 296 |
+
# non-monotonic should raise.
|
| 297 |
+
msg = "index must be monotonic increasing or decreasing"
|
| 298 |
+
with pytest.raises(ValueError, match=msg):
|
| 299 |
+
index._searchsorted_monotonic(value, side="left")
|
| 300 |
+
|
| 301 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
| 302 |
+
def test_drop_duplicates(self, index_flat, keep):
|
| 303 |
+
# MultiIndex is tested separately
|
| 304 |
+
index = index_flat
|
| 305 |
+
if isinstance(index, RangeIndex):
|
| 306 |
+
pytest.skip(
|
| 307 |
+
"RangeIndex is tested in test_drop_duplicates_no_duplicates "
|
| 308 |
+
"as it cannot hold duplicates"
|
| 309 |
+
)
|
| 310 |
+
if len(index) == 0:
|
| 311 |
+
pytest.skip(
|
| 312 |
+
"empty index is tested in test_drop_duplicates_no_duplicates "
|
| 313 |
+
"as it cannot hold duplicates"
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
# make unique index
|
| 317 |
+
holder = type(index)
|
| 318 |
+
unique_values = list(set(index))
|
| 319 |
+
dtype = index.dtype if is_numeric_dtype(index) else None
|
| 320 |
+
unique_idx = holder(unique_values, dtype=dtype)
|
| 321 |
+
|
| 322 |
+
# make duplicated index
|
| 323 |
+
n = len(unique_idx)
|
| 324 |
+
duplicated_selection = np.random.default_rng(2).choice(n, int(n * 1.5))
|
| 325 |
+
idx = holder(unique_idx.values[duplicated_selection])
|
| 326 |
+
|
| 327 |
+
# Series.duplicated is tested separately
|
| 328 |
+
expected_duplicated = (
|
| 329 |
+
pd.Series(duplicated_selection).duplicated(keep=keep).values
|
| 330 |
+
)
|
| 331 |
+
tm.assert_numpy_array_equal(idx.duplicated(keep=keep), expected_duplicated)
|
| 332 |
+
|
| 333 |
+
# Series.drop_duplicates is tested separately
|
| 334 |
+
expected_dropped = holder(pd.Series(idx).drop_duplicates(keep=keep))
|
| 335 |
+
tm.assert_index_equal(idx.drop_duplicates(keep=keep), expected_dropped)
|
| 336 |
+
|
| 337 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
| 338 |
+
def test_drop_duplicates_no_duplicates(self, index_flat):
|
| 339 |
+
# MultiIndex is tested separately
|
| 340 |
+
index = index_flat
|
| 341 |
+
|
| 342 |
+
# make unique index
|
| 343 |
+
if isinstance(index, RangeIndex):
|
| 344 |
+
# RangeIndex cannot have duplicates
|
| 345 |
+
unique_idx = index
|
| 346 |
+
else:
|
| 347 |
+
holder = type(index)
|
| 348 |
+
unique_values = list(set(index))
|
| 349 |
+
dtype = index.dtype if is_numeric_dtype(index) else None
|
| 350 |
+
unique_idx = holder(unique_values, dtype=dtype)
|
| 351 |
+
|
| 352 |
+
# check on unique index
|
| 353 |
+
expected_duplicated = np.array([False] * len(unique_idx), dtype="bool")
|
| 354 |
+
tm.assert_numpy_array_equal(unique_idx.duplicated(), expected_duplicated)
|
| 355 |
+
result_dropped = unique_idx.drop_duplicates()
|
| 356 |
+
tm.assert_index_equal(result_dropped, unique_idx)
|
| 357 |
+
# validate shallow copy
|
| 358 |
+
assert result_dropped is not unique_idx
|
| 359 |
+
|
| 360 |
+
def test_drop_duplicates_inplace(self, index):
|
| 361 |
+
msg = r"drop_duplicates\(\) got an unexpected keyword argument"
|
| 362 |
+
with pytest.raises(TypeError, match=msg):
|
| 363 |
+
index.drop_duplicates(inplace=True)
|
| 364 |
+
|
| 365 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
| 366 |
+
def test_has_duplicates(self, index_flat):
|
| 367 |
+
# MultiIndex tested separately in:
|
| 368 |
+
# tests/indexes/multi/test_unique_and_duplicates.
|
| 369 |
+
index = index_flat
|
| 370 |
+
holder = type(index)
|
| 371 |
+
if not len(index) or isinstance(index, RangeIndex):
|
| 372 |
+
# MultiIndex tested separately in:
|
| 373 |
+
# tests/indexes/multi/test_unique_and_duplicates.
|
| 374 |
+
# RangeIndex is unique by definition.
|
| 375 |
+
pytest.skip("Skip check for empty Index, MultiIndex, and RangeIndex")
|
| 376 |
+
|
| 377 |
+
idx = holder([index[0]] * 5)
|
| 378 |
+
assert idx.is_unique is False
|
| 379 |
+
assert idx.has_duplicates is True
|
| 380 |
+
|
| 381 |
+
@pytest.mark.parametrize(
|
| 382 |
+
"dtype",
|
| 383 |
+
["int64", "uint64", "float64", "category", "datetime64[ns]", "timedelta64[ns]"],
|
| 384 |
+
)
|
| 385 |
+
def test_astype_preserves_name(self, index, dtype):
|
| 386 |
+
# https://github.com/pandas-dev/pandas/issues/32013
|
| 387 |
+
if isinstance(index, MultiIndex):
|
| 388 |
+
index.names = ["idx" + str(i) for i in range(index.nlevels)]
|
| 389 |
+
else:
|
| 390 |
+
index.name = "idx"
|
| 391 |
+
|
| 392 |
+
warn = None
|
| 393 |
+
if index.dtype.kind == "c" and dtype in ["float64", "int64", "uint64"]:
|
| 394 |
+
# imaginary components discarded
|
| 395 |
+
if np_version_gte1p25:
|
| 396 |
+
warn = np.exceptions.ComplexWarning
|
| 397 |
+
else:
|
| 398 |
+
warn = np.ComplexWarning
|
| 399 |
+
|
| 400 |
+
is_pyarrow_str = str(index.dtype) == "string[pyarrow]" and dtype == "category"
|
| 401 |
+
try:
|
| 402 |
+
# Some of these conversions cannot succeed so we use a try / except
|
| 403 |
+
with tm.assert_produces_warning(
|
| 404 |
+
warn,
|
| 405 |
+
raise_on_extra_warnings=is_pyarrow_str,
|
| 406 |
+
check_stacklevel=False,
|
| 407 |
+
):
|
| 408 |
+
result = index.astype(dtype)
|
| 409 |
+
except (ValueError, TypeError, NotImplementedError, SystemError):
|
| 410 |
+
return
|
| 411 |
+
|
| 412 |
+
if isinstance(index, MultiIndex):
|
| 413 |
+
assert result.names == index.names
|
| 414 |
+
else:
|
| 415 |
+
assert result.name == index.name
|
| 416 |
+
|
| 417 |
+
def test_hasnans_isnans(self, index_flat):
|
| 418 |
+
# GH#11343, added tests for hasnans / isnans
|
| 419 |
+
index = index_flat
|
| 420 |
+
|
| 421 |
+
# cases in indices doesn't include NaN
|
| 422 |
+
idx = index.copy(deep=True)
|
| 423 |
+
expected = np.array([False] * len(idx), dtype=bool)
|
| 424 |
+
tm.assert_numpy_array_equal(idx._isnan, expected)
|
| 425 |
+
assert idx.hasnans is False
|
| 426 |
+
|
| 427 |
+
idx = index.copy(deep=True)
|
| 428 |
+
values = idx._values
|
| 429 |
+
|
| 430 |
+
if len(index) == 0:
|
| 431 |
+
return
|
| 432 |
+
elif is_integer_dtype(index.dtype):
|
| 433 |
+
return
|
| 434 |
+
elif index.dtype == bool:
|
| 435 |
+
# values[1] = np.nan below casts to True!
|
| 436 |
+
return
|
| 437 |
+
|
| 438 |
+
values[1] = np.nan
|
| 439 |
+
|
| 440 |
+
idx = type(index)(values)
|
| 441 |
+
|
| 442 |
+
expected = np.array([False] * len(idx), dtype=bool)
|
| 443 |
+
expected[1] = True
|
| 444 |
+
tm.assert_numpy_array_equal(idx._isnan, expected)
|
| 445 |
+
assert idx.hasnans is True
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
| 449 |
+
@pytest.mark.parametrize("na_position", [None, "middle"])
|
| 450 |
+
def test_sort_values_invalid_na_position(index_with_missing, na_position):
|
| 451 |
+
with pytest.raises(ValueError, match=f"invalid na_position: {na_position}"):
|
| 452 |
+
index_with_missing.sort_values(na_position=na_position)
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
@pytest.mark.fails_arm_wheels
|
| 456 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
| 457 |
+
@pytest.mark.parametrize("na_position", ["first", "last"])
|
| 458 |
+
def test_sort_values_with_missing(index_with_missing, na_position, request):
|
| 459 |
+
# GH 35584. Test that sort_values works with missing values,
|
| 460 |
+
# sort non-missing and place missing according to na_position
|
| 461 |
+
|
| 462 |
+
if isinstance(index_with_missing, CategoricalIndex):
|
| 463 |
+
request.applymarker(
|
| 464 |
+
pytest.mark.xfail(
|
| 465 |
+
reason="missing value sorting order not well-defined", strict=False
|
| 466 |
+
)
|
| 467 |
+
)
|
| 468 |
+
|
| 469 |
+
missing_count = np.sum(index_with_missing.isna())
|
| 470 |
+
not_na_vals = index_with_missing[index_with_missing.notna()].values
|
| 471 |
+
sorted_values = np.sort(not_na_vals)
|
| 472 |
+
if na_position == "first":
|
| 473 |
+
sorted_values = np.concatenate([[None] * missing_count, sorted_values])
|
| 474 |
+
else:
|
| 475 |
+
sorted_values = np.concatenate([sorted_values, [None] * missing_count])
|
| 476 |
+
|
| 477 |
+
# Explicitly pass dtype needed for Index backed by EA e.g. IntegerArray
|
| 478 |
+
expected = type(index_with_missing)(sorted_values, dtype=index_with_missing.dtype)
|
| 479 |
+
|
| 480 |
+
result = index_with_missing.sort_values(na_position=na_position)
|
| 481 |
+
tm.assert_index_equal(result, expected)
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
def test_ndarray_compat_properties(index):
|
| 485 |
+
if isinstance(index, PeriodIndex) and not IS64:
|
| 486 |
+
pytest.skip("Overflow")
|
| 487 |
+
idx = index
|
| 488 |
+
assert idx.T.equals(idx)
|
| 489 |
+
assert idx.transpose().equals(idx)
|
| 490 |
+
|
| 491 |
+
values = idx.values
|
| 492 |
+
|
| 493 |
+
assert idx.shape == values.shape
|
| 494 |
+
assert idx.ndim == values.ndim
|
| 495 |
+
assert idx.size == values.size
|
| 496 |
+
|
| 497 |
+
if not isinstance(index, (RangeIndex, MultiIndex)):
|
| 498 |
+
# These two are not backed by an ndarray
|
| 499 |
+
assert idx.nbytes == values.nbytes
|
| 500 |
+
|
| 501 |
+
# test for validity
|
| 502 |
+
idx.nbytes
|
| 503 |
+
idx.values.nbytes
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
def test_compare_read_only_array():
|
| 507 |
+
# GH#57130
|
| 508 |
+
arr = np.array([], dtype=object)
|
| 509 |
+
arr.flags.writeable = False
|
| 510 |
+
idx = pd.Index(arr)
|
| 511 |
+
result = idx > 69
|
| 512 |
+
assert result.dtype == bool
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/test_datetimelike.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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andas._testing as tm
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class TestDatetimeLike:
|
| 11 |
+
@pytest.fixture(
|
| 12 |
+
params=[
|
| 13 |
+
pd.period_range("20130101", periods=5, freq="D"),
|
| 14 |
+
pd.TimedeltaIndex(
|
| 15 |
+
[
|
| 16 |
+
"0 days 01:00:00",
|
| 17 |
+
"1 days 01:00:00",
|
| 18 |
+
"2 days 01:00:00",
|
| 19 |
+
"3 days 01:00:00",
|
| 20 |
+
"4 days 01:00:00",
|
| 21 |
+
],
|
| 22 |
+
dtype="timedelta64[ns]",
|
| 23 |
+
freq="D",
|
| 24 |
+
),
|
| 25 |
+
pd.DatetimeIndex(
|
| 26 |
+
["2013-01-01", "2013-01-02", "2013-01-03", "2013-01-04", "2013-01-05"],
|
| 27 |
+
dtype="datetime64[ns]",
|
| 28 |
+
freq="D",
|
| 29 |
+
),
|
| 30 |
+
]
|
| 31 |
+
)
|
| 32 |
+
def simple_index(self, request):
|
| 33 |
+
return request.param
|
| 34 |
+
|
| 35 |
+
def test_isin(self, simple_index):
|
| 36 |
+
index = simple_index[:4]
|
| 37 |
+
result = index.isin(index)
|
| 38 |
+
assert result.all()
|
| 39 |
+
|
| 40 |
+
result = index.isin(list(index))
|
| 41 |
+
assert result.all()
|
| 42 |
+
|
| 43 |
+
result = index.isin([index[2], 5])
|
| 44 |
+
expected = np.array([False, False, True, False])
|
| 45 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 46 |
+
|
| 47 |
+
def test_argsort_matches_array(self, simple_index):
|
| 48 |
+
idx = simple_index
|
| 49 |
+
idx = idx.insert(1, pd.NaT)
|
| 50 |
+
|
| 51 |
+
result = idx.argsort()
|
| 52 |
+
expected = idx._data.argsort()
|
| 53 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 54 |
+
|
| 55 |
+
def test_can_hold_identifiers(self, simple_index):
|
| 56 |
+
idx = simple_index
|
| 57 |
+
key = idx[0]
|
| 58 |
+
assert idx._can_hold_identifiers_and_holds_name(key) is False
|
| 59 |
+
|
| 60 |
+
def test_shift_identity(self, simple_index):
|
| 61 |
+
idx = simple_index
|
| 62 |
+
tm.assert_index_equal(idx, idx.shift(0))
|
| 63 |
+
|
| 64 |
+
def test_shift_empty(self, simple_index):
|
| 65 |
+
# GH#14811
|
| 66 |
+
idx = simple_index[:0]
|
| 67 |
+
tm.assert_index_equal(idx, idx.shift(1))
|
| 68 |
+
|
| 69 |
+
def test_str(self, simple_index):
|
| 70 |
+
# test the string repr
|
| 71 |
+
idx = simple_index.copy()
|
| 72 |
+
idx.name = "foo"
|
| 73 |
+
assert f"length={len(idx)}" not in str(idx)
|
| 74 |
+
assert "'foo'" in str(idx)
|
| 75 |
+
assert type(idx).__name__ in str(idx)
|
| 76 |
+
|
| 77 |
+
if hasattr(idx, "tz"):
|
| 78 |
+
if idx.tz is not None:
|
| 79 |
+
assert idx.tz in str(idx)
|
| 80 |
+
if isinstance(idx, pd.PeriodIndex):
|
| 81 |
+
assert f"dtype='period[{idx.freqstr}]'" in str(idx)
|
| 82 |
+
else:
|
| 83 |
+
assert f"freq='{idx.freqstr}'" in str(idx)
|
| 84 |
+
|
| 85 |
+
def test_view(self, simple_index):
|
| 86 |
+
idx = simple_index
|
| 87 |
+
|
| 88 |
+
idx_view = idx.view("i8")
|
| 89 |
+
result = type(simple_index)(idx)
|
| 90 |
+
tm.assert_index_equal(result, idx)
|
| 91 |
+
|
| 92 |
+
msg = "Passing a type in .*Index.view is deprecated"
|
| 93 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 94 |
+
idx_view = idx.view(type(simple_index))
|
| 95 |
+
result = type(simple_index)(idx)
|
| 96 |
+
tm.assert_index_equal(result, idx_view)
|
| 97 |
+
|
| 98 |
+
def test_map_callable(self, simple_index):
|
| 99 |
+
index = simple_index
|
| 100 |
+
expected = index + index.freq
|
| 101 |
+
result = index.map(lambda x: x + index.freq)
|
| 102 |
+
tm.assert_index_equal(result, expected)
|
| 103 |
+
|
| 104 |
+
# map to NaT
|
| 105 |
+
result = index.map(lambda x: pd.NaT if x == index[0] else x)
|
| 106 |
+
expected = pd.Index([pd.NaT] + index[1:].tolist())
|
| 107 |
+
tm.assert_index_equal(result, expected)
|
| 108 |
+
|
| 109 |
+
@pytest.mark.parametrize(
|
| 110 |
+
"mapper",
|
| 111 |
+
[
|
| 112 |
+
lambda values, index: {i: e for e, i in zip(values, index)},
|
| 113 |
+
lambda values, index: pd.Series(values, index, dtype=object),
|
| 114 |
+
],
|
| 115 |
+
)
|
| 116 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
| 117 |
+
def test_map_dictlike(self, mapper, simple_index):
|
| 118 |
+
index = simple_index
|
| 119 |
+
expected = index + index.freq
|
| 120 |
+
|
| 121 |
+
# don't compare the freqs
|
| 122 |
+
if isinstance(expected, (pd.DatetimeIndex, pd.TimedeltaIndex)):
|
| 123 |
+
expected = expected._with_freq(None)
|
| 124 |
+
|
| 125 |
+
result = index.map(mapper(expected, index))
|
| 126 |
+
tm.assert_index_equal(result, expected)
|
| 127 |
+
|
| 128 |
+
expected = pd.Index([pd.NaT] + index[1:].tolist())
|
| 129 |
+
result = index.map(mapper(expected, index))
|
| 130 |
+
tm.assert_index_equal(result, expected)
|
| 131 |
+
|
| 132 |
+
# empty map; these map to np.nan because we cannot know
|
| 133 |
+
# to re-infer things
|
| 134 |
+
expected = pd.Index([np.nan] * len(index))
|
| 135 |
+
result = index.map(mapper([], []))
|
| 136 |
+
tm.assert_index_equal(result, expected)
|
| 137 |
+
|
| 138 |
+
def test_getitem_preserves_freq(self, simple_index):
|
| 139 |
+
index = simple_index
|
| 140 |
+
assert index.freq is not None
|
| 141 |
+
|
| 142 |
+
result = index[:]
|
| 143 |
+
assert result.freq == index.freq
|
| 144 |
+
|
| 145 |
+
def test_where_cast_str(self, simple_index):
|
| 146 |
+
index = simple_index
|
| 147 |
+
|
| 148 |
+
mask = np.ones(len(index), dtype=bool)
|
| 149 |
+
mask[-1] = False
|
| 150 |
+
|
| 151 |
+
result = index.where(mask, str(index[0]))
|
| 152 |
+
expected = index.where(mask, index[0])
|
| 153 |
+
tm.assert_index_equal(result, expected)
|
| 154 |
+
|
| 155 |
+
result = index.where(mask, [str(index[0])])
|
| 156 |
+
tm.assert_index_equal(result, expected)
|
| 157 |
+
|
| 158 |
+
expected = index.astype(object).where(mask, "foo")
|
| 159 |
+
result = index.where(mask, "foo")
|
| 160 |
+
tm.assert_index_equal(result, expected)
|
| 161 |
+
|
| 162 |
+
result = index.where(mask, ["foo"])
|
| 163 |
+
tm.assert_index_equal(result, expected)
|
| 164 |
+
|
| 165 |
+
@pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
|
| 166 |
+
def test_diff(self, unit):
|
| 167 |
+
# GH 55080
|
| 168 |
+
dti = pd.to_datetime([10, 20, 30], unit=unit).as_unit(unit)
|
| 169 |
+
result = dti.diff(1)
|
| 170 |
+
expected = pd.to_timedelta([pd.NaT, 10, 10], unit=unit).as_unit(unit)
|
| 171 |
+
tm.assert_index_equal(result, expected)
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/test_engines.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from pandas._libs import index as libindex
|
| 7 |
+
|
| 8 |
+
import pandas as pd
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@pytest.fixture(
|
| 12 |
+
params=[
|
| 13 |
+
(libindex.Int64Engine, np.int64),
|
| 14 |
+
(libindex.Int32Engine, np.int32),
|
| 15 |
+
(libindex.Int16Engine, np.int16),
|
| 16 |
+
(libindex.Int8Engine, np.int8),
|
| 17 |
+
(libindex.UInt64Engine, np.uint64),
|
| 18 |
+
(libindex.UInt32Engine, np.uint32),
|
| 19 |
+
(libindex.UInt16Engine, np.uint16),
|
| 20 |
+
(libindex.UInt8Engine, np.uint8),
|
| 21 |
+
(libindex.Float64Engine, np.float64),
|
| 22 |
+
(libindex.Float32Engine, np.float32),
|
| 23 |
+
],
|
| 24 |
+
ids=lambda x: x[0].__name__,
|
| 25 |
+
)
|
| 26 |
+
def numeric_indexing_engine_type_and_dtype(request):
|
| 27 |
+
return request.param
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class TestDatetimeEngine:
|
| 31 |
+
@pytest.mark.parametrize(
|
| 32 |
+
"scalar",
|
| 33 |
+
[
|
| 34 |
+
pd.Timedelta(pd.Timestamp("2016-01-01").asm8.view("m8[ns]")),
|
| 35 |
+
pd.Timestamp("2016-01-01")._value,
|
| 36 |
+
pd.Timestamp("2016-01-01").to_pydatetime(),
|
| 37 |
+
pd.Timestamp("2016-01-01").to_datetime64(),
|
| 38 |
+
],
|
| 39 |
+
)
|
| 40 |
+
def test_not_contains_requires_timestamp(self, scalar):
|
| 41 |
+
dti1 = pd.date_range("2016-01-01", periods=3)
|
| 42 |
+
dti2 = dti1.insert(1, pd.NaT) # non-monotonic
|
| 43 |
+
dti3 = dti1.insert(3, dti1[0]) # non-unique
|
| 44 |
+
dti4 = pd.date_range("2016-01-01", freq="ns", periods=2_000_000)
|
| 45 |
+
dti5 = dti4.insert(0, dti4[0]) # over size threshold, not unique
|
| 46 |
+
|
| 47 |
+
msg = "|".join([re.escape(str(scalar)), re.escape(repr(scalar))])
|
| 48 |
+
for dti in [dti1, dti2, dti3, dti4, dti5]:
|
| 49 |
+
with pytest.raises(TypeError, match=msg):
|
| 50 |
+
scalar in dti._engine
|
| 51 |
+
|
| 52 |
+
with pytest.raises(KeyError, match=msg):
|
| 53 |
+
dti._engine.get_loc(scalar)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class TestTimedeltaEngine:
|
| 57 |
+
@pytest.mark.parametrize(
|
| 58 |
+
"scalar",
|
| 59 |
+
[
|
| 60 |
+
pd.Timestamp(pd.Timedelta(days=42).asm8.view("datetime64[ns]")),
|
| 61 |
+
pd.Timedelta(days=42)._value,
|
| 62 |
+
pd.Timedelta(days=42).to_pytimedelta(),
|
| 63 |
+
pd.Timedelta(days=42).to_timedelta64(),
|
| 64 |
+
],
|
| 65 |
+
)
|
| 66 |
+
def test_not_contains_requires_timedelta(self, scalar):
|
| 67 |
+
tdi1 = pd.timedelta_range("42 days", freq="9h", periods=1234)
|
| 68 |
+
tdi2 = tdi1.insert(1, pd.NaT) # non-monotonic
|
| 69 |
+
tdi3 = tdi1.insert(3, tdi1[0]) # non-unique
|
| 70 |
+
tdi4 = pd.timedelta_range("42 days", freq="ns", periods=2_000_000)
|
| 71 |
+
tdi5 = tdi4.insert(0, tdi4[0]) # over size threshold, not unique
|
| 72 |
+
|
| 73 |
+
msg = "|".join([re.escape(str(scalar)), re.escape(repr(scalar))])
|
| 74 |
+
for tdi in [tdi1, tdi2, tdi3, tdi4, tdi5]:
|
| 75 |
+
with pytest.raises(TypeError, match=msg):
|
| 76 |
+
scalar in tdi._engine
|
| 77 |
+
|
| 78 |
+
with pytest.raises(KeyError, match=msg):
|
| 79 |
+
tdi._engine.get_loc(scalar)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class TestNumericEngine:
|
| 83 |
+
def test_is_monotonic(self, numeric_indexing_engine_type_and_dtype):
|
| 84 |
+
engine_type, dtype = numeric_indexing_engine_type_and_dtype
|
| 85 |
+
num = 1000
|
| 86 |
+
arr = np.array([1] * num + [2] * num + [3] * num, dtype=dtype)
|
| 87 |
+
|
| 88 |
+
# monotonic increasing
|
| 89 |
+
engine = engine_type(arr)
|
| 90 |
+
assert engine.is_monotonic_increasing is True
|
| 91 |
+
assert engine.is_monotonic_decreasing is False
|
| 92 |
+
|
| 93 |
+
# monotonic decreasing
|
| 94 |
+
engine = engine_type(arr[::-1])
|
| 95 |
+
assert engine.is_monotonic_increasing is False
|
| 96 |
+
assert engine.is_monotonic_decreasing is True
|
| 97 |
+
|
| 98 |
+
# neither monotonic increasing or decreasing
|
| 99 |
+
arr = np.array([1] * num + [2] * num + [1] * num, dtype=dtype)
|
| 100 |
+
engine = engine_type(arr[::-1])
|
| 101 |
+
assert engine.is_monotonic_increasing is False
|
| 102 |
+
assert engine.is_monotonic_decreasing is False
|
| 103 |
+
|
| 104 |
+
def test_is_unique(self, numeric_indexing_engine_type_and_dtype):
|
| 105 |
+
engine_type, dtype = numeric_indexing_engine_type_and_dtype
|
| 106 |
+
|
| 107 |
+
# unique
|
| 108 |
+
arr = np.array([1, 3, 2], dtype=dtype)
|
| 109 |
+
engine = engine_type(arr)
|
| 110 |
+
assert engine.is_unique is True
|
| 111 |
+
|
| 112 |
+
# not unique
|
| 113 |
+
arr = np.array([1, 2, 1], dtype=dtype)
|
| 114 |
+
engine = engine_type(arr)
|
| 115 |
+
assert engine.is_unique is False
|
| 116 |
+
|
| 117 |
+
def test_get_loc(self, numeric_indexing_engine_type_and_dtype):
|
| 118 |
+
engine_type, dtype = numeric_indexing_engine_type_and_dtype
|
| 119 |
+
|
| 120 |
+
# unique
|
| 121 |
+
arr = np.array([1, 2, 3], dtype=dtype)
|
| 122 |
+
engine = engine_type(arr)
|
| 123 |
+
assert engine.get_loc(2) == 1
|
| 124 |
+
|
| 125 |
+
# monotonic
|
| 126 |
+
num = 1000
|
| 127 |
+
arr = np.array([1] * num + [2] * num + [3] * num, dtype=dtype)
|
| 128 |
+
engine = engine_type(arr)
|
| 129 |
+
assert engine.get_loc(2) == slice(1000, 2000)
|
| 130 |
+
|
| 131 |
+
# not monotonic
|
| 132 |
+
arr = np.array([1, 2, 3] * num, dtype=dtype)
|
| 133 |
+
engine = engine_type(arr)
|
| 134 |
+
expected = np.array([False, True, False] * num, dtype=bool)
|
| 135 |
+
result = engine.get_loc(2)
|
| 136 |
+
assert (result == expected).all()
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class TestObjectEngine:
|
| 140 |
+
engine_type = libindex.ObjectEngine
|
| 141 |
+
dtype = np.object_
|
| 142 |
+
values = list("abc")
|
| 143 |
+
|
| 144 |
+
def test_is_monotonic(self):
|
| 145 |
+
num = 1000
|
| 146 |
+
arr = np.array(["a"] * num + ["a"] * num + ["c"] * num, dtype=self.dtype)
|
| 147 |
+
|
| 148 |
+
# monotonic increasing
|
| 149 |
+
engine = self.engine_type(arr)
|
| 150 |
+
assert engine.is_monotonic_increasing is True
|
| 151 |
+
assert engine.is_monotonic_decreasing is False
|
| 152 |
+
|
| 153 |
+
# monotonic decreasing
|
| 154 |
+
engine = self.engine_type(arr[::-1])
|
| 155 |
+
assert engine.is_monotonic_increasing is False
|
| 156 |
+
assert engine.is_monotonic_decreasing is True
|
| 157 |
+
|
| 158 |
+
# neither monotonic increasing or decreasing
|
| 159 |
+
arr = np.array(["a"] * num + ["b"] * num + ["a"] * num, dtype=self.dtype)
|
| 160 |
+
engine = self.engine_type(arr[::-1])
|
| 161 |
+
assert engine.is_monotonic_increasing is False
|
| 162 |
+
assert engine.is_monotonic_decreasing is False
|
| 163 |
+
|
| 164 |
+
def test_is_unique(self):
|
| 165 |
+
# unique
|
| 166 |
+
arr = np.array(self.values, dtype=self.dtype)
|
| 167 |
+
engine = self.engine_type(arr)
|
| 168 |
+
assert engine.is_unique is True
|
| 169 |
+
|
| 170 |
+
# not unique
|
| 171 |
+
arr = np.array(["a", "b", "a"], dtype=self.dtype)
|
| 172 |
+
engine = self.engine_type(arr)
|
| 173 |
+
assert engine.is_unique is False
|
| 174 |
+
|
| 175 |
+
def test_get_loc(self):
|
| 176 |
+
# unique
|
| 177 |
+
arr = np.array(self.values, dtype=self.dtype)
|
| 178 |
+
engine = self.engine_type(arr)
|
| 179 |
+
assert engine.get_loc("b") == 1
|
| 180 |
+
|
| 181 |
+
# monotonic
|
| 182 |
+
num = 1000
|
| 183 |
+
arr = np.array(["a"] * num + ["b"] * num + ["c"] * num, dtype=self.dtype)
|
| 184 |
+
engine = self.engine_type(arr)
|
| 185 |
+
assert engine.get_loc("b") == slice(1000, 2000)
|
| 186 |
+
|
| 187 |
+
# not monotonic
|
| 188 |
+
arr = np.array(self.values * num, dtype=self.dtype)
|
| 189 |
+
engine = self.engine_type(arr)
|
| 190 |
+
expected = np.array([False, True, False] * num, dtype=bool)
|
| 191 |
+
result = engine.get_loc("b")
|
| 192 |
+
assert (result == expected).all()
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/test_frozen.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
from pandas.core.indexes.frozen import FrozenList
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@pytest.fixture
|
| 9 |
+
def lst():
|
| 10 |
+
return [1, 2, 3, 4, 5]
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@pytest.fixture
|
| 14 |
+
def container(lst):
|
| 15 |
+
return FrozenList(lst)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@pytest.fixture
|
| 19 |
+
def unicode_container():
|
| 20 |
+
return FrozenList(["\u05d0", "\u05d1", "c"])
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class TestFrozenList:
|
| 24 |
+
def check_mutable_error(self, *args, **kwargs):
|
| 25 |
+
# Pass whatever function you normally would to pytest.raises
|
| 26 |
+
# (after the Exception kind).
|
| 27 |
+
mutable_regex = re.compile("does not support mutable operations")
|
| 28 |
+
msg = "'(_s)?re.(SRE_)?Pattern' object is not callable"
|
| 29 |
+
with pytest.raises(TypeError, match=msg):
|
| 30 |
+
mutable_regex(*args, **kwargs)
|
| 31 |
+
|
| 32 |
+
def test_no_mutable_funcs(self, container):
|
| 33 |
+
def setitem():
|
| 34 |
+
container[0] = 5
|
| 35 |
+
|
| 36 |
+
self.check_mutable_error(setitem)
|
| 37 |
+
|
| 38 |
+
def setslice():
|
| 39 |
+
container[1:2] = 3
|
| 40 |
+
|
| 41 |
+
self.check_mutable_error(setslice)
|
| 42 |
+
|
| 43 |
+
def delitem():
|
| 44 |
+
del container[0]
|
| 45 |
+
|
| 46 |
+
self.check_mutable_error(delitem)
|
| 47 |
+
|
| 48 |
+
def delslice():
|
| 49 |
+
del container[0:3]
|
| 50 |
+
|
| 51 |
+
self.check_mutable_error(delslice)
|
| 52 |
+
|
| 53 |
+
mutable_methods = ("extend", "pop", "remove", "insert")
|
| 54 |
+
|
| 55 |
+
for meth in mutable_methods:
|
| 56 |
+
self.check_mutable_error(getattr(container, meth))
|
| 57 |
+
|
| 58 |
+
def test_slicing_maintains_type(self, container, lst):
|
| 59 |
+
result = container[1:2]
|
| 60 |
+
expected = lst[1:2]
|
| 61 |
+
self.check_result(result, expected)
|
| 62 |
+
|
| 63 |
+
def check_result(self, result, expected):
|
| 64 |
+
assert isinstance(result, FrozenList)
|
| 65 |
+
assert result == expected
|
| 66 |
+
|
| 67 |
+
def test_string_methods_dont_fail(self, container):
|
| 68 |
+
repr(container)
|
| 69 |
+
str(container)
|
| 70 |
+
bytes(container)
|
| 71 |
+
|
| 72 |
+
def test_tricky_container(self, unicode_container):
|
| 73 |
+
repr(unicode_container)
|
| 74 |
+
str(unicode_container)
|
| 75 |
+
|
| 76 |
+
def test_add(self, container, lst):
|
| 77 |
+
result = container + (1, 2, 3)
|
| 78 |
+
expected = FrozenList(lst + [1, 2, 3])
|
| 79 |
+
self.check_result(result, expected)
|
| 80 |
+
|
| 81 |
+
result = (1, 2, 3) + container
|
| 82 |
+
expected = FrozenList([1, 2, 3] + lst)
|
| 83 |
+
self.check_result(result, expected)
|
| 84 |
+
|
| 85 |
+
def test_iadd(self, container, lst):
|
| 86 |
+
q = r = container
|
| 87 |
+
|
| 88 |
+
q += [5]
|
| 89 |
+
self.check_result(q, lst + [5])
|
| 90 |
+
|
| 91 |
+
# Other shouldn't be mutated.
|
| 92 |
+
self.check_result(r, lst)
|
| 93 |
+
|
| 94 |
+
def test_union(self, container, lst):
|
| 95 |
+
result = container.union((1, 2, 3))
|
| 96 |
+
expected = FrozenList(lst + [1, 2, 3])
|
| 97 |
+
self.check_result(result, expected)
|
| 98 |
+
|
| 99 |
+
def test_difference(self, container):
|
| 100 |
+
result = container.difference([2])
|
| 101 |
+
expected = FrozenList([1, 3, 4, 5])
|
| 102 |
+
self.check_result(result, expected)
|
| 103 |
+
|
| 104 |
+
def test_difference_dupe(self):
|
| 105 |
+
result = FrozenList([1, 2, 3, 2]).difference([2])
|
| 106 |
+
expected = FrozenList([1, 3])
|
| 107 |
+
self.check_result(result, expected)
|
| 108 |
+
|
| 109 |
+
def test_tricky_container_to_bytes_raises(self, unicode_container):
|
| 110 |
+
# GH 26447
|
| 111 |
+
msg = "^'str' object cannot be interpreted as an integer$"
|
| 112 |
+
with pytest.raises(TypeError, match=msg):
|
| 113 |
+
bytes(unicode_container)
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/test_index_new.py
ADDED
|
@@ -0,0 +1,432 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests for the Index constructor conducting inference.
|
| 3 |
+
"""
|
| 4 |
+
from datetime import (
|
| 5 |
+
datetime,
|
| 6 |
+
timedelta,
|
| 7 |
+
timezone,
|
| 8 |
+
)
|
| 9 |
+
from decimal import Decimal
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
import pytest
|
| 13 |
+
|
| 14 |
+
from pandas._libs.tslibs.timezones import maybe_get_tz
|
| 15 |
+
|
| 16 |
+
from pandas import (
|
| 17 |
+
NA,
|
| 18 |
+
Categorical,
|
| 19 |
+
CategoricalIndex,
|
| 20 |
+
DatetimeIndex,
|
| 21 |
+
Index,
|
| 22 |
+
IntervalIndex,
|
| 23 |
+
MultiIndex,
|
| 24 |
+
NaT,
|
| 25 |
+
PeriodIndex,
|
| 26 |
+
Series,
|
| 27 |
+
TimedeltaIndex,
|
| 28 |
+
Timestamp,
|
| 29 |
+
array,
|
| 30 |
+
date_range,
|
| 31 |
+
period_range,
|
| 32 |
+
timedelta_range,
|
| 33 |
+
)
|
| 34 |
+
import pandas._testing as tm
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class TestIndexConstructorInference:
|
| 38 |
+
def test_object_all_bools(self):
|
| 39 |
+
# GH#49594 match Series behavior on ndarray[object] of all bools
|
| 40 |
+
arr = np.array([True, False], dtype=object)
|
| 41 |
+
res = Index(arr)
|
| 42 |
+
assert res.dtype == object
|
| 43 |
+
|
| 44 |
+
# since the point is matching Series behavior, let's double check
|
| 45 |
+
assert Series(arr).dtype == object
|
| 46 |
+
|
| 47 |
+
def test_object_all_complex(self):
|
| 48 |
+
# GH#49594 match Series behavior on ndarray[object] of all complex
|
| 49 |
+
arr = np.array([complex(1), complex(2)], dtype=object)
|
| 50 |
+
res = Index(arr)
|
| 51 |
+
assert res.dtype == object
|
| 52 |
+
|
| 53 |
+
# since the point is matching Series behavior, let's double check
|
| 54 |
+
assert Series(arr).dtype == object
|
| 55 |
+
|
| 56 |
+
@pytest.mark.parametrize("val", [NaT, None, np.nan, float("nan")])
|
| 57 |
+
def test_infer_nat(self, val):
|
| 58 |
+
# GH#49340 all NaT/None/nan and at least 1 NaT -> datetime64[ns],
|
| 59 |
+
# matching Series behavior
|
| 60 |
+
values = [NaT, val]
|
| 61 |
+
|
| 62 |
+
idx = Index(values)
|
| 63 |
+
assert idx.dtype == "datetime64[ns]" and idx.isna().all()
|
| 64 |
+
|
| 65 |
+
idx = Index(values[::-1])
|
| 66 |
+
assert idx.dtype == "datetime64[ns]" and idx.isna().all()
|
| 67 |
+
|
| 68 |
+
idx = Index(np.array(values, dtype=object))
|
| 69 |
+
assert idx.dtype == "datetime64[ns]" and idx.isna().all()
|
| 70 |
+
|
| 71 |
+
idx = Index(np.array(values, dtype=object)[::-1])
|
| 72 |
+
assert idx.dtype == "datetime64[ns]" and idx.isna().all()
|
| 73 |
+
|
| 74 |
+
@pytest.mark.parametrize("na_value", [None, np.nan])
|
| 75 |
+
@pytest.mark.parametrize("vtype", [list, tuple, iter])
|
| 76 |
+
def test_construction_list_tuples_nan(self, na_value, vtype):
|
| 77 |
+
# GH#18505 : valid tuples containing NaN
|
| 78 |
+
values = [(1, "two"), (3.0, na_value)]
|
| 79 |
+
result = Index(vtype(values))
|
| 80 |
+
expected = MultiIndex.from_tuples(values)
|
| 81 |
+
tm.assert_index_equal(result, expected)
|
| 82 |
+
|
| 83 |
+
@pytest.mark.parametrize(
|
| 84 |
+
"dtype",
|
| 85 |
+
[int, "int64", "int32", "int16", "int8", "uint64", "uint32", "uint16", "uint8"],
|
| 86 |
+
)
|
| 87 |
+
def test_constructor_int_dtype_float(self, dtype):
|
| 88 |
+
# GH#18400
|
| 89 |
+
expected = Index([0, 1, 2, 3], dtype=dtype)
|
| 90 |
+
result = Index([0.0, 1.0, 2.0, 3.0], dtype=dtype)
|
| 91 |
+
tm.assert_index_equal(result, expected)
|
| 92 |
+
|
| 93 |
+
@pytest.mark.parametrize("cast_index", [True, False])
|
| 94 |
+
@pytest.mark.parametrize(
|
| 95 |
+
"vals", [[True, False, True], np.array([True, False, True], dtype=bool)]
|
| 96 |
+
)
|
| 97 |
+
def test_constructor_dtypes_to_object(self, cast_index, vals):
|
| 98 |
+
if cast_index:
|
| 99 |
+
index = Index(vals, dtype=bool)
|
| 100 |
+
else:
|
| 101 |
+
index = Index(vals)
|
| 102 |
+
|
| 103 |
+
assert type(index) is Index
|
| 104 |
+
assert index.dtype == bool
|
| 105 |
+
|
| 106 |
+
def test_constructor_categorical_to_object(self):
|
| 107 |
+
# GH#32167 Categorical data and dtype=object should return object-dtype
|
| 108 |
+
ci = CategoricalIndex(range(5))
|
| 109 |
+
result = Index(ci, dtype=object)
|
| 110 |
+
assert not isinstance(result, CategoricalIndex)
|
| 111 |
+
|
| 112 |
+
def test_constructor_infer_periodindex(self):
|
| 113 |
+
xp = period_range("2012-1-1", freq="M", periods=3)
|
| 114 |
+
rs = Index(xp)
|
| 115 |
+
tm.assert_index_equal(rs, xp)
|
| 116 |
+
assert isinstance(rs, PeriodIndex)
|
| 117 |
+
|
| 118 |
+
def test_from_list_of_periods(self):
|
| 119 |
+
rng = period_range("1/1/2000", periods=20, freq="D")
|
| 120 |
+
periods = list(rng)
|
| 121 |
+
|
| 122 |
+
result = Index(periods)
|
| 123 |
+
assert isinstance(result, PeriodIndex)
|
| 124 |
+
|
| 125 |
+
@pytest.mark.parametrize("pos", [0, 1])
|
| 126 |
+
@pytest.mark.parametrize(
|
| 127 |
+
"klass,dtype,ctor",
|
| 128 |
+
[
|
| 129 |
+
(DatetimeIndex, "datetime64[ns]", np.datetime64("nat")),
|
| 130 |
+
(TimedeltaIndex, "timedelta64[ns]", np.timedelta64("nat")),
|
| 131 |
+
],
|
| 132 |
+
)
|
| 133 |
+
def test_constructor_infer_nat_dt_like(
|
| 134 |
+
self, pos, klass, dtype, ctor, nulls_fixture, request
|
| 135 |
+
):
|
| 136 |
+
if isinstance(nulls_fixture, Decimal):
|
| 137 |
+
# We dont cast these to datetime64/timedelta64
|
| 138 |
+
pytest.skip(
|
| 139 |
+
f"We don't cast {type(nulls_fixture).__name__} to "
|
| 140 |
+
"datetime64/timedelta64"
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
expected = klass([NaT, NaT])
|
| 144 |
+
assert expected.dtype == dtype
|
| 145 |
+
data = [ctor]
|
| 146 |
+
data.insert(pos, nulls_fixture)
|
| 147 |
+
|
| 148 |
+
warn = None
|
| 149 |
+
if nulls_fixture is NA:
|
| 150 |
+
expected = Index([NA, NaT])
|
| 151 |
+
mark = pytest.mark.xfail(reason="Broken with np.NaT ctor; see GH 31884")
|
| 152 |
+
request.applymarker(mark)
|
| 153 |
+
# GH#35942 numpy will emit a DeprecationWarning within the
|
| 154 |
+
# assert_index_equal calls. Since we can't do anything
|
| 155 |
+
# about it until GH#31884 is fixed, we suppress that warning.
|
| 156 |
+
warn = DeprecationWarning
|
| 157 |
+
|
| 158 |
+
result = Index(data)
|
| 159 |
+
|
| 160 |
+
with tm.assert_produces_warning(warn):
|
| 161 |
+
tm.assert_index_equal(result, expected)
|
| 162 |
+
|
| 163 |
+
result = Index(np.array(data, dtype=object))
|
| 164 |
+
|
| 165 |
+
with tm.assert_produces_warning(warn):
|
| 166 |
+
tm.assert_index_equal(result, expected)
|
| 167 |
+
|
| 168 |
+
@pytest.mark.parametrize("swap_objs", [True, False])
|
| 169 |
+
def test_constructor_mixed_nat_objs_infers_object(self, swap_objs):
|
| 170 |
+
# mixed np.datetime64/timedelta64 nat results in object
|
| 171 |
+
data = [np.datetime64("nat"), np.timedelta64("nat")]
|
| 172 |
+
if swap_objs:
|
| 173 |
+
data = data[::-1]
|
| 174 |
+
|
| 175 |
+
expected = Index(data, dtype=object)
|
| 176 |
+
tm.assert_index_equal(Index(data), expected)
|
| 177 |
+
tm.assert_index_equal(Index(np.array(data, dtype=object)), expected)
|
| 178 |
+
|
| 179 |
+
@pytest.mark.parametrize("swap_objs", [True, False])
|
| 180 |
+
def test_constructor_datetime_and_datetime64(self, swap_objs):
|
| 181 |
+
data = [Timestamp(2021, 6, 8, 9, 42), np.datetime64("now")]
|
| 182 |
+
if swap_objs:
|
| 183 |
+
data = data[::-1]
|
| 184 |
+
expected = DatetimeIndex(data)
|
| 185 |
+
|
| 186 |
+
tm.assert_index_equal(Index(data), expected)
|
| 187 |
+
tm.assert_index_equal(Index(np.array(data, dtype=object)), expected)
|
| 188 |
+
|
| 189 |
+
def test_constructor_datetimes_mixed_tzs(self):
|
| 190 |
+
# https://github.com/pandas-dev/pandas/pull/55793/files#r1383719998
|
| 191 |
+
tz = maybe_get_tz("US/Central")
|
| 192 |
+
dt1 = datetime(2020, 1, 1, tzinfo=tz)
|
| 193 |
+
dt2 = datetime(2020, 1, 1, tzinfo=timezone.utc)
|
| 194 |
+
result = Index([dt1, dt2])
|
| 195 |
+
expected = Index([dt1, dt2], dtype=object)
|
| 196 |
+
tm.assert_index_equal(result, expected)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
class TestDtypeEnforced:
|
| 200 |
+
# check we don't silently ignore the dtype keyword
|
| 201 |
+
|
| 202 |
+
def test_constructor_object_dtype_with_ea_data(self, any_numeric_ea_dtype):
|
| 203 |
+
# GH#45206
|
| 204 |
+
arr = array([0], dtype=any_numeric_ea_dtype)
|
| 205 |
+
|
| 206 |
+
idx = Index(arr, dtype=object)
|
| 207 |
+
assert idx.dtype == object
|
| 208 |
+
|
| 209 |
+
@pytest.mark.parametrize("dtype", [object, "float64", "uint64", "category"])
|
| 210 |
+
def test_constructor_range_values_mismatched_dtype(self, dtype):
|
| 211 |
+
rng = Index(range(5))
|
| 212 |
+
|
| 213 |
+
result = Index(rng, dtype=dtype)
|
| 214 |
+
assert result.dtype == dtype
|
| 215 |
+
|
| 216 |
+
result = Index(range(5), dtype=dtype)
|
| 217 |
+
assert result.dtype == dtype
|
| 218 |
+
|
| 219 |
+
@pytest.mark.parametrize("dtype", [object, "float64", "uint64", "category"])
|
| 220 |
+
def test_constructor_categorical_values_mismatched_non_ea_dtype(self, dtype):
|
| 221 |
+
cat = Categorical([1, 2, 3])
|
| 222 |
+
|
| 223 |
+
result = Index(cat, dtype=dtype)
|
| 224 |
+
assert result.dtype == dtype
|
| 225 |
+
|
| 226 |
+
def test_constructor_categorical_values_mismatched_dtype(self):
|
| 227 |
+
dti = date_range("2016-01-01", periods=3)
|
| 228 |
+
cat = Categorical(dti)
|
| 229 |
+
result = Index(cat, dti.dtype)
|
| 230 |
+
tm.assert_index_equal(result, dti)
|
| 231 |
+
|
| 232 |
+
dti2 = dti.tz_localize("Asia/Tokyo")
|
| 233 |
+
cat2 = Categorical(dti2)
|
| 234 |
+
result = Index(cat2, dti2.dtype)
|
| 235 |
+
tm.assert_index_equal(result, dti2)
|
| 236 |
+
|
| 237 |
+
ii = IntervalIndex.from_breaks(range(5))
|
| 238 |
+
cat3 = Categorical(ii)
|
| 239 |
+
result = Index(cat3, dtype=ii.dtype)
|
| 240 |
+
tm.assert_index_equal(result, ii)
|
| 241 |
+
|
| 242 |
+
def test_constructor_ea_values_mismatched_categorical_dtype(self):
|
| 243 |
+
dti = date_range("2016-01-01", periods=3)
|
| 244 |
+
result = Index(dti, dtype="category")
|
| 245 |
+
expected = CategoricalIndex(dti)
|
| 246 |
+
tm.assert_index_equal(result, expected)
|
| 247 |
+
|
| 248 |
+
dti2 = date_range("2016-01-01", periods=3, tz="US/Pacific")
|
| 249 |
+
result = Index(dti2, dtype="category")
|
| 250 |
+
expected = CategoricalIndex(dti2)
|
| 251 |
+
tm.assert_index_equal(result, expected)
|
| 252 |
+
|
| 253 |
+
def test_constructor_period_values_mismatched_dtype(self):
|
| 254 |
+
pi = period_range("2016-01-01", periods=3, freq="D")
|
| 255 |
+
result = Index(pi, dtype="category")
|
| 256 |
+
expected = CategoricalIndex(pi)
|
| 257 |
+
tm.assert_index_equal(result, expected)
|
| 258 |
+
|
| 259 |
+
def test_constructor_timedelta64_values_mismatched_dtype(self):
|
| 260 |
+
# check we don't silently ignore the dtype keyword
|
| 261 |
+
tdi = timedelta_range("4 Days", periods=5)
|
| 262 |
+
result = Index(tdi, dtype="category")
|
| 263 |
+
expected = CategoricalIndex(tdi)
|
| 264 |
+
tm.assert_index_equal(result, expected)
|
| 265 |
+
|
| 266 |
+
def test_constructor_interval_values_mismatched_dtype(self):
|
| 267 |
+
dti = date_range("2016-01-01", periods=3)
|
| 268 |
+
ii = IntervalIndex.from_breaks(dti)
|
| 269 |
+
result = Index(ii, dtype="category")
|
| 270 |
+
expected = CategoricalIndex(ii)
|
| 271 |
+
tm.assert_index_equal(result, expected)
|
| 272 |
+
|
| 273 |
+
def test_constructor_datetime64_values_mismatched_period_dtype(self):
|
| 274 |
+
dti = date_range("2016-01-01", periods=3)
|
| 275 |
+
result = Index(dti, dtype="Period[D]")
|
| 276 |
+
expected = dti.to_period("D")
|
| 277 |
+
tm.assert_index_equal(result, expected)
|
| 278 |
+
|
| 279 |
+
@pytest.mark.parametrize("dtype", ["int64", "uint64"])
|
| 280 |
+
def test_constructor_int_dtype_nan_raises(self, dtype):
|
| 281 |
+
# see GH#15187
|
| 282 |
+
data = [np.nan]
|
| 283 |
+
msg = "cannot convert"
|
| 284 |
+
with pytest.raises(ValueError, match=msg):
|
| 285 |
+
Index(data, dtype=dtype)
|
| 286 |
+
|
| 287 |
+
@pytest.mark.parametrize(
|
| 288 |
+
"vals",
|
| 289 |
+
[
|
| 290 |
+
[1, 2, 3],
|
| 291 |
+
np.array([1, 2, 3]),
|
| 292 |
+
np.array([1, 2, 3], dtype=int),
|
| 293 |
+
# below should coerce
|
| 294 |
+
[1.0, 2.0, 3.0],
|
| 295 |
+
np.array([1.0, 2.0, 3.0], dtype=float),
|
| 296 |
+
],
|
| 297 |
+
)
|
| 298 |
+
def test_constructor_dtypes_to_int(self, vals, any_int_numpy_dtype):
|
| 299 |
+
dtype = any_int_numpy_dtype
|
| 300 |
+
index = Index(vals, dtype=dtype)
|
| 301 |
+
assert index.dtype == dtype
|
| 302 |
+
|
| 303 |
+
@pytest.mark.parametrize(
|
| 304 |
+
"vals",
|
| 305 |
+
[
|
| 306 |
+
[1, 2, 3],
|
| 307 |
+
[1.0, 2.0, 3.0],
|
| 308 |
+
np.array([1.0, 2.0, 3.0]),
|
| 309 |
+
np.array([1, 2, 3], dtype=int),
|
| 310 |
+
np.array([1.0, 2.0, 3.0], dtype=float),
|
| 311 |
+
],
|
| 312 |
+
)
|
| 313 |
+
def test_constructor_dtypes_to_float(self, vals, float_numpy_dtype):
|
| 314 |
+
dtype = float_numpy_dtype
|
| 315 |
+
index = Index(vals, dtype=dtype)
|
| 316 |
+
assert index.dtype == dtype
|
| 317 |
+
|
| 318 |
+
@pytest.mark.parametrize(
|
| 319 |
+
"vals",
|
| 320 |
+
[
|
| 321 |
+
[1, 2, 3],
|
| 322 |
+
np.array([1, 2, 3], dtype=int),
|
| 323 |
+
np.array(["2011-01-01", "2011-01-02"], dtype="datetime64[ns]"),
|
| 324 |
+
[datetime(2011, 1, 1), datetime(2011, 1, 2)],
|
| 325 |
+
],
|
| 326 |
+
)
|
| 327 |
+
def test_constructor_dtypes_to_categorical(self, vals):
|
| 328 |
+
index = Index(vals, dtype="category")
|
| 329 |
+
assert isinstance(index, CategoricalIndex)
|
| 330 |
+
|
| 331 |
+
@pytest.mark.parametrize("cast_index", [True, False])
|
| 332 |
+
@pytest.mark.parametrize(
|
| 333 |
+
"vals",
|
| 334 |
+
[
|
| 335 |
+
Index(np.array([np.datetime64("2011-01-01"), np.datetime64("2011-01-02")])),
|
| 336 |
+
Index([datetime(2011, 1, 1), datetime(2011, 1, 2)]),
|
| 337 |
+
],
|
| 338 |
+
)
|
| 339 |
+
def test_constructor_dtypes_to_datetime(self, cast_index, vals):
|
| 340 |
+
if cast_index:
|
| 341 |
+
index = Index(vals, dtype=object)
|
| 342 |
+
assert isinstance(index, Index)
|
| 343 |
+
assert index.dtype == object
|
| 344 |
+
else:
|
| 345 |
+
index = Index(vals)
|
| 346 |
+
assert isinstance(index, DatetimeIndex)
|
| 347 |
+
|
| 348 |
+
@pytest.mark.parametrize("cast_index", [True, False])
|
| 349 |
+
@pytest.mark.parametrize(
|
| 350 |
+
"vals",
|
| 351 |
+
[
|
| 352 |
+
np.array([np.timedelta64(1, "D"), np.timedelta64(1, "D")]),
|
| 353 |
+
[timedelta(1), timedelta(1)],
|
| 354 |
+
],
|
| 355 |
+
)
|
| 356 |
+
def test_constructor_dtypes_to_timedelta(self, cast_index, vals):
|
| 357 |
+
if cast_index:
|
| 358 |
+
index = Index(vals, dtype=object)
|
| 359 |
+
assert isinstance(index, Index)
|
| 360 |
+
assert index.dtype == object
|
| 361 |
+
else:
|
| 362 |
+
index = Index(vals)
|
| 363 |
+
assert isinstance(index, TimedeltaIndex)
|
| 364 |
+
|
| 365 |
+
def test_pass_timedeltaindex_to_index(self):
|
| 366 |
+
rng = timedelta_range("1 days", "10 days")
|
| 367 |
+
idx = Index(rng, dtype=object)
|
| 368 |
+
|
| 369 |
+
expected = Index(rng.to_pytimedelta(), dtype=object)
|
| 370 |
+
|
| 371 |
+
tm.assert_numpy_array_equal(idx.values, expected.values)
|
| 372 |
+
|
| 373 |
+
def test_pass_datetimeindex_to_index(self):
|
| 374 |
+
# GH#1396
|
| 375 |
+
rng = date_range("1/1/2000", "3/1/2000")
|
| 376 |
+
idx = Index(rng, dtype=object)
|
| 377 |
+
|
| 378 |
+
expected = Index(rng.to_pydatetime(), dtype=object)
|
| 379 |
+
|
| 380 |
+
tm.assert_numpy_array_equal(idx.values, expected.values)
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
class TestIndexConstructorUnwrapping:
|
| 384 |
+
# Test passing different arraylike values to pd.Index
|
| 385 |
+
|
| 386 |
+
@pytest.mark.parametrize("klass", [Index, DatetimeIndex])
|
| 387 |
+
def test_constructor_from_series_dt64(self, klass):
|
| 388 |
+
stamps = [Timestamp("20110101"), Timestamp("20120101"), Timestamp("20130101")]
|
| 389 |
+
expected = DatetimeIndex(stamps)
|
| 390 |
+
ser = Series(stamps)
|
| 391 |
+
result = klass(ser)
|
| 392 |
+
tm.assert_index_equal(result, expected)
|
| 393 |
+
|
| 394 |
+
def test_constructor_no_pandas_array(self):
|
| 395 |
+
ser = Series([1, 2, 3])
|
| 396 |
+
result = Index(ser.array)
|
| 397 |
+
expected = Index([1, 2, 3])
|
| 398 |
+
tm.assert_index_equal(result, expected)
|
| 399 |
+
|
| 400 |
+
@pytest.mark.parametrize(
|
| 401 |
+
"array",
|
| 402 |
+
[
|
| 403 |
+
np.arange(5),
|
| 404 |
+
np.array(["a", "b", "c"]),
|
| 405 |
+
date_range("2000-01-01", periods=3).values,
|
| 406 |
+
],
|
| 407 |
+
)
|
| 408 |
+
def test_constructor_ndarray_like(self, array):
|
| 409 |
+
# GH#5460#issuecomment-44474502
|
| 410 |
+
# it should be possible to convert any object that satisfies the numpy
|
| 411 |
+
# ndarray interface directly into an Index
|
| 412 |
+
class ArrayLike:
|
| 413 |
+
def __init__(self, array) -> None:
|
| 414 |
+
self.array = array
|
| 415 |
+
|
| 416 |
+
def __array__(self, dtype=None, copy=None) -> np.ndarray:
|
| 417 |
+
return self.array
|
| 418 |
+
|
| 419 |
+
expected = Index(array)
|
| 420 |
+
result = Index(ArrayLike(array))
|
| 421 |
+
tm.assert_index_equal(result, expected)
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
class TestIndexConstructionErrors:
|
| 425 |
+
def test_constructor_overflow_int64(self):
|
| 426 |
+
# see GH#15832
|
| 427 |
+
msg = (
|
| 428 |
+
"The elements provided in the data cannot "
|
| 429 |
+
"all be casted to the dtype int64"
|
| 430 |
+
)
|
| 431 |
+
with pytest.raises(OverflowError, match=msg):
|
| 432 |
+
Index([np.iinfo(np.uint64).max - 1], dtype="int64")
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/test_indexing.py
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
test_indexing tests the following Index methods:
|
| 3 |
+
__getitem__
|
| 4 |
+
get_loc
|
| 5 |
+
get_value
|
| 6 |
+
__contains__
|
| 7 |
+
take
|
| 8 |
+
where
|
| 9 |
+
get_indexer
|
| 10 |
+
get_indexer_for
|
| 11 |
+
slice_locs
|
| 12 |
+
asof_locs
|
| 13 |
+
|
| 14 |
+
The corresponding tests.indexes.[index_type].test_indexing files
|
| 15 |
+
contain tests for the corresponding methods specific to those Index subclasses.
|
| 16 |
+
"""
|
| 17 |
+
import numpy as np
|
| 18 |
+
import pytest
|
| 19 |
+
|
| 20 |
+
from pandas.errors import InvalidIndexError
|
| 21 |
+
|
| 22 |
+
from pandas.core.dtypes.common import (
|
| 23 |
+
is_float_dtype,
|
| 24 |
+
is_scalar,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
from pandas import (
|
| 28 |
+
NA,
|
| 29 |
+
DatetimeIndex,
|
| 30 |
+
Index,
|
| 31 |
+
IntervalIndex,
|
| 32 |
+
MultiIndex,
|
| 33 |
+
NaT,
|
| 34 |
+
PeriodIndex,
|
| 35 |
+
TimedeltaIndex,
|
| 36 |
+
)
|
| 37 |
+
import pandas._testing as tm
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class TestTake:
|
| 41 |
+
def test_take_invalid_kwargs(self, index):
|
| 42 |
+
indices = [1, 2]
|
| 43 |
+
|
| 44 |
+
msg = r"take\(\) got an unexpected keyword argument 'foo'"
|
| 45 |
+
with pytest.raises(TypeError, match=msg):
|
| 46 |
+
index.take(indices, foo=2)
|
| 47 |
+
|
| 48 |
+
msg = "the 'out' parameter is not supported"
|
| 49 |
+
with pytest.raises(ValueError, match=msg):
|
| 50 |
+
index.take(indices, out=indices)
|
| 51 |
+
|
| 52 |
+
msg = "the 'mode' parameter is not supported"
|
| 53 |
+
with pytest.raises(ValueError, match=msg):
|
| 54 |
+
index.take(indices, mode="clip")
|
| 55 |
+
|
| 56 |
+
def test_take(self, index):
|
| 57 |
+
indexer = [4, 3, 0, 2]
|
| 58 |
+
if len(index) < 5:
|
| 59 |
+
pytest.skip("Test doesn't make sense since not enough elements")
|
| 60 |
+
|
| 61 |
+
result = index.take(indexer)
|
| 62 |
+
expected = index[indexer]
|
| 63 |
+
assert result.equals(expected)
|
| 64 |
+
|
| 65 |
+
if not isinstance(index, (DatetimeIndex, PeriodIndex, TimedeltaIndex)):
|
| 66 |
+
# GH 10791
|
| 67 |
+
msg = r"'(.*Index)' object has no attribute 'freq'"
|
| 68 |
+
with pytest.raises(AttributeError, match=msg):
|
| 69 |
+
index.freq
|
| 70 |
+
|
| 71 |
+
def test_take_indexer_type(self):
|
| 72 |
+
# GH#42875
|
| 73 |
+
integer_index = Index([0, 1, 2, 3])
|
| 74 |
+
scalar_index = 1
|
| 75 |
+
msg = "Expected indices to be array-like"
|
| 76 |
+
with pytest.raises(TypeError, match=msg):
|
| 77 |
+
integer_index.take(scalar_index)
|
| 78 |
+
|
| 79 |
+
def test_take_minus1_without_fill(self, index):
|
| 80 |
+
# -1 does not get treated as NA unless allow_fill=True is passed
|
| 81 |
+
if len(index) == 0:
|
| 82 |
+
# Test is not applicable
|
| 83 |
+
pytest.skip("Test doesn't make sense for empty index")
|
| 84 |
+
|
| 85 |
+
result = index.take([0, 0, -1])
|
| 86 |
+
|
| 87 |
+
expected = index.take([0, 0, len(index) - 1])
|
| 88 |
+
tm.assert_index_equal(result, expected)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class TestContains:
|
| 92 |
+
@pytest.mark.parametrize(
|
| 93 |
+
"index,val",
|
| 94 |
+
[
|
| 95 |
+
(Index([0, 1, 2]), 2),
|
| 96 |
+
(Index([0, 1, "2"]), "2"),
|
| 97 |
+
(Index([0, 1, 2, np.inf, 4]), 4),
|
| 98 |
+
(Index([0, 1, 2, np.nan, 4]), 4),
|
| 99 |
+
(Index([0, 1, 2, np.inf]), np.inf),
|
| 100 |
+
(Index([0, 1, 2, np.nan]), np.nan),
|
| 101 |
+
],
|
| 102 |
+
)
|
| 103 |
+
def test_index_contains(self, index, val):
|
| 104 |
+
assert val in index
|
| 105 |
+
|
| 106 |
+
@pytest.mark.parametrize(
|
| 107 |
+
"index,val",
|
| 108 |
+
[
|
| 109 |
+
(Index([0, 1, 2]), "2"),
|
| 110 |
+
(Index([0, 1, "2"]), 2),
|
| 111 |
+
(Index([0, 1, 2, np.inf]), 4),
|
| 112 |
+
(Index([0, 1, 2, np.nan]), 4),
|
| 113 |
+
(Index([0, 1, 2, np.inf]), np.nan),
|
| 114 |
+
(Index([0, 1, 2, np.nan]), np.inf),
|
| 115 |
+
# Checking if np.inf in int64 Index should not cause an OverflowError
|
| 116 |
+
# Related to GH 16957
|
| 117 |
+
(Index([0, 1, 2], dtype=np.int64), np.inf),
|
| 118 |
+
(Index([0, 1, 2], dtype=np.int64), np.nan),
|
| 119 |
+
(Index([0, 1, 2], dtype=np.uint64), np.inf),
|
| 120 |
+
(Index([0, 1, 2], dtype=np.uint64), np.nan),
|
| 121 |
+
],
|
| 122 |
+
)
|
| 123 |
+
def test_index_not_contains(self, index, val):
|
| 124 |
+
assert val not in index
|
| 125 |
+
|
| 126 |
+
@pytest.mark.parametrize(
|
| 127 |
+
"index,val", [(Index([0, 1, "2"]), 0), (Index([0, 1, "2"]), "2")]
|
| 128 |
+
)
|
| 129 |
+
def test_mixed_index_contains(self, index, val):
|
| 130 |
+
# GH#19860
|
| 131 |
+
assert val in index
|
| 132 |
+
|
| 133 |
+
@pytest.mark.parametrize(
|
| 134 |
+
"index,val", [(Index([0, 1, "2"]), "1"), (Index([0, 1, "2"]), 2)]
|
| 135 |
+
)
|
| 136 |
+
def test_mixed_index_not_contains(self, index, val):
|
| 137 |
+
# GH#19860
|
| 138 |
+
assert val not in index
|
| 139 |
+
|
| 140 |
+
def test_contains_with_float_index(self, any_real_numpy_dtype):
|
| 141 |
+
# GH#22085
|
| 142 |
+
dtype = any_real_numpy_dtype
|
| 143 |
+
data = [0, 1, 2, 3] if not is_float_dtype(dtype) else [0.1, 1.1, 2.2, 3.3]
|
| 144 |
+
index = Index(data, dtype=dtype)
|
| 145 |
+
|
| 146 |
+
if not is_float_dtype(index.dtype):
|
| 147 |
+
assert 1.1 not in index
|
| 148 |
+
assert 1.0 in index
|
| 149 |
+
assert 1 in index
|
| 150 |
+
else:
|
| 151 |
+
assert 1.1 in index
|
| 152 |
+
assert 1.0 not in index
|
| 153 |
+
assert 1 not in index
|
| 154 |
+
|
| 155 |
+
def test_contains_requires_hashable_raises(self, index):
|
| 156 |
+
if isinstance(index, MultiIndex):
|
| 157 |
+
return # TODO: do we want this to raise?
|
| 158 |
+
|
| 159 |
+
msg = "unhashable type: 'list'"
|
| 160 |
+
with pytest.raises(TypeError, match=msg):
|
| 161 |
+
[] in index
|
| 162 |
+
|
| 163 |
+
msg = "|".join(
|
| 164 |
+
[
|
| 165 |
+
r"unhashable type: 'dict'",
|
| 166 |
+
r"must be real number, not dict",
|
| 167 |
+
r"an integer is required",
|
| 168 |
+
r"\{\}",
|
| 169 |
+
r"pandas\._libs\.interval\.IntervalTree' is not iterable",
|
| 170 |
+
]
|
| 171 |
+
)
|
| 172 |
+
with pytest.raises(TypeError, match=msg):
|
| 173 |
+
{} in index._engine
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class TestGetLoc:
|
| 177 |
+
def test_get_loc_non_hashable(self, index):
|
| 178 |
+
with pytest.raises(InvalidIndexError, match="[0, 1]"):
|
| 179 |
+
index.get_loc([0, 1])
|
| 180 |
+
|
| 181 |
+
def test_get_loc_non_scalar_hashable(self, index):
|
| 182 |
+
# GH52877
|
| 183 |
+
from enum import Enum
|
| 184 |
+
|
| 185 |
+
class E(Enum):
|
| 186 |
+
X1 = "x1"
|
| 187 |
+
|
| 188 |
+
assert not is_scalar(E.X1)
|
| 189 |
+
|
| 190 |
+
exc = KeyError
|
| 191 |
+
msg = "<E.X1: 'x1'>"
|
| 192 |
+
if isinstance(
|
| 193 |
+
index,
|
| 194 |
+
(
|
| 195 |
+
DatetimeIndex,
|
| 196 |
+
TimedeltaIndex,
|
| 197 |
+
PeriodIndex,
|
| 198 |
+
IntervalIndex,
|
| 199 |
+
),
|
| 200 |
+
):
|
| 201 |
+
# TODO: make these more consistent?
|
| 202 |
+
exc = InvalidIndexError
|
| 203 |
+
msg = "E.X1"
|
| 204 |
+
with pytest.raises(exc, match=msg):
|
| 205 |
+
index.get_loc(E.X1)
|
| 206 |
+
|
| 207 |
+
def test_get_loc_generator(self, index):
|
| 208 |
+
exc = KeyError
|
| 209 |
+
if isinstance(
|
| 210 |
+
index,
|
| 211 |
+
(
|
| 212 |
+
DatetimeIndex,
|
| 213 |
+
TimedeltaIndex,
|
| 214 |
+
PeriodIndex,
|
| 215 |
+
IntervalIndex,
|
| 216 |
+
MultiIndex,
|
| 217 |
+
),
|
| 218 |
+
):
|
| 219 |
+
# TODO: make these more consistent?
|
| 220 |
+
exc = InvalidIndexError
|
| 221 |
+
with pytest.raises(exc, match="generator object"):
|
| 222 |
+
# MultiIndex specifically checks for generator; others for scalar
|
| 223 |
+
index.get_loc(x for x in range(5))
|
| 224 |
+
|
| 225 |
+
def test_get_loc_masked_duplicated_na(self):
|
| 226 |
+
# GH#48411
|
| 227 |
+
idx = Index([1, 2, NA, NA], dtype="Int64")
|
| 228 |
+
result = idx.get_loc(NA)
|
| 229 |
+
expected = np.array([False, False, True, True])
|
| 230 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
class TestGetIndexer:
|
| 234 |
+
def test_get_indexer_base(self, index):
|
| 235 |
+
if index._index_as_unique:
|
| 236 |
+
expected = np.arange(index.size, dtype=np.intp)
|
| 237 |
+
actual = index.get_indexer(index)
|
| 238 |
+
tm.assert_numpy_array_equal(expected, actual)
|
| 239 |
+
else:
|
| 240 |
+
msg = "Reindexing only valid with uniquely valued Index objects"
|
| 241 |
+
with pytest.raises(InvalidIndexError, match=msg):
|
| 242 |
+
index.get_indexer(index)
|
| 243 |
+
|
| 244 |
+
with pytest.raises(ValueError, match="Invalid fill method"):
|
| 245 |
+
index.get_indexer(index, method="invalid")
|
| 246 |
+
|
| 247 |
+
def test_get_indexer_consistency(self, index):
|
| 248 |
+
# See GH#16819
|
| 249 |
+
|
| 250 |
+
if index._index_as_unique:
|
| 251 |
+
indexer = index.get_indexer(index[0:2])
|
| 252 |
+
assert isinstance(indexer, np.ndarray)
|
| 253 |
+
assert indexer.dtype == np.intp
|
| 254 |
+
else:
|
| 255 |
+
msg = "Reindexing only valid with uniquely valued Index objects"
|
| 256 |
+
with pytest.raises(InvalidIndexError, match=msg):
|
| 257 |
+
index.get_indexer(index[0:2])
|
| 258 |
+
|
| 259 |
+
indexer, _ = index.get_indexer_non_unique(index[0:2])
|
| 260 |
+
assert isinstance(indexer, np.ndarray)
|
| 261 |
+
assert indexer.dtype == np.intp
|
| 262 |
+
|
| 263 |
+
def test_get_indexer_masked_duplicated_na(self):
|
| 264 |
+
# GH#48411
|
| 265 |
+
idx = Index([1, 2, NA, NA], dtype="Int64")
|
| 266 |
+
result = idx.get_indexer_for(Index([1, NA], dtype="Int64"))
|
| 267 |
+
expected = np.array([0, 2, 3], dtype=result.dtype)
|
| 268 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
class TestConvertSliceIndexer:
|
| 272 |
+
def test_convert_almost_null_slice(self, index):
|
| 273 |
+
# slice with None at both ends, but not step
|
| 274 |
+
|
| 275 |
+
key = slice(None, None, "foo")
|
| 276 |
+
|
| 277 |
+
if isinstance(index, IntervalIndex):
|
| 278 |
+
msg = "label-based slicing with step!=1 is not supported for IntervalIndex"
|
| 279 |
+
with pytest.raises(ValueError, match=msg):
|
| 280 |
+
index._convert_slice_indexer(key, "loc")
|
| 281 |
+
else:
|
| 282 |
+
msg = "'>=' not supported between instances of 'str' and 'int'"
|
| 283 |
+
with pytest.raises(TypeError, match=msg):
|
| 284 |
+
index._convert_slice_indexer(key, "loc")
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
class TestPutmask:
|
| 288 |
+
def test_putmask_with_wrong_mask(self, index):
|
| 289 |
+
# GH#18368
|
| 290 |
+
if not len(index):
|
| 291 |
+
pytest.skip("Test doesn't make sense for empty index")
|
| 292 |
+
|
| 293 |
+
fill = index[0]
|
| 294 |
+
|
| 295 |
+
msg = "putmask: mask and data must be the same size"
|
| 296 |
+
with pytest.raises(ValueError, match=msg):
|
| 297 |
+
index.putmask(np.ones(len(index) + 1, np.bool_), fill)
|
| 298 |
+
|
| 299 |
+
with pytest.raises(ValueError, match=msg):
|
| 300 |
+
index.putmask(np.ones(len(index) - 1, np.bool_), fill)
|
| 301 |
+
|
| 302 |
+
with pytest.raises(ValueError, match=msg):
|
| 303 |
+
index.putmask("foo", fill)
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
@pytest.mark.parametrize(
|
| 307 |
+
"idx", [Index([1, 2, 3]), Index([0.1, 0.2, 0.3]), Index(["a", "b", "c"])]
|
| 308 |
+
)
|
| 309 |
+
def test_getitem_deprecated_float(idx):
|
| 310 |
+
# https://github.com/pandas-dev/pandas/issues/34191
|
| 311 |
+
|
| 312 |
+
msg = "Indexing with a float is no longer supported"
|
| 313 |
+
with pytest.raises(IndexError, match=msg):
|
| 314 |
+
idx[1.0]
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
@pytest.mark.parametrize(
|
| 318 |
+
"idx,target,expected",
|
| 319 |
+
[
|
| 320 |
+
([np.nan, "var1", np.nan], [np.nan], np.array([0, 2], dtype=np.intp)),
|
| 321 |
+
(
|
| 322 |
+
[np.nan, "var1", np.nan],
|
| 323 |
+
[np.nan, "var1"],
|
| 324 |
+
np.array([0, 2, 1], dtype=np.intp),
|
| 325 |
+
),
|
| 326 |
+
(
|
| 327 |
+
np.array([np.nan, "var1", np.nan], dtype=object),
|
| 328 |
+
[np.nan],
|
| 329 |
+
np.array([0, 2], dtype=np.intp),
|
| 330 |
+
),
|
| 331 |
+
(
|
| 332 |
+
DatetimeIndex(["2020-08-05", NaT, NaT]),
|
| 333 |
+
[NaT],
|
| 334 |
+
np.array([1, 2], dtype=np.intp),
|
| 335 |
+
),
|
| 336 |
+
(["a", "b", "a", np.nan], [np.nan], np.array([3], dtype=np.intp)),
|
| 337 |
+
(
|
| 338 |
+
np.array(["b", np.nan, float("NaN"), "b"], dtype=object),
|
| 339 |
+
Index([np.nan], dtype=object),
|
| 340 |
+
np.array([1, 2], dtype=np.intp),
|
| 341 |
+
),
|
| 342 |
+
],
|
| 343 |
+
)
|
| 344 |
+
def test_get_indexer_non_unique_multiple_nans(idx, target, expected):
|
| 345 |
+
# GH 35392
|
| 346 |
+
axis = Index(idx)
|
| 347 |
+
actual = axis.get_indexer_for(target)
|
| 348 |
+
tm.assert_numpy_array_equal(actual, expected)
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def test_get_indexer_non_unique_nans_in_object_dtype_target(nulls_fixture):
|
| 352 |
+
idx = Index([1.0, 2.0])
|
| 353 |
+
target = Index([1, nulls_fixture], dtype="object")
|
| 354 |
+
|
| 355 |
+
result_idx, result_missing = idx.get_indexer_non_unique(target)
|
| 356 |
+
tm.assert_numpy_array_equal(result_idx, np.array([0, -1], dtype=np.intp))
|
| 357 |
+
tm.assert_numpy_array_equal(result_missing, np.array([1], dtype=np.intp))
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/test_numpy_compat.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from pandas import (
|
| 5 |
+
CategoricalIndex,
|
| 6 |
+
DatetimeIndex,
|
| 7 |
+
Index,
|
| 8 |
+
PeriodIndex,
|
| 9 |
+
TimedeltaIndex,
|
| 10 |
+
isna,
|
| 11 |
+
)
|
| 12 |
+
import pandas._testing as tm
|
| 13 |
+
from pandas.api.types import (
|
| 14 |
+
is_complex_dtype,
|
| 15 |
+
is_numeric_dtype,
|
| 16 |
+
)
|
| 17 |
+
from pandas.core.arrays import BooleanArray
|
| 18 |
+
from pandas.core.indexes.datetimelike import DatetimeIndexOpsMixin
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def test_numpy_ufuncs_out(index):
|
| 22 |
+
result = index == index
|
| 23 |
+
|
| 24 |
+
out = np.empty(index.shape, dtype=bool)
|
| 25 |
+
np.equal(index, index, out=out)
|
| 26 |
+
tm.assert_numpy_array_equal(out, result)
|
| 27 |
+
|
| 28 |
+
if not index._is_multi:
|
| 29 |
+
# same thing on the ExtensionArray
|
| 30 |
+
out = np.empty(index.shape, dtype=bool)
|
| 31 |
+
np.equal(index.array, index.array, out=out)
|
| 32 |
+
tm.assert_numpy_array_equal(out, result)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@pytest.mark.parametrize(
|
| 36 |
+
"func",
|
| 37 |
+
[
|
| 38 |
+
np.exp,
|
| 39 |
+
np.exp2,
|
| 40 |
+
np.expm1,
|
| 41 |
+
np.log,
|
| 42 |
+
np.log2,
|
| 43 |
+
np.log10,
|
| 44 |
+
np.log1p,
|
| 45 |
+
np.sqrt,
|
| 46 |
+
np.sin,
|
| 47 |
+
np.cos,
|
| 48 |
+
np.tan,
|
| 49 |
+
np.arcsin,
|
| 50 |
+
np.arccos,
|
| 51 |
+
np.arctan,
|
| 52 |
+
np.sinh,
|
| 53 |
+
np.cosh,
|
| 54 |
+
np.tanh,
|
| 55 |
+
np.arcsinh,
|
| 56 |
+
np.arccosh,
|
| 57 |
+
np.arctanh,
|
| 58 |
+
np.deg2rad,
|
| 59 |
+
np.rad2deg,
|
| 60 |
+
],
|
| 61 |
+
ids=lambda x: x.__name__,
|
| 62 |
+
)
|
| 63 |
+
def test_numpy_ufuncs_basic(index, func):
|
| 64 |
+
# test ufuncs of numpy, see:
|
| 65 |
+
# https://numpy.org/doc/stable/reference/ufuncs.html
|
| 66 |
+
|
| 67 |
+
if isinstance(index, DatetimeIndexOpsMixin):
|
| 68 |
+
with tm.external_error_raised((TypeError, AttributeError)):
|
| 69 |
+
with np.errstate(all="ignore"):
|
| 70 |
+
func(index)
|
| 71 |
+
elif is_numeric_dtype(index) and not (
|
| 72 |
+
is_complex_dtype(index) and func in [np.deg2rad, np.rad2deg]
|
| 73 |
+
):
|
| 74 |
+
# coerces to float (e.g. np.sin)
|
| 75 |
+
with np.errstate(all="ignore"):
|
| 76 |
+
result = func(index)
|
| 77 |
+
arr_result = func(index.values)
|
| 78 |
+
if arr_result.dtype == np.float16:
|
| 79 |
+
arr_result = arr_result.astype(np.float32)
|
| 80 |
+
exp = Index(arr_result, name=index.name)
|
| 81 |
+
|
| 82 |
+
tm.assert_index_equal(result, exp)
|
| 83 |
+
if isinstance(index.dtype, np.dtype) and is_numeric_dtype(index):
|
| 84 |
+
if is_complex_dtype(index):
|
| 85 |
+
assert result.dtype == index.dtype
|
| 86 |
+
elif index.dtype in ["bool", "int8", "uint8"]:
|
| 87 |
+
assert result.dtype in ["float16", "float32"]
|
| 88 |
+
elif index.dtype in ["int16", "uint16", "float32"]:
|
| 89 |
+
assert result.dtype == "float32"
|
| 90 |
+
else:
|
| 91 |
+
assert result.dtype == "float64"
|
| 92 |
+
else:
|
| 93 |
+
# e.g. np.exp with Int64 -> Float64
|
| 94 |
+
assert type(result) is Index
|
| 95 |
+
# raise AttributeError or TypeError
|
| 96 |
+
elif len(index) == 0:
|
| 97 |
+
pass
|
| 98 |
+
else:
|
| 99 |
+
with tm.external_error_raised((TypeError, AttributeError)):
|
| 100 |
+
with np.errstate(all="ignore"):
|
| 101 |
+
func(index)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
@pytest.mark.parametrize(
|
| 105 |
+
"func", [np.isfinite, np.isinf, np.isnan, np.signbit], ids=lambda x: x.__name__
|
| 106 |
+
)
|
| 107 |
+
def test_numpy_ufuncs_other(index, func):
|
| 108 |
+
# test ufuncs of numpy, see:
|
| 109 |
+
# https://numpy.org/doc/stable/reference/ufuncs.html
|
| 110 |
+
if isinstance(index, (DatetimeIndex, TimedeltaIndex)):
|
| 111 |
+
if func in (np.isfinite, np.isinf, np.isnan):
|
| 112 |
+
# numpy 1.18 changed isinf and isnan to not raise on dt64/td64
|
| 113 |
+
result = func(index)
|
| 114 |
+
assert isinstance(result, np.ndarray)
|
| 115 |
+
|
| 116 |
+
out = np.empty(index.shape, dtype=bool)
|
| 117 |
+
func(index, out=out)
|
| 118 |
+
tm.assert_numpy_array_equal(out, result)
|
| 119 |
+
else:
|
| 120 |
+
with tm.external_error_raised(TypeError):
|
| 121 |
+
func(index)
|
| 122 |
+
|
| 123 |
+
elif isinstance(index, PeriodIndex):
|
| 124 |
+
with tm.external_error_raised(TypeError):
|
| 125 |
+
func(index)
|
| 126 |
+
|
| 127 |
+
elif is_numeric_dtype(index) and not (
|
| 128 |
+
is_complex_dtype(index) and func is np.signbit
|
| 129 |
+
):
|
| 130 |
+
# Results in bool array
|
| 131 |
+
result = func(index)
|
| 132 |
+
if not isinstance(index.dtype, np.dtype):
|
| 133 |
+
# e.g. Int64 we expect to get BooleanArray back
|
| 134 |
+
assert isinstance(result, BooleanArray)
|
| 135 |
+
else:
|
| 136 |
+
assert isinstance(result, np.ndarray)
|
| 137 |
+
|
| 138 |
+
out = np.empty(index.shape, dtype=bool)
|
| 139 |
+
func(index, out=out)
|
| 140 |
+
|
| 141 |
+
if not isinstance(index.dtype, np.dtype):
|
| 142 |
+
tm.assert_numpy_array_equal(out, result._data)
|
| 143 |
+
else:
|
| 144 |
+
tm.assert_numpy_array_equal(out, result)
|
| 145 |
+
|
| 146 |
+
elif len(index) == 0:
|
| 147 |
+
pass
|
| 148 |
+
else:
|
| 149 |
+
with tm.external_error_raised(TypeError):
|
| 150 |
+
func(index)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
@pytest.mark.parametrize("func", [np.maximum, np.minimum])
|
| 154 |
+
def test_numpy_ufuncs_reductions(index, func, request):
|
| 155 |
+
# TODO: overlap with tests.series.test_ufunc.test_reductions
|
| 156 |
+
if len(index) == 0:
|
| 157 |
+
pytest.skip("Test doesn't make sense for empty index.")
|
| 158 |
+
|
| 159 |
+
if isinstance(index, CategoricalIndex) and index.dtype.ordered is False:
|
| 160 |
+
with pytest.raises(TypeError, match="is not ordered for"):
|
| 161 |
+
func.reduce(index)
|
| 162 |
+
return
|
| 163 |
+
else:
|
| 164 |
+
result = func.reduce(index)
|
| 165 |
+
|
| 166 |
+
if func is np.maximum:
|
| 167 |
+
expected = index.max(skipna=False)
|
| 168 |
+
else:
|
| 169 |
+
expected = index.min(skipna=False)
|
| 170 |
+
# TODO: do we have cases both with and without NAs?
|
| 171 |
+
|
| 172 |
+
assert type(result) is type(expected)
|
| 173 |
+
if isna(result):
|
| 174 |
+
assert isna(expected)
|
| 175 |
+
else:
|
| 176 |
+
assert result == expected
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
@pytest.mark.parametrize("func", [np.bitwise_and, np.bitwise_or, np.bitwise_xor])
|
| 180 |
+
def test_numpy_ufuncs_bitwise(func):
|
| 181 |
+
# https://github.com/pandas-dev/pandas/issues/46769
|
| 182 |
+
idx1 = Index([1, 2, 3, 4], dtype="int64")
|
| 183 |
+
idx2 = Index([3, 4, 5, 6], dtype="int64")
|
| 184 |
+
|
| 185 |
+
with tm.assert_produces_warning(None):
|
| 186 |
+
result = func(idx1, idx2)
|
| 187 |
+
|
| 188 |
+
expected = Index(func(idx1.values, idx2.values))
|
| 189 |
+
tm.assert_index_equal(result, expected)
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/test_old_base.py
ADDED
|
@@ -0,0 +1,1061 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
+
from pandas._config import using_pyarrow_string_dtype
|
| 10 |
+
|
| 11 |
+
from pandas._libs.tslibs import Timestamp
|
| 12 |
+
|
| 13 |
+
from pandas.core.dtypes.common import (
|
| 14 |
+
is_integer_dtype,
|
| 15 |
+
is_numeric_dtype,
|
| 16 |
+
)
|
| 17 |
+
from pandas.core.dtypes.dtypes import CategoricalDtype
|
| 18 |
+
|
| 19 |
+
import pandas as pd
|
| 20 |
+
from pandas import (
|
| 21 |
+
CategoricalIndex,
|
| 22 |
+
DatetimeIndex,
|
| 23 |
+
DatetimeTZDtype,
|
| 24 |
+
Index,
|
| 25 |
+
IntervalIndex,
|
| 26 |
+
MultiIndex,
|
| 27 |
+
PeriodIndex,
|
| 28 |
+
RangeIndex,
|
| 29 |
+
Series,
|
| 30 |
+
TimedeltaIndex,
|
| 31 |
+
isna,
|
| 32 |
+
period_range,
|
| 33 |
+
)
|
| 34 |
+
import pandas._testing as tm
|
| 35 |
+
import pandas.core.algorithms as algos
|
| 36 |
+
from pandas.core.arrays import BaseMaskedArray
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class TestBase:
|
| 40 |
+
@pytest.fixture(
|
| 41 |
+
params=[
|
| 42 |
+
RangeIndex(start=0, stop=20, step=2),
|
| 43 |
+
Index(np.arange(5, dtype=np.float64)),
|
| 44 |
+
Index(np.arange(5, dtype=np.float32)),
|
| 45 |
+
Index(np.arange(5, dtype=np.uint64)),
|
| 46 |
+
Index(range(0, 20, 2), dtype=np.int64),
|
| 47 |
+
Index(range(0, 20, 2), dtype=np.int32),
|
| 48 |
+
Index(range(0, 20, 2), dtype=np.int16),
|
| 49 |
+
Index(range(0, 20, 2), dtype=np.int8),
|
| 50 |
+
Index(list("abcde")),
|
| 51 |
+
Index([0, "a", 1, "b", 2, "c"]),
|
| 52 |
+
period_range("20130101", periods=5, freq="D"),
|
| 53 |
+
TimedeltaIndex(
|
| 54 |
+
[
|
| 55 |
+
"0 days 01:00:00",
|
| 56 |
+
"1 days 01:00:00",
|
| 57 |
+
"2 days 01:00:00",
|
| 58 |
+
"3 days 01:00:00",
|
| 59 |
+
"4 days 01:00:00",
|
| 60 |
+
],
|
| 61 |
+
dtype="timedelta64[ns]",
|
| 62 |
+
freq="D",
|
| 63 |
+
),
|
| 64 |
+
DatetimeIndex(
|
| 65 |
+
["2013-01-01", "2013-01-02", "2013-01-03", "2013-01-04", "2013-01-05"],
|
| 66 |
+
dtype="datetime64[ns]",
|
| 67 |
+
freq="D",
|
| 68 |
+
),
|
| 69 |
+
IntervalIndex.from_breaks(range(11), closed="right"),
|
| 70 |
+
]
|
| 71 |
+
)
|
| 72 |
+
def simple_index(self, request):
|
| 73 |
+
return request.param
|
| 74 |
+
|
| 75 |
+
def test_pickle_compat_construction(self, simple_index):
|
| 76 |
+
# need an object to create with
|
| 77 |
+
if isinstance(simple_index, RangeIndex):
|
| 78 |
+
pytest.skip("RangeIndex() is a valid constructor")
|
| 79 |
+
msg = "|".join(
|
| 80 |
+
[
|
| 81 |
+
r"Index\(\.\.\.\) must be called with a collection of some "
|
| 82 |
+
r"kind, None was passed",
|
| 83 |
+
r"DatetimeIndex\(\) must be called with a collection of some "
|
| 84 |
+
r"kind, None was passed",
|
| 85 |
+
r"TimedeltaIndex\(\) must be called with a collection of some "
|
| 86 |
+
r"kind, None was passed",
|
| 87 |
+
r"__new__\(\) missing 1 required positional argument: 'data'",
|
| 88 |
+
r"__new__\(\) takes at least 2 arguments \(1 given\)",
|
| 89 |
+
]
|
| 90 |
+
)
|
| 91 |
+
with pytest.raises(TypeError, match=msg):
|
| 92 |
+
type(simple_index)()
|
| 93 |
+
|
| 94 |
+
def test_shift(self, simple_index):
|
| 95 |
+
# GH8083 test the base class for shift
|
| 96 |
+
if isinstance(simple_index, (DatetimeIndex, TimedeltaIndex, PeriodIndex)):
|
| 97 |
+
pytest.skip("Tested in test_ops/test_arithmetic")
|
| 98 |
+
idx = simple_index
|
| 99 |
+
msg = (
|
| 100 |
+
f"This method is only implemented for DatetimeIndex, PeriodIndex and "
|
| 101 |
+
f"TimedeltaIndex; Got type {type(idx).__name__}"
|
| 102 |
+
)
|
| 103 |
+
with pytest.raises(NotImplementedError, match=msg):
|
| 104 |
+
idx.shift(1)
|
| 105 |
+
with pytest.raises(NotImplementedError, match=msg):
|
| 106 |
+
idx.shift(1, 2)
|
| 107 |
+
|
| 108 |
+
def test_constructor_name_unhashable(self, simple_index):
|
| 109 |
+
# GH#29069 check that name is hashable
|
| 110 |
+
# See also same-named test in tests.series.test_constructors
|
| 111 |
+
idx = simple_index
|
| 112 |
+
with pytest.raises(TypeError, match="Index.name must be a hashable type"):
|
| 113 |
+
type(idx)(idx, name=[])
|
| 114 |
+
|
| 115 |
+
def test_create_index_existing_name(self, simple_index):
|
| 116 |
+
# GH11193, when an existing index is passed, and a new name is not
|
| 117 |
+
# specified, the new index should inherit the previous object name
|
| 118 |
+
expected = simple_index.copy()
|
| 119 |
+
if not isinstance(expected, MultiIndex):
|
| 120 |
+
expected.name = "foo"
|
| 121 |
+
result = Index(expected)
|
| 122 |
+
tm.assert_index_equal(result, expected)
|
| 123 |
+
|
| 124 |
+
result = Index(expected, name="bar")
|
| 125 |
+
expected.name = "bar"
|
| 126 |
+
tm.assert_index_equal(result, expected)
|
| 127 |
+
else:
|
| 128 |
+
expected.names = ["foo", "bar"]
|
| 129 |
+
result = Index(expected)
|
| 130 |
+
tm.assert_index_equal(
|
| 131 |
+
result,
|
| 132 |
+
Index(
|
| 133 |
+
Index(
|
| 134 |
+
[
|
| 135 |
+
("foo", "one"),
|
| 136 |
+
("foo", "two"),
|
| 137 |
+
("bar", "one"),
|
| 138 |
+
("baz", "two"),
|
| 139 |
+
("qux", "one"),
|
| 140 |
+
("qux", "two"),
|
| 141 |
+
],
|
| 142 |
+
dtype="object",
|
| 143 |
+
),
|
| 144 |
+
names=["foo", "bar"],
|
| 145 |
+
),
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
result = Index(expected, names=["A", "B"])
|
| 149 |
+
tm.assert_index_equal(
|
| 150 |
+
result,
|
| 151 |
+
Index(
|
| 152 |
+
Index(
|
| 153 |
+
[
|
| 154 |
+
("foo", "one"),
|
| 155 |
+
("foo", "two"),
|
| 156 |
+
("bar", "one"),
|
| 157 |
+
("baz", "two"),
|
| 158 |
+
("qux", "one"),
|
| 159 |
+
("qux", "two"),
|
| 160 |
+
],
|
| 161 |
+
dtype="object",
|
| 162 |
+
),
|
| 163 |
+
names=["A", "B"],
|
| 164 |
+
),
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
def test_numeric_compat(self, simple_index):
|
| 168 |
+
idx = simple_index
|
| 169 |
+
# Check that this doesn't cover MultiIndex case, if/when it does,
|
| 170 |
+
# we can remove multi.test_compat.test_numeric_compat
|
| 171 |
+
assert not isinstance(idx, MultiIndex)
|
| 172 |
+
if type(idx) is Index:
|
| 173 |
+
pytest.skip("Not applicable for Index")
|
| 174 |
+
if is_numeric_dtype(simple_index.dtype) or isinstance(
|
| 175 |
+
simple_index, TimedeltaIndex
|
| 176 |
+
):
|
| 177 |
+
pytest.skip("Tested elsewhere.")
|
| 178 |
+
|
| 179 |
+
typ = type(idx._data).__name__
|
| 180 |
+
cls = type(idx).__name__
|
| 181 |
+
lmsg = "|".join(
|
| 182 |
+
[
|
| 183 |
+
rf"unsupported operand type\(s\) for \*: '{typ}' and 'int'",
|
| 184 |
+
"cannot perform (__mul__|__truediv__|__floordiv__) with "
|
| 185 |
+
f"this index type: ({cls}|{typ})",
|
| 186 |
+
]
|
| 187 |
+
)
|
| 188 |
+
with pytest.raises(TypeError, match=lmsg):
|
| 189 |
+
idx * 1
|
| 190 |
+
rmsg = "|".join(
|
| 191 |
+
[
|
| 192 |
+
rf"unsupported operand type\(s\) for \*: 'int' and '{typ}'",
|
| 193 |
+
"cannot perform (__rmul__|__rtruediv__|__rfloordiv__) with "
|
| 194 |
+
f"this index type: ({cls}|{typ})",
|
| 195 |
+
]
|
| 196 |
+
)
|
| 197 |
+
with pytest.raises(TypeError, match=rmsg):
|
| 198 |
+
1 * idx
|
| 199 |
+
|
| 200 |
+
div_err = lmsg.replace("*", "/")
|
| 201 |
+
with pytest.raises(TypeError, match=div_err):
|
| 202 |
+
idx / 1
|
| 203 |
+
div_err = rmsg.replace("*", "/")
|
| 204 |
+
with pytest.raises(TypeError, match=div_err):
|
| 205 |
+
1 / idx
|
| 206 |
+
|
| 207 |
+
floordiv_err = lmsg.replace("*", "//")
|
| 208 |
+
with pytest.raises(TypeError, match=floordiv_err):
|
| 209 |
+
idx // 1
|
| 210 |
+
floordiv_err = rmsg.replace("*", "//")
|
| 211 |
+
with pytest.raises(TypeError, match=floordiv_err):
|
| 212 |
+
1 // idx
|
| 213 |
+
|
| 214 |
+
def test_logical_compat(self, simple_index):
|
| 215 |
+
if simple_index.dtype in (object, "string"):
|
| 216 |
+
pytest.skip("Tested elsewhere.")
|
| 217 |
+
idx = simple_index
|
| 218 |
+
if idx.dtype.kind in "iufcbm":
|
| 219 |
+
assert idx.all() == idx._values.all()
|
| 220 |
+
assert idx.all() == idx.to_series().all()
|
| 221 |
+
assert idx.any() == idx._values.any()
|
| 222 |
+
assert idx.any() == idx.to_series().any()
|
| 223 |
+
else:
|
| 224 |
+
msg = "cannot perform (any|all)"
|
| 225 |
+
if isinstance(idx, IntervalIndex):
|
| 226 |
+
msg = (
|
| 227 |
+
r"'IntervalArray' with dtype interval\[.*\] does "
|
| 228 |
+
"not support reduction '(any|all)'"
|
| 229 |
+
)
|
| 230 |
+
with pytest.raises(TypeError, match=msg):
|
| 231 |
+
idx.all()
|
| 232 |
+
with pytest.raises(TypeError, match=msg):
|
| 233 |
+
idx.any()
|
| 234 |
+
|
| 235 |
+
def test_repr_roundtrip(self, simple_index):
|
| 236 |
+
if isinstance(simple_index, IntervalIndex):
|
| 237 |
+
pytest.skip(f"Not a valid repr for {type(simple_index).__name__}")
|
| 238 |
+
idx = simple_index
|
| 239 |
+
tm.assert_index_equal(eval(repr(idx)), idx)
|
| 240 |
+
|
| 241 |
+
def test_repr_max_seq_item_setting(self, simple_index):
|
| 242 |
+
# GH10182
|
| 243 |
+
if isinstance(simple_index, IntervalIndex):
|
| 244 |
+
pytest.skip(f"Not a valid repr for {type(simple_index).__name__}")
|
| 245 |
+
idx = simple_index
|
| 246 |
+
idx = idx.repeat(50)
|
| 247 |
+
with pd.option_context("display.max_seq_items", None):
|
| 248 |
+
repr(idx)
|
| 249 |
+
assert "..." not in str(idx)
|
| 250 |
+
|
| 251 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
| 252 |
+
def test_ensure_copied_data(self, index):
|
| 253 |
+
# Check the "copy" argument of each Index.__new__ is honoured
|
| 254 |
+
# GH12309
|
| 255 |
+
init_kwargs = {}
|
| 256 |
+
if isinstance(index, PeriodIndex):
|
| 257 |
+
# Needs "freq" specification:
|
| 258 |
+
init_kwargs["freq"] = index.freq
|
| 259 |
+
elif isinstance(index, (RangeIndex, MultiIndex, CategoricalIndex)):
|
| 260 |
+
pytest.skip(
|
| 261 |
+
"RangeIndex cannot be initialized from data, "
|
| 262 |
+
"MultiIndex and CategoricalIndex are tested separately"
|
| 263 |
+
)
|
| 264 |
+
elif index.dtype == object and index.inferred_type == "boolean":
|
| 265 |
+
init_kwargs["dtype"] = index.dtype
|
| 266 |
+
|
| 267 |
+
index_type = type(index)
|
| 268 |
+
result = index_type(index.values, copy=True, **init_kwargs)
|
| 269 |
+
if isinstance(index.dtype, DatetimeTZDtype):
|
| 270 |
+
result = result.tz_localize("UTC").tz_convert(index.tz)
|
| 271 |
+
if isinstance(index, (DatetimeIndex, TimedeltaIndex)):
|
| 272 |
+
index = index._with_freq(None)
|
| 273 |
+
|
| 274 |
+
tm.assert_index_equal(index, result)
|
| 275 |
+
|
| 276 |
+
if isinstance(index, PeriodIndex):
|
| 277 |
+
# .values an object array of Period, thus copied
|
| 278 |
+
depr_msg = "The 'ordinal' keyword in PeriodIndex is deprecated"
|
| 279 |
+
with tm.assert_produces_warning(FutureWarning, match=depr_msg):
|
| 280 |
+
result = index_type(ordinal=index.asi8, copy=False, **init_kwargs)
|
| 281 |
+
tm.assert_numpy_array_equal(index.asi8, result.asi8, check_same="same")
|
| 282 |
+
elif isinstance(index, IntervalIndex):
|
| 283 |
+
# checked in test_interval.py
|
| 284 |
+
pass
|
| 285 |
+
elif type(index) is Index and not isinstance(index.dtype, np.dtype):
|
| 286 |
+
result = index_type(index.values, copy=False, **init_kwargs)
|
| 287 |
+
tm.assert_index_equal(result, index)
|
| 288 |
+
|
| 289 |
+
if isinstance(index._values, BaseMaskedArray):
|
| 290 |
+
assert np.shares_memory(index._values._data, result._values._data)
|
| 291 |
+
tm.assert_numpy_array_equal(
|
| 292 |
+
index._values._data, result._values._data, check_same="same"
|
| 293 |
+
)
|
| 294 |
+
assert np.shares_memory(index._values._mask, result._values._mask)
|
| 295 |
+
tm.assert_numpy_array_equal(
|
| 296 |
+
index._values._mask, result._values._mask, check_same="same"
|
| 297 |
+
)
|
| 298 |
+
elif index.dtype == "string[python]":
|
| 299 |
+
assert np.shares_memory(index._values._ndarray, result._values._ndarray)
|
| 300 |
+
tm.assert_numpy_array_equal(
|
| 301 |
+
index._values._ndarray, result._values._ndarray, check_same="same"
|
| 302 |
+
)
|
| 303 |
+
elif index.dtype in ("string[pyarrow]", "string[pyarrow_numpy]"):
|
| 304 |
+
assert tm.shares_memory(result._values, index._values)
|
| 305 |
+
else:
|
| 306 |
+
raise NotImplementedError(index.dtype)
|
| 307 |
+
else:
|
| 308 |
+
result = index_type(index.values, copy=False, **init_kwargs)
|
| 309 |
+
tm.assert_numpy_array_equal(index.values, result.values, check_same="same")
|
| 310 |
+
|
| 311 |
+
def test_memory_usage(self, index):
|
| 312 |
+
index._engine.clear_mapping()
|
| 313 |
+
result = index.memory_usage()
|
| 314 |
+
if index.empty:
|
| 315 |
+
# we report 0 for no-length
|
| 316 |
+
assert result == 0
|
| 317 |
+
return
|
| 318 |
+
|
| 319 |
+
# non-zero length
|
| 320 |
+
index.get_loc(index[0])
|
| 321 |
+
result2 = index.memory_usage()
|
| 322 |
+
result3 = index.memory_usage(deep=True)
|
| 323 |
+
|
| 324 |
+
# RangeIndex, IntervalIndex
|
| 325 |
+
# don't have engines
|
| 326 |
+
# Index[EA] has engine but it does not have a Hashtable .mapping
|
| 327 |
+
if not isinstance(index, (RangeIndex, IntervalIndex)) and not (
|
| 328 |
+
type(index) is Index and not isinstance(index.dtype, np.dtype)
|
| 329 |
+
):
|
| 330 |
+
assert result2 > result
|
| 331 |
+
|
| 332 |
+
if index.inferred_type == "object":
|
| 333 |
+
assert result3 > result2
|
| 334 |
+
|
| 335 |
+
def test_argsort(self, index):
|
| 336 |
+
if isinstance(index, CategoricalIndex):
|
| 337 |
+
pytest.skip(f"{type(self).__name__} separately tested")
|
| 338 |
+
|
| 339 |
+
result = index.argsort()
|
| 340 |
+
expected = np.array(index).argsort()
|
| 341 |
+
tm.assert_numpy_array_equal(result, expected, check_dtype=False)
|
| 342 |
+
|
| 343 |
+
def test_numpy_argsort(self, index):
|
| 344 |
+
result = np.argsort(index)
|
| 345 |
+
expected = index.argsort()
|
| 346 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 347 |
+
|
| 348 |
+
result = np.argsort(index, kind="mergesort")
|
| 349 |
+
expected = index.argsort(kind="mergesort")
|
| 350 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 351 |
+
|
| 352 |
+
# these are the only two types that perform
|
| 353 |
+
# pandas compatibility input validation - the
|
| 354 |
+
# rest already perform separate (or no) such
|
| 355 |
+
# validation via their 'values' attribute as
|
| 356 |
+
# defined in pandas.core.indexes/base.py - they
|
| 357 |
+
# cannot be changed at the moment due to
|
| 358 |
+
# backwards compatibility concerns
|
| 359 |
+
if isinstance(index, (CategoricalIndex, RangeIndex)):
|
| 360 |
+
msg = "the 'axis' parameter is not supported"
|
| 361 |
+
with pytest.raises(ValueError, match=msg):
|
| 362 |
+
np.argsort(index, axis=1)
|
| 363 |
+
|
| 364 |
+
msg = "the 'order' parameter is not supported"
|
| 365 |
+
with pytest.raises(ValueError, match=msg):
|
| 366 |
+
np.argsort(index, order=("a", "b"))
|
| 367 |
+
|
| 368 |
+
def test_repeat(self, simple_index):
|
| 369 |
+
rep = 2
|
| 370 |
+
idx = simple_index.copy()
|
| 371 |
+
new_index_cls = idx._constructor
|
| 372 |
+
expected = new_index_cls(idx.values.repeat(rep), name=idx.name)
|
| 373 |
+
tm.assert_index_equal(idx.repeat(rep), expected)
|
| 374 |
+
|
| 375 |
+
idx = simple_index
|
| 376 |
+
rep = np.arange(len(idx))
|
| 377 |
+
expected = new_index_cls(idx.values.repeat(rep), name=idx.name)
|
| 378 |
+
tm.assert_index_equal(idx.repeat(rep), expected)
|
| 379 |
+
|
| 380 |
+
def test_numpy_repeat(self, simple_index):
|
| 381 |
+
rep = 2
|
| 382 |
+
idx = simple_index
|
| 383 |
+
expected = idx.repeat(rep)
|
| 384 |
+
tm.assert_index_equal(np.repeat(idx, rep), expected)
|
| 385 |
+
|
| 386 |
+
msg = "the 'axis' parameter is not supported"
|
| 387 |
+
with pytest.raises(ValueError, match=msg):
|
| 388 |
+
np.repeat(idx, rep, axis=0)
|
| 389 |
+
|
| 390 |
+
def test_where(self, listlike_box, simple_index):
|
| 391 |
+
if isinstance(simple_index, (IntervalIndex, PeriodIndex)) or is_numeric_dtype(
|
| 392 |
+
simple_index.dtype
|
| 393 |
+
):
|
| 394 |
+
pytest.skip("Tested elsewhere.")
|
| 395 |
+
klass = listlike_box
|
| 396 |
+
|
| 397 |
+
idx = simple_index
|
| 398 |
+
if isinstance(idx, (DatetimeIndex, TimedeltaIndex)):
|
| 399 |
+
# where does not preserve freq
|
| 400 |
+
idx = idx._with_freq(None)
|
| 401 |
+
|
| 402 |
+
cond = [True] * len(idx)
|
| 403 |
+
result = idx.where(klass(cond))
|
| 404 |
+
expected = idx
|
| 405 |
+
tm.assert_index_equal(result, expected)
|
| 406 |
+
|
| 407 |
+
cond = [False] + [True] * len(idx[1:])
|
| 408 |
+
expected = Index([idx._na_value] + idx[1:].tolist(), dtype=idx.dtype)
|
| 409 |
+
result = idx.where(klass(cond))
|
| 410 |
+
tm.assert_index_equal(result, expected)
|
| 411 |
+
|
| 412 |
+
def test_insert_base(self, index):
|
| 413 |
+
trimmed = index[1:4]
|
| 414 |
+
|
| 415 |
+
if not len(index):
|
| 416 |
+
pytest.skip("Not applicable for empty index")
|
| 417 |
+
|
| 418 |
+
# test 0th element
|
| 419 |
+
warn = None
|
| 420 |
+
if index.dtype == object and index.inferred_type == "boolean":
|
| 421 |
+
# GH#51363
|
| 422 |
+
warn = FutureWarning
|
| 423 |
+
msg = "The behavior of Index.insert with object-dtype is deprecated"
|
| 424 |
+
with tm.assert_produces_warning(warn, match=msg):
|
| 425 |
+
result = trimmed.insert(0, index[0])
|
| 426 |
+
assert index[0:4].equals(result)
|
| 427 |
+
|
| 428 |
+
@pytest.mark.skipif(
|
| 429 |
+
using_pyarrow_string_dtype(),
|
| 430 |
+
reason="completely different behavior, tested elsewher",
|
| 431 |
+
)
|
| 432 |
+
def test_insert_out_of_bounds(self, index):
|
| 433 |
+
# TypeError/IndexError matches what np.insert raises in these cases
|
| 434 |
+
|
| 435 |
+
if len(index) > 0:
|
| 436 |
+
err = TypeError
|
| 437 |
+
else:
|
| 438 |
+
err = IndexError
|
| 439 |
+
if len(index) == 0:
|
| 440 |
+
# 0 vs 0.5 in error message varies with numpy version
|
| 441 |
+
msg = "index (0|0.5) is out of bounds for axis 0 with size 0"
|
| 442 |
+
else:
|
| 443 |
+
msg = "slice indices must be integers or None or have an __index__ method"
|
| 444 |
+
with pytest.raises(err, match=msg):
|
| 445 |
+
index.insert(0.5, "foo")
|
| 446 |
+
|
| 447 |
+
msg = "|".join(
|
| 448 |
+
[
|
| 449 |
+
r"index -?\d+ is out of bounds for axis 0 with size \d+",
|
| 450 |
+
"loc must be an integer between",
|
| 451 |
+
]
|
| 452 |
+
)
|
| 453 |
+
with pytest.raises(IndexError, match=msg):
|
| 454 |
+
index.insert(len(index) + 1, 1)
|
| 455 |
+
|
| 456 |
+
with pytest.raises(IndexError, match=msg):
|
| 457 |
+
index.insert(-len(index) - 1, 1)
|
| 458 |
+
|
| 459 |
+
def test_delete_base(self, index):
|
| 460 |
+
if not len(index):
|
| 461 |
+
pytest.skip("Not applicable for empty index")
|
| 462 |
+
|
| 463 |
+
if isinstance(index, RangeIndex):
|
| 464 |
+
# tested in class
|
| 465 |
+
pytest.skip(f"{type(self).__name__} tested elsewhere")
|
| 466 |
+
|
| 467 |
+
expected = index[1:]
|
| 468 |
+
result = index.delete(0)
|
| 469 |
+
assert result.equals(expected)
|
| 470 |
+
assert result.name == expected.name
|
| 471 |
+
|
| 472 |
+
expected = index[:-1]
|
| 473 |
+
result = index.delete(-1)
|
| 474 |
+
assert result.equals(expected)
|
| 475 |
+
assert result.name == expected.name
|
| 476 |
+
|
| 477 |
+
length = len(index)
|
| 478 |
+
msg = f"index {length} is out of bounds for axis 0 with size {length}"
|
| 479 |
+
with pytest.raises(IndexError, match=msg):
|
| 480 |
+
index.delete(length)
|
| 481 |
+
|
| 482 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
| 483 |
+
def test_equals(self, index):
|
| 484 |
+
if isinstance(index, IntervalIndex):
|
| 485 |
+
pytest.skip(f"{type(index).__name__} tested elsewhere")
|
| 486 |
+
|
| 487 |
+
is_ea_idx = type(index) is Index and not isinstance(index.dtype, np.dtype)
|
| 488 |
+
|
| 489 |
+
assert index.equals(index)
|
| 490 |
+
assert index.equals(index.copy())
|
| 491 |
+
if not is_ea_idx:
|
| 492 |
+
# doesn't hold for e.g. IntegerDtype
|
| 493 |
+
assert index.equals(index.astype(object))
|
| 494 |
+
|
| 495 |
+
assert not index.equals(list(index))
|
| 496 |
+
assert not index.equals(np.array(index))
|
| 497 |
+
|
| 498 |
+
# Cannot pass in non-int64 dtype to RangeIndex
|
| 499 |
+
if not isinstance(index, RangeIndex) and not is_ea_idx:
|
| 500 |
+
same_values = Index(index, dtype=object)
|
| 501 |
+
assert index.equals(same_values)
|
| 502 |
+
assert same_values.equals(index)
|
| 503 |
+
|
| 504 |
+
if index.nlevels == 1:
|
| 505 |
+
# do not test MultiIndex
|
| 506 |
+
assert not index.equals(Series(index))
|
| 507 |
+
|
| 508 |
+
def test_equals_op(self, simple_index):
|
| 509 |
+
# GH9947, GH10637
|
| 510 |
+
index_a = simple_index
|
| 511 |
+
|
| 512 |
+
n = len(index_a)
|
| 513 |
+
index_b = index_a[0:-1]
|
| 514 |
+
index_c = index_a[0:-1].append(index_a[-2:-1])
|
| 515 |
+
index_d = index_a[0:1]
|
| 516 |
+
|
| 517 |
+
msg = "Lengths must match|could not be broadcast"
|
| 518 |
+
with pytest.raises(ValueError, match=msg):
|
| 519 |
+
index_a == index_b
|
| 520 |
+
expected1 = np.array([True] * n)
|
| 521 |
+
expected2 = np.array([True] * (n - 1) + [False])
|
| 522 |
+
tm.assert_numpy_array_equal(index_a == index_a, expected1)
|
| 523 |
+
tm.assert_numpy_array_equal(index_a == index_c, expected2)
|
| 524 |
+
|
| 525 |
+
# test comparisons with numpy arrays
|
| 526 |
+
array_a = np.array(index_a)
|
| 527 |
+
array_b = np.array(index_a[0:-1])
|
| 528 |
+
array_c = np.array(index_a[0:-1].append(index_a[-2:-1]))
|
| 529 |
+
array_d = np.array(index_a[0:1])
|
| 530 |
+
with pytest.raises(ValueError, match=msg):
|
| 531 |
+
index_a == array_b
|
| 532 |
+
tm.assert_numpy_array_equal(index_a == array_a, expected1)
|
| 533 |
+
tm.assert_numpy_array_equal(index_a == array_c, expected2)
|
| 534 |
+
|
| 535 |
+
# test comparisons with Series
|
| 536 |
+
series_a = Series(array_a)
|
| 537 |
+
series_b = Series(array_b)
|
| 538 |
+
series_c = Series(array_c)
|
| 539 |
+
series_d = Series(array_d)
|
| 540 |
+
with pytest.raises(ValueError, match=msg):
|
| 541 |
+
index_a == series_b
|
| 542 |
+
|
| 543 |
+
tm.assert_numpy_array_equal(index_a == series_a, expected1)
|
| 544 |
+
tm.assert_numpy_array_equal(index_a == series_c, expected2)
|
| 545 |
+
|
| 546 |
+
# cases where length is 1 for one of them
|
| 547 |
+
with pytest.raises(ValueError, match="Lengths must match"):
|
| 548 |
+
index_a == index_d
|
| 549 |
+
with pytest.raises(ValueError, match="Lengths must match"):
|
| 550 |
+
index_a == series_d
|
| 551 |
+
with pytest.raises(ValueError, match="Lengths must match"):
|
| 552 |
+
index_a == array_d
|
| 553 |
+
msg = "Can only compare identically-labeled Series objects"
|
| 554 |
+
with pytest.raises(ValueError, match=msg):
|
| 555 |
+
series_a == series_d
|
| 556 |
+
with pytest.raises(ValueError, match="Lengths must match"):
|
| 557 |
+
series_a == array_d
|
| 558 |
+
|
| 559 |
+
# comparing with a scalar should broadcast; note that we are excluding
|
| 560 |
+
# MultiIndex because in this case each item in the index is a tuple of
|
| 561 |
+
# length 2, and therefore is considered an array of length 2 in the
|
| 562 |
+
# comparison instead of a scalar
|
| 563 |
+
if not isinstance(index_a, MultiIndex):
|
| 564 |
+
expected3 = np.array([False] * (len(index_a) - 2) + [True, False])
|
| 565 |
+
# assuming the 2nd to last item is unique in the data
|
| 566 |
+
item = index_a[-2]
|
| 567 |
+
tm.assert_numpy_array_equal(index_a == item, expected3)
|
| 568 |
+
tm.assert_series_equal(series_a == item, Series(expected3))
|
| 569 |
+
|
| 570 |
+
def test_format(self, simple_index):
|
| 571 |
+
# GH35439
|
| 572 |
+
if is_numeric_dtype(simple_index.dtype) or isinstance(
|
| 573 |
+
simple_index, DatetimeIndex
|
| 574 |
+
):
|
| 575 |
+
pytest.skip("Tested elsewhere.")
|
| 576 |
+
idx = simple_index
|
| 577 |
+
expected = [str(x) for x in idx]
|
| 578 |
+
msg = r"Index\.format is deprecated"
|
| 579 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 580 |
+
assert idx.format() == expected
|
| 581 |
+
|
| 582 |
+
def test_format_empty(self, simple_index):
|
| 583 |
+
# GH35712
|
| 584 |
+
if isinstance(simple_index, (PeriodIndex, RangeIndex)):
|
| 585 |
+
pytest.skip("Tested elsewhere")
|
| 586 |
+
empty_idx = type(simple_index)([])
|
| 587 |
+
msg = r"Index\.format is deprecated"
|
| 588 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 589 |
+
assert empty_idx.format() == []
|
| 590 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 591 |
+
assert empty_idx.format(name=True) == [""]
|
| 592 |
+
|
| 593 |
+
def test_fillna(self, index):
|
| 594 |
+
# GH 11343
|
| 595 |
+
if len(index) == 0:
|
| 596 |
+
pytest.skip("Not relevant for empty index")
|
| 597 |
+
elif index.dtype == bool:
|
| 598 |
+
pytest.skip(f"{index.dtype} cannot hold NAs")
|
| 599 |
+
elif isinstance(index, Index) and is_integer_dtype(index.dtype):
|
| 600 |
+
pytest.skip(f"Not relevant for Index with {index.dtype}")
|
| 601 |
+
elif isinstance(index, MultiIndex):
|
| 602 |
+
idx = index.copy(deep=True)
|
| 603 |
+
msg = "isna is not defined for MultiIndex"
|
| 604 |
+
with pytest.raises(NotImplementedError, match=msg):
|
| 605 |
+
idx.fillna(idx[0])
|
| 606 |
+
else:
|
| 607 |
+
idx = index.copy(deep=True)
|
| 608 |
+
result = idx.fillna(idx[0])
|
| 609 |
+
tm.assert_index_equal(result, idx)
|
| 610 |
+
assert result is not idx
|
| 611 |
+
|
| 612 |
+
msg = "'value' must be a scalar, passed: "
|
| 613 |
+
with pytest.raises(TypeError, match=msg):
|
| 614 |
+
idx.fillna([idx[0]])
|
| 615 |
+
|
| 616 |
+
idx = index.copy(deep=True)
|
| 617 |
+
values = idx._values
|
| 618 |
+
|
| 619 |
+
values[1] = np.nan
|
| 620 |
+
|
| 621 |
+
idx = type(index)(values)
|
| 622 |
+
|
| 623 |
+
msg = "does not support 'downcast'"
|
| 624 |
+
msg2 = r"The 'downcast' keyword in .*Index\.fillna is deprecated"
|
| 625 |
+
with tm.assert_produces_warning(FutureWarning, match=msg2):
|
| 626 |
+
with pytest.raises(NotImplementedError, match=msg):
|
| 627 |
+
# For now at least, we only raise if there are NAs present
|
| 628 |
+
idx.fillna(idx[0], downcast="infer")
|
| 629 |
+
|
| 630 |
+
expected = np.array([False] * len(idx), dtype=bool)
|
| 631 |
+
expected[1] = True
|
| 632 |
+
tm.assert_numpy_array_equal(idx._isnan, expected)
|
| 633 |
+
assert idx.hasnans is True
|
| 634 |
+
|
| 635 |
+
def test_nulls(self, index):
|
| 636 |
+
# this is really a smoke test for the methods
|
| 637 |
+
# as these are adequately tested for function elsewhere
|
| 638 |
+
if len(index) == 0:
|
| 639 |
+
tm.assert_numpy_array_equal(index.isna(), np.array([], dtype=bool))
|
| 640 |
+
elif isinstance(index, MultiIndex):
|
| 641 |
+
idx = index.copy()
|
| 642 |
+
msg = "isna is not defined for MultiIndex"
|
| 643 |
+
with pytest.raises(NotImplementedError, match=msg):
|
| 644 |
+
idx.isna()
|
| 645 |
+
elif not index.hasnans:
|
| 646 |
+
tm.assert_numpy_array_equal(index.isna(), np.zeros(len(index), dtype=bool))
|
| 647 |
+
tm.assert_numpy_array_equal(index.notna(), np.ones(len(index), dtype=bool))
|
| 648 |
+
else:
|
| 649 |
+
result = isna(index)
|
| 650 |
+
tm.assert_numpy_array_equal(index.isna(), result)
|
| 651 |
+
tm.assert_numpy_array_equal(index.notna(), ~result)
|
| 652 |
+
|
| 653 |
+
def test_empty(self, simple_index):
|
| 654 |
+
# GH 15270
|
| 655 |
+
idx = simple_index
|
| 656 |
+
assert not idx.empty
|
| 657 |
+
assert idx[:0].empty
|
| 658 |
+
|
| 659 |
+
def test_join_self_unique(self, join_type, simple_index):
|
| 660 |
+
idx = simple_index
|
| 661 |
+
if idx.is_unique:
|
| 662 |
+
joined = idx.join(idx, how=join_type)
|
| 663 |
+
expected = simple_index
|
| 664 |
+
if join_type == "outer":
|
| 665 |
+
expected = algos.safe_sort(expected)
|
| 666 |
+
tm.assert_index_equal(joined, expected)
|
| 667 |
+
|
| 668 |
+
def test_map(self, simple_index):
|
| 669 |
+
# callable
|
| 670 |
+
if isinstance(simple_index, (TimedeltaIndex, PeriodIndex)):
|
| 671 |
+
pytest.skip("Tested elsewhere.")
|
| 672 |
+
idx = simple_index
|
| 673 |
+
|
| 674 |
+
result = idx.map(lambda x: x)
|
| 675 |
+
# RangeIndex are equivalent to the similar Index with int64 dtype
|
| 676 |
+
tm.assert_index_equal(result, idx, exact="equiv")
|
| 677 |
+
|
| 678 |
+
@pytest.mark.parametrize(
|
| 679 |
+
"mapper",
|
| 680 |
+
[
|
| 681 |
+
lambda values, index: {i: e for e, i in zip(values, index)},
|
| 682 |
+
lambda values, index: Series(values, index),
|
| 683 |
+
],
|
| 684 |
+
)
|
| 685 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
| 686 |
+
def test_map_dictlike(self, mapper, simple_index, request):
|
| 687 |
+
idx = simple_index
|
| 688 |
+
if isinstance(idx, (DatetimeIndex, TimedeltaIndex, PeriodIndex)):
|
| 689 |
+
pytest.skip("Tested elsewhere.")
|
| 690 |
+
|
| 691 |
+
identity = mapper(idx.values, idx)
|
| 692 |
+
|
| 693 |
+
result = idx.map(identity)
|
| 694 |
+
# RangeIndex are equivalent to the similar Index with int64 dtype
|
| 695 |
+
tm.assert_index_equal(result, idx, exact="equiv")
|
| 696 |
+
|
| 697 |
+
# empty mappable
|
| 698 |
+
dtype = None
|
| 699 |
+
if idx.dtype.kind == "f":
|
| 700 |
+
dtype = idx.dtype
|
| 701 |
+
|
| 702 |
+
expected = Index([np.nan] * len(idx), dtype=dtype)
|
| 703 |
+
result = idx.map(mapper(expected, idx))
|
| 704 |
+
tm.assert_index_equal(result, expected)
|
| 705 |
+
|
| 706 |
+
def test_map_str(self, simple_index):
|
| 707 |
+
# GH 31202
|
| 708 |
+
if isinstance(simple_index, CategoricalIndex):
|
| 709 |
+
pytest.skip("See test_map.py")
|
| 710 |
+
idx = simple_index
|
| 711 |
+
result = idx.map(str)
|
| 712 |
+
expected = Index([str(x) for x in idx])
|
| 713 |
+
tm.assert_index_equal(result, expected)
|
| 714 |
+
|
| 715 |
+
@pytest.mark.parametrize("copy", [True, False])
|
| 716 |
+
@pytest.mark.parametrize("name", [None, "foo"])
|
| 717 |
+
@pytest.mark.parametrize("ordered", [True, False])
|
| 718 |
+
def test_astype_category(self, copy, name, ordered, simple_index):
|
| 719 |
+
# GH 18630
|
| 720 |
+
idx = simple_index
|
| 721 |
+
if name:
|
| 722 |
+
idx = idx.rename(name)
|
| 723 |
+
|
| 724 |
+
# standard categories
|
| 725 |
+
dtype = CategoricalDtype(ordered=ordered)
|
| 726 |
+
result = idx.astype(dtype, copy=copy)
|
| 727 |
+
expected = CategoricalIndex(idx, name=name, ordered=ordered)
|
| 728 |
+
tm.assert_index_equal(result, expected, exact=True)
|
| 729 |
+
|
| 730 |
+
# non-standard categories
|
| 731 |
+
dtype = CategoricalDtype(idx.unique().tolist()[:-1], ordered)
|
| 732 |
+
result = idx.astype(dtype, copy=copy)
|
| 733 |
+
expected = CategoricalIndex(idx, name=name, dtype=dtype)
|
| 734 |
+
tm.assert_index_equal(result, expected, exact=True)
|
| 735 |
+
|
| 736 |
+
if ordered is False:
|
| 737 |
+
# dtype='category' defaults to ordered=False, so only test once
|
| 738 |
+
result = idx.astype("category", copy=copy)
|
| 739 |
+
expected = CategoricalIndex(idx, name=name)
|
| 740 |
+
tm.assert_index_equal(result, expected, exact=True)
|
| 741 |
+
|
| 742 |
+
def test_is_unique(self, simple_index):
|
| 743 |
+
# initialize a unique index
|
| 744 |
+
index = simple_index.drop_duplicates()
|
| 745 |
+
assert index.is_unique is True
|
| 746 |
+
|
| 747 |
+
# empty index should be unique
|
| 748 |
+
index_empty = index[:0]
|
| 749 |
+
assert index_empty.is_unique is True
|
| 750 |
+
|
| 751 |
+
# test basic dupes
|
| 752 |
+
index_dup = index.insert(0, index[0])
|
| 753 |
+
assert index_dup.is_unique is False
|
| 754 |
+
|
| 755 |
+
# single NA should be unique
|
| 756 |
+
index_na = index.insert(0, np.nan)
|
| 757 |
+
assert index_na.is_unique is True
|
| 758 |
+
|
| 759 |
+
# multiple NA should not be unique
|
| 760 |
+
index_na_dup = index_na.insert(0, np.nan)
|
| 761 |
+
assert index_na_dup.is_unique is False
|
| 762 |
+
|
| 763 |
+
@pytest.mark.arm_slow
|
| 764 |
+
def test_engine_reference_cycle(self, simple_index):
|
| 765 |
+
# GH27585
|
| 766 |
+
index = simple_index.copy()
|
| 767 |
+
ref = weakref.ref(index)
|
| 768 |
+
index._engine
|
| 769 |
+
del index
|
| 770 |
+
assert ref() is None
|
| 771 |
+
|
| 772 |
+
def test_getitem_2d_deprecated(self, simple_index):
|
| 773 |
+
# GH#30588, GH#31479
|
| 774 |
+
if isinstance(simple_index, IntervalIndex):
|
| 775 |
+
pytest.skip("Tested elsewhere")
|
| 776 |
+
idx = simple_index
|
| 777 |
+
msg = "Multi-dimensional indexing|too many|only"
|
| 778 |
+
with pytest.raises((ValueError, IndexError), match=msg):
|
| 779 |
+
idx[:, None]
|
| 780 |
+
|
| 781 |
+
if not isinstance(idx, RangeIndex):
|
| 782 |
+
# GH#44051 RangeIndex already raised pre-2.0 with a different message
|
| 783 |
+
with pytest.raises((ValueError, IndexError), match=msg):
|
| 784 |
+
idx[True]
|
| 785 |
+
with pytest.raises((ValueError, IndexError), match=msg):
|
| 786 |
+
idx[False]
|
| 787 |
+
else:
|
| 788 |
+
msg = "only integers, slices"
|
| 789 |
+
with pytest.raises(IndexError, match=msg):
|
| 790 |
+
idx[True]
|
| 791 |
+
with pytest.raises(IndexError, match=msg):
|
| 792 |
+
idx[False]
|
| 793 |
+
|
| 794 |
+
def test_copy_shares_cache(self, simple_index):
|
| 795 |
+
# GH32898, GH36840
|
| 796 |
+
idx = simple_index
|
| 797 |
+
idx.get_loc(idx[0]) # populates the _cache.
|
| 798 |
+
copy = idx.copy()
|
| 799 |
+
|
| 800 |
+
assert copy._cache is idx._cache
|
| 801 |
+
|
| 802 |
+
def test_shallow_copy_shares_cache(self, simple_index):
|
| 803 |
+
# GH32669, GH36840
|
| 804 |
+
idx = simple_index
|
| 805 |
+
idx.get_loc(idx[0]) # populates the _cache.
|
| 806 |
+
shallow_copy = idx._view()
|
| 807 |
+
|
| 808 |
+
assert shallow_copy._cache is idx._cache
|
| 809 |
+
|
| 810 |
+
shallow_copy = idx._shallow_copy(idx._data)
|
| 811 |
+
assert shallow_copy._cache is not idx._cache
|
| 812 |
+
assert shallow_copy._cache == {}
|
| 813 |
+
|
| 814 |
+
def test_index_groupby(self, simple_index):
|
| 815 |
+
idx = simple_index[:5]
|
| 816 |
+
to_groupby = np.array([1, 2, np.nan, 2, 1])
|
| 817 |
+
tm.assert_dict_equal(
|
| 818 |
+
idx.groupby(to_groupby), {1.0: idx[[0, 4]], 2.0: idx[[1, 3]]}
|
| 819 |
+
)
|
| 820 |
+
|
| 821 |
+
to_groupby = DatetimeIndex(
|
| 822 |
+
[
|
| 823 |
+
datetime(2011, 11, 1),
|
| 824 |
+
datetime(2011, 12, 1),
|
| 825 |
+
pd.NaT,
|
| 826 |
+
datetime(2011, 12, 1),
|
| 827 |
+
datetime(2011, 11, 1),
|
| 828 |
+
],
|
| 829 |
+
tz="UTC",
|
| 830 |
+
).values
|
| 831 |
+
|
| 832 |
+
ex_keys = [Timestamp("2011-11-01"), Timestamp("2011-12-01")]
|
| 833 |
+
expected = {ex_keys[0]: idx[[0, 4]], ex_keys[1]: idx[[1, 3]]}
|
| 834 |
+
tm.assert_dict_equal(idx.groupby(to_groupby), expected)
|
| 835 |
+
|
| 836 |
+
def test_append_preserves_dtype(self, simple_index):
|
| 837 |
+
# In particular Index with dtype float32
|
| 838 |
+
index = simple_index
|
| 839 |
+
N = len(index)
|
| 840 |
+
|
| 841 |
+
result = index.append(index)
|
| 842 |
+
assert result.dtype == index.dtype
|
| 843 |
+
tm.assert_index_equal(result[:N], index, check_exact=True)
|
| 844 |
+
tm.assert_index_equal(result[N:], index, check_exact=True)
|
| 845 |
+
|
| 846 |
+
alt = index.take(list(range(N)) * 2)
|
| 847 |
+
tm.assert_index_equal(result, alt, check_exact=True)
|
| 848 |
+
|
| 849 |
+
def test_inv(self, simple_index, using_infer_string):
|
| 850 |
+
idx = simple_index
|
| 851 |
+
|
| 852 |
+
if idx.dtype.kind in ["i", "u"]:
|
| 853 |
+
res = ~idx
|
| 854 |
+
expected = Index(~idx.values, name=idx.name)
|
| 855 |
+
tm.assert_index_equal(res, expected)
|
| 856 |
+
|
| 857 |
+
# check that we are matching Series behavior
|
| 858 |
+
res2 = ~Series(idx)
|
| 859 |
+
tm.assert_series_equal(res2, Series(expected))
|
| 860 |
+
else:
|
| 861 |
+
if idx.dtype.kind == "f":
|
| 862 |
+
err = TypeError
|
| 863 |
+
msg = "ufunc 'invert' not supported for the input types"
|
| 864 |
+
elif using_infer_string and idx.dtype == "string":
|
| 865 |
+
import pyarrow as pa
|
| 866 |
+
|
| 867 |
+
err = pa.lib.ArrowNotImplementedError
|
| 868 |
+
msg = "has no kernel"
|
| 869 |
+
else:
|
| 870 |
+
err = TypeError
|
| 871 |
+
msg = "bad operand"
|
| 872 |
+
with pytest.raises(err, match=msg):
|
| 873 |
+
~idx
|
| 874 |
+
|
| 875 |
+
# check that we get the same behavior with Series
|
| 876 |
+
with pytest.raises(err, match=msg):
|
| 877 |
+
~Series(idx)
|
| 878 |
+
|
| 879 |
+
def test_is_boolean_is_deprecated(self, simple_index):
|
| 880 |
+
# GH50042
|
| 881 |
+
idx = simple_index
|
| 882 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 883 |
+
idx.is_boolean()
|
| 884 |
+
|
| 885 |
+
def test_is_floating_is_deprecated(self, simple_index):
|
| 886 |
+
# GH50042
|
| 887 |
+
idx = simple_index
|
| 888 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 889 |
+
idx.is_floating()
|
| 890 |
+
|
| 891 |
+
def test_is_integer_is_deprecated(self, simple_index):
|
| 892 |
+
# GH50042
|
| 893 |
+
idx = simple_index
|
| 894 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 895 |
+
idx.is_integer()
|
| 896 |
+
|
| 897 |
+
def test_holds_integer_deprecated(self, simple_index):
|
| 898 |
+
# GH50243
|
| 899 |
+
idx = simple_index
|
| 900 |
+
msg = f"{type(idx).__name__}.holds_integer is deprecated. "
|
| 901 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 902 |
+
idx.holds_integer()
|
| 903 |
+
|
| 904 |
+
def test_is_numeric_is_deprecated(self, simple_index):
|
| 905 |
+
# GH50042
|
| 906 |
+
idx = simple_index
|
| 907 |
+
with tm.assert_produces_warning(
|
| 908 |
+
FutureWarning,
|
| 909 |
+
match=f"{type(idx).__name__}.is_numeric is deprecated. ",
|
| 910 |
+
):
|
| 911 |
+
idx.is_numeric()
|
| 912 |
+
|
| 913 |
+
def test_is_categorical_is_deprecated(self, simple_index):
|
| 914 |
+
# GH50042
|
| 915 |
+
idx = simple_index
|
| 916 |
+
with tm.assert_produces_warning(
|
| 917 |
+
FutureWarning,
|
| 918 |
+
match=r"Use pandas\.api\.types\.is_categorical_dtype instead",
|
| 919 |
+
):
|
| 920 |
+
idx.is_categorical()
|
| 921 |
+
|
| 922 |
+
def test_is_interval_is_deprecated(self, simple_index):
|
| 923 |
+
# GH50042
|
| 924 |
+
idx = simple_index
|
| 925 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 926 |
+
idx.is_interval()
|
| 927 |
+
|
| 928 |
+
def test_is_object_is_deprecated(self, simple_index):
|
| 929 |
+
# GH50042
|
| 930 |
+
idx = simple_index
|
| 931 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 932 |
+
idx.is_object()
|
| 933 |
+
|
| 934 |
+
|
| 935 |
+
class TestNumericBase:
|
| 936 |
+
@pytest.fixture(
|
| 937 |
+
params=[
|
| 938 |
+
RangeIndex(start=0, stop=20, step=2),
|
| 939 |
+
Index(np.arange(5, dtype=np.float64)),
|
| 940 |
+
Index(np.arange(5, dtype=np.float32)),
|
| 941 |
+
Index(np.arange(5, dtype=np.uint64)),
|
| 942 |
+
Index(range(0, 20, 2), dtype=np.int64),
|
| 943 |
+
Index(range(0, 20, 2), dtype=np.int32),
|
| 944 |
+
Index(range(0, 20, 2), dtype=np.int16),
|
| 945 |
+
Index(range(0, 20, 2), dtype=np.int8),
|
| 946 |
+
]
|
| 947 |
+
)
|
| 948 |
+
def simple_index(self, request):
|
| 949 |
+
return request.param
|
| 950 |
+
|
| 951 |
+
def test_constructor_unwraps_index(self, simple_index):
|
| 952 |
+
if isinstance(simple_index, RangeIndex):
|
| 953 |
+
pytest.skip("Tested elsewhere.")
|
| 954 |
+
index_cls = type(simple_index)
|
| 955 |
+
dtype = simple_index.dtype
|
| 956 |
+
|
| 957 |
+
idx = Index([1, 2], dtype=dtype)
|
| 958 |
+
result = index_cls(idx)
|
| 959 |
+
expected = np.array([1, 2], dtype=idx.dtype)
|
| 960 |
+
tm.assert_numpy_array_equal(result._data, expected)
|
| 961 |
+
|
| 962 |
+
def test_can_hold_identifiers(self, simple_index):
|
| 963 |
+
idx = simple_index
|
| 964 |
+
key = idx[0]
|
| 965 |
+
assert idx._can_hold_identifiers_and_holds_name(key) is False
|
| 966 |
+
|
| 967 |
+
def test_view(self, simple_index):
|
| 968 |
+
if isinstance(simple_index, RangeIndex):
|
| 969 |
+
pytest.skip("Tested elsewhere.")
|
| 970 |
+
index_cls = type(simple_index)
|
| 971 |
+
dtype = simple_index.dtype
|
| 972 |
+
|
| 973 |
+
idx = index_cls([], dtype=dtype, name="Foo")
|
| 974 |
+
idx_view = idx.view()
|
| 975 |
+
assert idx_view.name == "Foo"
|
| 976 |
+
|
| 977 |
+
idx_view = idx.view(dtype)
|
| 978 |
+
tm.assert_index_equal(idx, index_cls(idx_view, name="Foo"), exact=True)
|
| 979 |
+
|
| 980 |
+
msg = "Passing a type in .*Index.view is deprecated"
|
| 981 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 982 |
+
idx_view = idx.view(index_cls)
|
| 983 |
+
tm.assert_index_equal(idx, index_cls(idx_view, name="Foo"), exact=True)
|
| 984 |
+
|
| 985 |
+
def test_format(self, simple_index):
|
| 986 |
+
# GH35439
|
| 987 |
+
if isinstance(simple_index, DatetimeIndex):
|
| 988 |
+
pytest.skip("Tested elsewhere")
|
| 989 |
+
idx = simple_index
|
| 990 |
+
max_width = max(len(str(x)) for x in idx)
|
| 991 |
+
expected = [str(x).ljust(max_width) for x in idx]
|
| 992 |
+
msg = r"Index\.format is deprecated"
|
| 993 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 994 |
+
assert idx.format() == expected
|
| 995 |
+
|
| 996 |
+
def test_insert_non_na(self, simple_index):
|
| 997 |
+
# GH#43921 inserting an element that we know we can hold should
|
| 998 |
+
# not change dtype or type (except for RangeIndex)
|
| 999 |
+
index = simple_index
|
| 1000 |
+
|
| 1001 |
+
result = index.insert(0, index[0])
|
| 1002 |
+
|
| 1003 |
+
expected = Index([index[0]] + list(index), dtype=index.dtype)
|
| 1004 |
+
tm.assert_index_equal(result, expected, exact=True)
|
| 1005 |
+
|
| 1006 |
+
def test_insert_na(self, nulls_fixture, simple_index):
|
| 1007 |
+
# GH 18295 (test missing)
|
| 1008 |
+
index = simple_index
|
| 1009 |
+
na_val = nulls_fixture
|
| 1010 |
+
|
| 1011 |
+
if na_val is pd.NaT:
|
| 1012 |
+
expected = Index([index[0], pd.NaT] + list(index[1:]), dtype=object)
|
| 1013 |
+
else:
|
| 1014 |
+
expected = Index([index[0], np.nan] + list(index[1:]))
|
| 1015 |
+
# GH#43921 we preserve float dtype
|
| 1016 |
+
if index.dtype.kind == "f":
|
| 1017 |
+
expected = Index(expected, dtype=index.dtype)
|
| 1018 |
+
|
| 1019 |
+
result = index.insert(1, na_val)
|
| 1020 |
+
tm.assert_index_equal(result, expected, exact=True)
|
| 1021 |
+
|
| 1022 |
+
def test_arithmetic_explicit_conversions(self, simple_index):
|
| 1023 |
+
# GH 8608
|
| 1024 |
+
# add/sub are overridden explicitly for Float/Int Index
|
| 1025 |
+
index_cls = type(simple_index)
|
| 1026 |
+
if index_cls is RangeIndex:
|
| 1027 |
+
idx = RangeIndex(5)
|
| 1028 |
+
else:
|
| 1029 |
+
idx = index_cls(np.arange(5, dtype="int64"))
|
| 1030 |
+
|
| 1031 |
+
# float conversions
|
| 1032 |
+
arr = np.arange(5, dtype="int64") * 3.2
|
| 1033 |
+
expected = Index(arr, dtype=np.float64)
|
| 1034 |
+
fidx = idx * 3.2
|
| 1035 |
+
tm.assert_index_equal(fidx, expected)
|
| 1036 |
+
fidx = 3.2 * idx
|
| 1037 |
+
tm.assert_index_equal(fidx, expected)
|
| 1038 |
+
|
| 1039 |
+
# interops with numpy arrays
|
| 1040 |
+
expected = Index(arr, dtype=np.float64)
|
| 1041 |
+
a = np.zeros(5, dtype="float64")
|
| 1042 |
+
result = fidx - a
|
| 1043 |
+
tm.assert_index_equal(result, expected)
|
| 1044 |
+
|
| 1045 |
+
expected = Index(-arr, dtype=np.float64)
|
| 1046 |
+
a = np.zeros(5, dtype="float64")
|
| 1047 |
+
result = a - fidx
|
| 1048 |
+
tm.assert_index_equal(result, expected)
|
| 1049 |
+
|
| 1050 |
+
@pytest.mark.parametrize("complex_dtype", [np.complex64, np.complex128])
|
| 1051 |
+
def test_astype_to_complex(self, complex_dtype, simple_index):
|
| 1052 |
+
result = simple_index.astype(complex_dtype)
|
| 1053 |
+
|
| 1054 |
+
assert type(result) is Index and result.dtype == complex_dtype
|
| 1055 |
+
|
| 1056 |
+
def test_cast_string(self, simple_index):
|
| 1057 |
+
if isinstance(simple_index, RangeIndex):
|
| 1058 |
+
pytest.skip("casting of strings not relevant for RangeIndex")
|
| 1059 |
+
result = type(simple_index)(["0", "1", "2"], dtype=simple_index.dtype)
|
| 1060 |
+
expected = type(simple_index)([0, 1, 2], dtype=simple_index.dtype)
|
| 1061 |
+
tm.assert_index_equal(result, expected)
|
omnilmm/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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
The tests in this package are to ensure the proper resultant dtypes of
|
| 3 |
+
set operations.
|
| 4 |
+
"""
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
import operator
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pytest
|
| 10 |
+
|
| 11 |
+
from pandas._libs import lib
|
| 12 |
+
|
| 13 |
+
from pandas.core.dtypes.cast import find_common_type
|
| 14 |
+
|
| 15 |
+
from pandas import (
|
| 16 |
+
CategoricalDtype,
|
| 17 |
+
CategoricalIndex,
|
| 18 |
+
DatetimeTZDtype,
|
| 19 |
+
Index,
|
| 20 |
+
MultiIndex,
|
| 21 |
+
PeriodDtype,
|
| 22 |
+
RangeIndex,
|
| 23 |
+
Series,
|
| 24 |
+
Timestamp,
|
| 25 |
+
)
|
| 26 |
+
import pandas._testing as tm
|
| 27 |
+
from pandas.api.types import (
|
| 28 |
+
is_signed_integer_dtype,
|
| 29 |
+
pandas_dtype,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def equal_contents(arr1, arr2) -> bool:
|
| 34 |
+
"""
|
| 35 |
+
Checks if the set of unique elements of arr1 and arr2 are equivalent.
|
| 36 |
+
"""
|
| 37 |
+
return frozenset(arr1) == frozenset(arr2)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@pytest.fixture(
|
| 41 |
+
params=tm.ALL_REAL_NUMPY_DTYPES
|
| 42 |
+
+ [
|
| 43 |
+
"object",
|
| 44 |
+
"category",
|
| 45 |
+
"datetime64[ns]",
|
| 46 |
+
"timedelta64[ns]",
|
| 47 |
+
]
|
| 48 |
+
)
|
| 49 |
+
def any_dtype_for_small_pos_integer_indexes(request):
|
| 50 |
+
"""
|
| 51 |
+
Dtypes that can be given to an Index with small positive integers.
|
| 52 |
+
|
| 53 |
+
This means that for any dtype `x` in the params list, `Index([1, 2, 3], dtype=x)` is
|
| 54 |
+
valid and gives the correct Index (sub-)class.
|
| 55 |
+
"""
|
| 56 |
+
return request.param
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def test_union_same_types(index):
|
| 60 |
+
# Union with a non-unique, non-monotonic index raises error
|
| 61 |
+
# Only needed for bool index factory
|
| 62 |
+
idx1 = index.sort_values()
|
| 63 |
+
idx2 = index.sort_values()
|
| 64 |
+
assert idx1.union(idx2).dtype == idx1.dtype
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def test_union_different_types(index_flat, index_flat2, request):
|
| 68 |
+
# This test only considers combinations of indices
|
| 69 |
+
# GH 23525
|
| 70 |
+
idx1 = index_flat
|
| 71 |
+
idx2 = index_flat2
|
| 72 |
+
|
| 73 |
+
if (
|
| 74 |
+
not idx1.is_unique
|
| 75 |
+
and not idx2.is_unique
|
| 76 |
+
and idx1.dtype.kind == "i"
|
| 77 |
+
and idx2.dtype.kind == "b"
|
| 78 |
+
) or (
|
| 79 |
+
not idx2.is_unique
|
| 80 |
+
and not idx1.is_unique
|
| 81 |
+
and idx2.dtype.kind == "i"
|
| 82 |
+
and idx1.dtype.kind == "b"
|
| 83 |
+
):
|
| 84 |
+
# Each condition had idx[1|2].is_monotonic_decreasing
|
| 85 |
+
# but failed when e.g.
|
| 86 |
+
# idx1 = Index(
|
| 87 |
+
# [True, True, True, True, True, True, True, True, False, False], dtype='bool'
|
| 88 |
+
# )
|
| 89 |
+
# idx2 = Index([0, 0, 1, 1, 2, 2], dtype='int64')
|
| 90 |
+
mark = pytest.mark.xfail(
|
| 91 |
+
reason="GH#44000 True==1", raises=ValueError, strict=False
|
| 92 |
+
)
|
| 93 |
+
request.applymarker(mark)
|
| 94 |
+
|
| 95 |
+
common_dtype = find_common_type([idx1.dtype, idx2.dtype])
|
| 96 |
+
|
| 97 |
+
warn = None
|
| 98 |
+
msg = "'<' not supported between"
|
| 99 |
+
if not len(idx1) or not len(idx2):
|
| 100 |
+
pass
|
| 101 |
+
elif (idx1.dtype.kind == "c" and (not lib.is_np_dtype(idx2.dtype, "iufc"))) or (
|
| 102 |
+
idx2.dtype.kind == "c" and (not lib.is_np_dtype(idx1.dtype, "iufc"))
|
| 103 |
+
):
|
| 104 |
+
# complex objects non-sortable
|
| 105 |
+
warn = RuntimeWarning
|
| 106 |
+
elif (
|
| 107 |
+
isinstance(idx1.dtype, PeriodDtype) and isinstance(idx2.dtype, CategoricalDtype)
|
| 108 |
+
) or (
|
| 109 |
+
isinstance(idx2.dtype, PeriodDtype) and isinstance(idx1.dtype, CategoricalDtype)
|
| 110 |
+
):
|
| 111 |
+
warn = FutureWarning
|
| 112 |
+
msg = r"PeriodDtype\[B\] is deprecated"
|
| 113 |
+
mark = pytest.mark.xfail(
|
| 114 |
+
reason="Warning not produced on all builds",
|
| 115 |
+
raises=AssertionError,
|
| 116 |
+
strict=False,
|
| 117 |
+
)
|
| 118 |
+
request.applymarker(mark)
|
| 119 |
+
|
| 120 |
+
any_uint64 = np.uint64 in (idx1.dtype, idx2.dtype)
|
| 121 |
+
idx1_signed = is_signed_integer_dtype(idx1.dtype)
|
| 122 |
+
idx2_signed = is_signed_integer_dtype(idx2.dtype)
|
| 123 |
+
|
| 124 |
+
# Union with a non-unique, non-monotonic index raises error
|
| 125 |
+
# This applies to the boolean index
|
| 126 |
+
idx1 = idx1.sort_values()
|
| 127 |
+
idx2 = idx2.sort_values()
|
| 128 |
+
|
| 129 |
+
with tm.assert_produces_warning(warn, match=msg):
|
| 130 |
+
res1 = idx1.union(idx2)
|
| 131 |
+
res2 = idx2.union(idx1)
|
| 132 |
+
|
| 133 |
+
if any_uint64 and (idx1_signed or idx2_signed):
|
| 134 |
+
assert res1.dtype == np.dtype("O")
|
| 135 |
+
assert res2.dtype == np.dtype("O")
|
| 136 |
+
else:
|
| 137 |
+
assert res1.dtype == common_dtype
|
| 138 |
+
assert res2.dtype == common_dtype
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
@pytest.mark.parametrize(
|
| 142 |
+
"idx1,idx2",
|
| 143 |
+
[
|
| 144 |
+
(Index(np.arange(5), dtype=np.int64), RangeIndex(5)),
|
| 145 |
+
(Index(np.arange(5), dtype=np.float64), Index(np.arange(5), dtype=np.int64)),
|
| 146 |
+
(Index(np.arange(5), dtype=np.float64), RangeIndex(5)),
|
| 147 |
+
(Index(np.arange(5), dtype=np.float64), Index(np.arange(5), dtype=np.uint64)),
|
| 148 |
+
],
|
| 149 |
+
)
|
| 150 |
+
def test_compatible_inconsistent_pairs(idx1, idx2):
|
| 151 |
+
# GH 23525
|
| 152 |
+
res1 = idx1.union(idx2)
|
| 153 |
+
res2 = idx2.union(idx1)
|
| 154 |
+
|
| 155 |
+
assert res1.dtype in (idx1.dtype, idx2.dtype)
|
| 156 |
+
assert res2.dtype in (idx1.dtype, idx2.dtype)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
@pytest.mark.parametrize(
|
| 160 |
+
"left, right, expected",
|
| 161 |
+
[
|
| 162 |
+
("int64", "int64", "int64"),
|
| 163 |
+
("int64", "uint64", "object"),
|
| 164 |
+
("int64", "float64", "float64"),
|
| 165 |
+
("uint64", "float64", "float64"),
|
| 166 |
+
("uint64", "uint64", "uint64"),
|
| 167 |
+
("float64", "float64", "float64"),
|
| 168 |
+
("datetime64[ns]", "int64", "object"),
|
| 169 |
+
("datetime64[ns]", "uint64", "object"),
|
| 170 |
+
("datetime64[ns]", "float64", "object"),
|
| 171 |
+
("datetime64[ns, CET]", "int64", "object"),
|
| 172 |
+
("datetime64[ns, CET]", "uint64", "object"),
|
| 173 |
+
("datetime64[ns, CET]", "float64", "object"),
|
| 174 |
+
("Period[D]", "int64", "object"),
|
| 175 |
+
("Period[D]", "uint64", "object"),
|
| 176 |
+
("Period[D]", "float64", "object"),
|
| 177 |
+
],
|
| 178 |
+
)
|
| 179 |
+
@pytest.mark.parametrize("names", [("foo", "foo", "foo"), ("foo", "bar", None)])
|
| 180 |
+
def test_union_dtypes(left, right, expected, names):
|
| 181 |
+
left = pandas_dtype(left)
|
| 182 |
+
right = pandas_dtype(right)
|
| 183 |
+
a = Index([], dtype=left, name=names[0])
|
| 184 |
+
b = Index([], dtype=right, name=names[1])
|
| 185 |
+
result = a.union(b)
|
| 186 |
+
assert result.dtype == expected
|
| 187 |
+
assert result.name == names[2]
|
| 188 |
+
|
| 189 |
+
# Testing name retention
|
| 190 |
+
# TODO: pin down desired dtype; do we want it to be commutative?
|
| 191 |
+
result = a.intersection(b)
|
| 192 |
+
assert result.name == names[2]
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
@pytest.mark.parametrize("values", [[1, 2, 2, 3], [3, 3]])
|
| 196 |
+
def test_intersection_duplicates(values):
|
| 197 |
+
# GH#31326
|
| 198 |
+
a = Index(values)
|
| 199 |
+
b = Index([3, 3])
|
| 200 |
+
result = a.intersection(b)
|
| 201 |
+
expected = Index([3])
|
| 202 |
+
tm.assert_index_equal(result, expected)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
class TestSetOps:
|
| 206 |
+
# Set operation tests shared by all indexes in the `index` fixture
|
| 207 |
+
@pytest.mark.parametrize("case", [0.5, "xxx"])
|
| 208 |
+
@pytest.mark.parametrize(
|
| 209 |
+
"method", ["intersection", "union", "difference", "symmetric_difference"]
|
| 210 |
+
)
|
| 211 |
+
def test_set_ops_error_cases(self, case, method, index):
|
| 212 |
+
# non-iterable input
|
| 213 |
+
msg = "Input must be Index or array-like"
|
| 214 |
+
with pytest.raises(TypeError, match=msg):
|
| 215 |
+
getattr(index, method)(case)
|
| 216 |
+
|
| 217 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
| 218 |
+
def test_intersection_base(self, index):
|
| 219 |
+
if isinstance(index, CategoricalIndex):
|
| 220 |
+
pytest.skip(f"Not relevant for {type(index).__name__}")
|
| 221 |
+
|
| 222 |
+
first = index[:5].unique()
|
| 223 |
+
second = index[:3].unique()
|
| 224 |
+
intersect = first.intersection(second)
|
| 225 |
+
tm.assert_index_equal(intersect, second)
|
| 226 |
+
|
| 227 |
+
if isinstance(index.dtype, DatetimeTZDtype):
|
| 228 |
+
# The second.values below will drop tz, so the rest of this test
|
| 229 |
+
# is not applicable.
|
| 230 |
+
return
|
| 231 |
+
|
| 232 |
+
# GH#10149
|
| 233 |
+
cases = [second.to_numpy(), second.to_series(), second.to_list()]
|
| 234 |
+
for case in cases:
|
| 235 |
+
result = first.intersection(case)
|
| 236 |
+
assert equal_contents(result, second)
|
| 237 |
+
|
| 238 |
+
if isinstance(index, MultiIndex):
|
| 239 |
+
msg = "other must be a MultiIndex or a list of tuples"
|
| 240 |
+
with pytest.raises(TypeError, match=msg):
|
| 241 |
+
first.intersection([1, 2, 3])
|
| 242 |
+
|
| 243 |
+
@pytest.mark.filterwarnings(
|
| 244 |
+
"ignore:Falling back on a non-pyarrow:pandas.errors.PerformanceWarning"
|
| 245 |
+
)
|
| 246 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
| 247 |
+
def test_union_base(self, index):
|
| 248 |
+
index = index.unique()
|
| 249 |
+
first = index[3:]
|
| 250 |
+
second = index[:5]
|
| 251 |
+
everything = index
|
| 252 |
+
|
| 253 |
+
union = first.union(second)
|
| 254 |
+
tm.assert_index_equal(union.sort_values(), everything.sort_values())
|
| 255 |
+
|
| 256 |
+
if isinstance(index.dtype, DatetimeTZDtype):
|
| 257 |
+
# The second.values below will drop tz, so the rest of this test
|
| 258 |
+
# is not applicable.
|
| 259 |
+
return
|
| 260 |
+
|
| 261 |
+
# GH#10149
|
| 262 |
+
cases = [second.to_numpy(), second.to_series(), second.to_list()]
|
| 263 |
+
for case in cases:
|
| 264 |
+
result = first.union(case)
|
| 265 |
+
assert equal_contents(result, everything)
|
| 266 |
+
|
| 267 |
+
if isinstance(index, MultiIndex):
|
| 268 |
+
msg = "other must be a MultiIndex or a list of tuples"
|
| 269 |
+
with pytest.raises(TypeError, match=msg):
|
| 270 |
+
first.union([1, 2, 3])
|
| 271 |
+
|
| 272 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
| 273 |
+
@pytest.mark.filterwarnings(
|
| 274 |
+
"ignore:Falling back on a non-pyarrow:pandas.errors.PerformanceWarning"
|
| 275 |
+
)
|
| 276 |
+
def test_difference_base(self, sort, index):
|
| 277 |
+
first = index[2:]
|
| 278 |
+
second = index[:4]
|
| 279 |
+
if index.inferred_type == "boolean":
|
| 280 |
+
# i think (TODO: be sure) there assumptions baked in about
|
| 281 |
+
# the index fixture that don't hold here?
|
| 282 |
+
answer = set(first).difference(set(second))
|
| 283 |
+
elif isinstance(index, CategoricalIndex):
|
| 284 |
+
answer = []
|
| 285 |
+
else:
|
| 286 |
+
answer = index[4:]
|
| 287 |
+
result = first.difference(second, sort)
|
| 288 |
+
assert equal_contents(result, answer)
|
| 289 |
+
|
| 290 |
+
# GH#10149
|
| 291 |
+
cases = [second.to_numpy(), second.to_series(), second.to_list()]
|
| 292 |
+
for case in cases:
|
| 293 |
+
result = first.difference(case, sort)
|
| 294 |
+
assert equal_contents(result, answer)
|
| 295 |
+
|
| 296 |
+
if isinstance(index, MultiIndex):
|
| 297 |
+
msg = "other must be a MultiIndex or a list of tuples"
|
| 298 |
+
with pytest.raises(TypeError, match=msg):
|
| 299 |
+
first.difference([1, 2, 3], sort)
|
| 300 |
+
|
| 301 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
| 302 |
+
@pytest.mark.filterwarnings(
|
| 303 |
+
"ignore:Falling back on a non-pyarrow:pandas.errors.PerformanceWarning"
|
| 304 |
+
)
|
| 305 |
+
def test_symmetric_difference(self, index):
|
| 306 |
+
if isinstance(index, CategoricalIndex):
|
| 307 |
+
pytest.skip(f"Not relevant for {type(index).__name__}")
|
| 308 |
+
if len(index) < 2:
|
| 309 |
+
pytest.skip("Too few values for test")
|
| 310 |
+
if index[0] in index[1:] or index[-1] in index[:-1]:
|
| 311 |
+
# index fixture has e.g. an index of bools that does not satisfy this,
|
| 312 |
+
# another with [0, 0, 1, 1, 2, 2]
|
| 313 |
+
pytest.skip("Index values no not satisfy test condition.")
|
| 314 |
+
|
| 315 |
+
first = index[1:]
|
| 316 |
+
second = index[:-1]
|
| 317 |
+
answer = index[[0, -1]]
|
| 318 |
+
result = first.symmetric_difference(second)
|
| 319 |
+
tm.assert_index_equal(result.sort_values(), answer.sort_values())
|
| 320 |
+
|
| 321 |
+
# GH#10149
|
| 322 |
+
cases = [second.to_numpy(), second.to_series(), second.to_list()]
|
| 323 |
+
for case in cases:
|
| 324 |
+
result = first.symmetric_difference(case)
|
| 325 |
+
assert equal_contents(result, answer)
|
| 326 |
+
|
| 327 |
+
if isinstance(index, MultiIndex):
|
| 328 |
+
msg = "other must be a MultiIndex or a list of tuples"
|
| 329 |
+
with pytest.raises(TypeError, match=msg):
|
| 330 |
+
first.symmetric_difference([1, 2, 3])
|
| 331 |
+
|
| 332 |
+
@pytest.mark.parametrize(
|
| 333 |
+
"fname, sname, expected_name",
|
| 334 |
+
[
|
| 335 |
+
("A", "A", "A"),
|
| 336 |
+
("A", "B", None),
|
| 337 |
+
("A", None, None),
|
| 338 |
+
(None, "B", None),
|
| 339 |
+
(None, None, None),
|
| 340 |
+
],
|
| 341 |
+
)
|
| 342 |
+
def test_corner_union(self, index_flat, fname, sname, expected_name):
|
| 343 |
+
# GH#9943, GH#9862
|
| 344 |
+
# Test unions with various name combinations
|
| 345 |
+
# Do not test MultiIndex or repeats
|
| 346 |
+
if not index_flat.is_unique:
|
| 347 |
+
index = index_flat.unique()
|
| 348 |
+
else:
|
| 349 |
+
index = index_flat
|
| 350 |
+
|
| 351 |
+
# Test copy.union(copy)
|
| 352 |
+
first = index.copy().set_names(fname)
|
| 353 |
+
second = index.copy().set_names(sname)
|
| 354 |
+
union = first.union(second)
|
| 355 |
+
expected = index.copy().set_names(expected_name)
|
| 356 |
+
tm.assert_index_equal(union, expected)
|
| 357 |
+
|
| 358 |
+
# Test copy.union(empty)
|
| 359 |
+
first = index.copy().set_names(fname)
|
| 360 |
+
second = index.drop(index).set_names(sname)
|
| 361 |
+
union = first.union(second)
|
| 362 |
+
expected = index.copy().set_names(expected_name)
|
| 363 |
+
tm.assert_index_equal(union, expected)
|
| 364 |
+
|
| 365 |
+
# Test empty.union(copy)
|
| 366 |
+
first = index.drop(index).set_names(fname)
|
| 367 |
+
second = index.copy().set_names(sname)
|
| 368 |
+
union = first.union(second)
|
| 369 |
+
expected = index.copy().set_names(expected_name)
|
| 370 |
+
tm.assert_index_equal(union, expected)
|
| 371 |
+
|
| 372 |
+
# Test empty.union(empty)
|
| 373 |
+
first = index.drop(index).set_names(fname)
|
| 374 |
+
second = index.drop(index).set_names(sname)
|
| 375 |
+
union = first.union(second)
|
| 376 |
+
expected = index.drop(index).set_names(expected_name)
|
| 377 |
+
tm.assert_index_equal(union, expected)
|
| 378 |
+
|
| 379 |
+
@pytest.mark.parametrize(
|
| 380 |
+
"fname, sname, expected_name",
|
| 381 |
+
[
|
| 382 |
+
("A", "A", "A"),
|
| 383 |
+
("A", "B", None),
|
| 384 |
+
("A", None, None),
|
| 385 |
+
(None, "B", None),
|
| 386 |
+
(None, None, None),
|
| 387 |
+
],
|
| 388 |
+
)
|
| 389 |
+
def test_union_unequal(self, index_flat, fname, sname, expected_name):
|
| 390 |
+
if not index_flat.is_unique:
|
| 391 |
+
index = index_flat.unique()
|
| 392 |
+
else:
|
| 393 |
+
index = index_flat
|
| 394 |
+
|
| 395 |
+
# test copy.union(subset) - need sort for unicode and string
|
| 396 |
+
first = index.copy().set_names(fname)
|
| 397 |
+
second = index[1:].set_names(sname)
|
| 398 |
+
union = first.union(second).sort_values()
|
| 399 |
+
expected = index.set_names(expected_name).sort_values()
|
| 400 |
+
tm.assert_index_equal(union, expected)
|
| 401 |
+
|
| 402 |
+
@pytest.mark.parametrize(
|
| 403 |
+
"fname, sname, expected_name",
|
| 404 |
+
[
|
| 405 |
+
("A", "A", "A"),
|
| 406 |
+
("A", "B", None),
|
| 407 |
+
("A", None, None),
|
| 408 |
+
(None, "B", None),
|
| 409 |
+
(None, None, None),
|
| 410 |
+
],
|
| 411 |
+
)
|
| 412 |
+
def test_corner_intersect(self, index_flat, fname, sname, expected_name):
|
| 413 |
+
# GH#35847
|
| 414 |
+
# Test intersections with various name combinations
|
| 415 |
+
if not index_flat.is_unique:
|
| 416 |
+
index = index_flat.unique()
|
| 417 |
+
else:
|
| 418 |
+
index = index_flat
|
| 419 |
+
|
| 420 |
+
# Test copy.intersection(copy)
|
| 421 |
+
first = index.copy().set_names(fname)
|
| 422 |
+
second = index.copy().set_names(sname)
|
| 423 |
+
intersect = first.intersection(second)
|
| 424 |
+
expected = index.copy().set_names(expected_name)
|
| 425 |
+
tm.assert_index_equal(intersect, expected)
|
| 426 |
+
|
| 427 |
+
# Test copy.intersection(empty)
|
| 428 |
+
first = index.copy().set_names(fname)
|
| 429 |
+
second = index.drop(index).set_names(sname)
|
| 430 |
+
intersect = first.intersection(second)
|
| 431 |
+
expected = index.drop(index).set_names(expected_name)
|
| 432 |
+
tm.assert_index_equal(intersect, expected)
|
| 433 |
+
|
| 434 |
+
# Test empty.intersection(copy)
|
| 435 |
+
first = index.drop(index).set_names(fname)
|
| 436 |
+
second = index.copy().set_names(sname)
|
| 437 |
+
intersect = first.intersection(second)
|
| 438 |
+
expected = index.drop(index).set_names(expected_name)
|
| 439 |
+
tm.assert_index_equal(intersect, expected)
|
| 440 |
+
|
| 441 |
+
# Test empty.intersection(empty)
|
| 442 |
+
first = index.drop(index).set_names(fname)
|
| 443 |
+
second = index.drop(index).set_names(sname)
|
| 444 |
+
intersect = first.intersection(second)
|
| 445 |
+
expected = index.drop(index).set_names(expected_name)
|
| 446 |
+
tm.assert_index_equal(intersect, expected)
|
| 447 |
+
|
| 448 |
+
@pytest.mark.parametrize(
|
| 449 |
+
"fname, sname, expected_name",
|
| 450 |
+
[
|
| 451 |
+
("A", "A", "A"),
|
| 452 |
+
("A", "B", None),
|
| 453 |
+
("A", None, None),
|
| 454 |
+
(None, "B", None),
|
| 455 |
+
(None, None, None),
|
| 456 |
+
],
|
| 457 |
+
)
|
| 458 |
+
def test_intersect_unequal(self, index_flat, fname, sname, expected_name):
|
| 459 |
+
if not index_flat.is_unique:
|
| 460 |
+
index = index_flat.unique()
|
| 461 |
+
else:
|
| 462 |
+
index = index_flat
|
| 463 |
+
|
| 464 |
+
# test copy.intersection(subset) - need sort for unicode and string
|
| 465 |
+
first = index.copy().set_names(fname)
|
| 466 |
+
second = index[1:].set_names(sname)
|
| 467 |
+
intersect = first.intersection(second).sort_values()
|
| 468 |
+
expected = index[1:].set_names(expected_name).sort_values()
|
| 469 |
+
tm.assert_index_equal(intersect, expected)
|
| 470 |
+
|
| 471 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
| 472 |
+
def test_intersection_name_retention_with_nameless(self, index):
|
| 473 |
+
if isinstance(index, MultiIndex):
|
| 474 |
+
index = index.rename(list(range(index.nlevels)))
|
| 475 |
+
else:
|
| 476 |
+
index = index.rename("foo")
|
| 477 |
+
|
| 478 |
+
other = np.asarray(index)
|
| 479 |
+
|
| 480 |
+
result = index.intersection(other)
|
| 481 |
+
assert result.name == index.name
|
| 482 |
+
|
| 483 |
+
# empty other, same dtype
|
| 484 |
+
result = index.intersection(other[:0])
|
| 485 |
+
assert result.name == index.name
|
| 486 |
+
|
| 487 |
+
# empty `self`
|
| 488 |
+
result = index[:0].intersection(other)
|
| 489 |
+
assert result.name == index.name
|
| 490 |
+
|
| 491 |
+
def test_difference_preserves_type_empty(self, index, sort):
|
| 492 |
+
# GH#20040
|
| 493 |
+
# If taking difference of a set and itself, it
|
| 494 |
+
# needs to preserve the type of the index
|
| 495 |
+
if not index.is_unique:
|
| 496 |
+
pytest.skip("Not relevant since index is not unique")
|
| 497 |
+
result = index.difference(index, sort=sort)
|
| 498 |
+
expected = index[:0]
|
| 499 |
+
tm.assert_index_equal(result, expected, exact=True)
|
| 500 |
+
|
| 501 |
+
def test_difference_name_retention_equals(self, index, names):
|
| 502 |
+
if isinstance(index, MultiIndex):
|
| 503 |
+
names = [[x] * index.nlevels for x in names]
|
| 504 |
+
index = index.rename(names[0])
|
| 505 |
+
other = index.rename(names[1])
|
| 506 |
+
|
| 507 |
+
assert index.equals(other)
|
| 508 |
+
|
| 509 |
+
result = index.difference(other)
|
| 510 |
+
expected = index[:0].rename(names[2])
|
| 511 |
+
tm.assert_index_equal(result, expected)
|
| 512 |
+
|
| 513 |
+
def test_intersection_difference_match_empty(self, index, sort):
|
| 514 |
+
# GH#20040
|
| 515 |
+
# Test that the intersection of an index with an
|
| 516 |
+
# empty index produces the same index as the difference
|
| 517 |
+
# of an index with itself. Test for all types
|
| 518 |
+
if not index.is_unique:
|
| 519 |
+
pytest.skip("Not relevant because index is not unique")
|
| 520 |
+
inter = index.intersection(index[:0])
|
| 521 |
+
diff = index.difference(index, sort=sort)
|
| 522 |
+
tm.assert_index_equal(inter, diff, exact=True)
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
|
| 526 |
+
@pytest.mark.filterwarnings(
|
| 527 |
+
"ignore:Falling back on a non-pyarrow:pandas.errors.PerformanceWarning"
|
| 528 |
+
)
|
| 529 |
+
@pytest.mark.parametrize(
|
| 530 |
+
"method", ["intersection", "union", "difference", "symmetric_difference"]
|
| 531 |
+
)
|
| 532 |
+
def test_setop_with_categorical(index_flat, sort, method):
|
| 533 |
+
# MultiIndex tested separately in tests.indexes.multi.test_setops
|
| 534 |
+
index = index_flat
|
| 535 |
+
|
| 536 |
+
other = index.astype("category")
|
| 537 |
+
exact = "equiv" if isinstance(index, RangeIndex) else True
|
| 538 |
+
|
| 539 |
+
result = getattr(index, method)(other, sort=sort)
|
| 540 |
+
expected = getattr(index, method)(index, sort=sort)
|
| 541 |
+
tm.assert_index_equal(result, expected, exact=exact)
|
| 542 |
+
|
| 543 |
+
result = getattr(index, method)(other[:5], sort=sort)
|
| 544 |
+
expected = getattr(index, method)(index[:5], sort=sort)
|
| 545 |
+
tm.assert_index_equal(result, expected, exact=exact)
|
| 546 |
+
|
| 547 |
+
|
| 548 |
+
def test_intersection_duplicates_all_indexes(index):
|
| 549 |
+
# GH#38743
|
| 550 |
+
if index.empty:
|
| 551 |
+
# No duplicates in empty indexes
|
| 552 |
+
pytest.skip("Not relevant for empty Index")
|
| 553 |
+
|
| 554 |
+
idx = index
|
| 555 |
+
idx_non_unique = idx[[0, 0, 1, 2]]
|
| 556 |
+
|
| 557 |
+
assert idx.intersection(idx_non_unique).equals(idx_non_unique.intersection(idx))
|
| 558 |
+
assert idx.intersection(idx_non_unique).is_unique
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
def test_union_duplicate_index_subsets_of_each_other(
|
| 562 |
+
any_dtype_for_small_pos_integer_indexes,
|
| 563 |
+
):
|
| 564 |
+
# GH#31326
|
| 565 |
+
dtype = any_dtype_for_small_pos_integer_indexes
|
| 566 |
+
a = Index([1, 2, 2, 3], dtype=dtype)
|
| 567 |
+
b = Index([3, 3, 4], dtype=dtype)
|
| 568 |
+
|
| 569 |
+
expected = Index([1, 2, 2, 3, 3, 4], dtype=dtype)
|
| 570 |
+
if isinstance(a, CategoricalIndex):
|
| 571 |
+
expected = Index([1, 2, 2, 3, 3, 4])
|
| 572 |
+
result = a.union(b)
|
| 573 |
+
tm.assert_index_equal(result, expected)
|
| 574 |
+
result = a.union(b, sort=False)
|
| 575 |
+
tm.assert_index_equal(result, expected)
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
def test_union_with_duplicate_index_and_non_monotonic(
|
| 579 |
+
any_dtype_for_small_pos_integer_indexes,
|
| 580 |
+
):
|
| 581 |
+
# GH#36289
|
| 582 |
+
dtype = any_dtype_for_small_pos_integer_indexes
|
| 583 |
+
a = Index([1, 0, 0], dtype=dtype)
|
| 584 |
+
b = Index([0, 1], dtype=dtype)
|
| 585 |
+
expected = Index([0, 0, 1], dtype=dtype)
|
| 586 |
+
|
| 587 |
+
result = a.union(b)
|
| 588 |
+
tm.assert_index_equal(result, expected)
|
| 589 |
+
|
| 590 |
+
result = b.union(a)
|
| 591 |
+
tm.assert_index_equal(result, expected)
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
def test_union_duplicate_index_different_dtypes():
|
| 595 |
+
# GH#36289
|
| 596 |
+
a = Index([1, 2, 2, 3])
|
| 597 |
+
b = Index(["1", "0", "0"])
|
| 598 |
+
expected = Index([1, 2, 2, 3, "1", "0", "0"])
|
| 599 |
+
result = a.union(b, sort=False)
|
| 600 |
+
tm.assert_index_equal(result, expected)
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
def test_union_same_value_duplicated_in_both():
|
| 604 |
+
# GH#36289
|
| 605 |
+
a = Index([0, 0, 1])
|
| 606 |
+
b = Index([0, 0, 1, 2])
|
| 607 |
+
result = a.union(b)
|
| 608 |
+
expected = Index([0, 0, 1, 2])
|
| 609 |
+
tm.assert_index_equal(result, expected)
|
| 610 |
+
|
| 611 |
+
|
| 612 |
+
@pytest.mark.parametrize("dup", [1, np.nan])
|
| 613 |
+
def test_union_nan_in_both(dup):
|
| 614 |
+
# GH#36289
|
| 615 |
+
a = Index([np.nan, 1, 2, 2])
|
| 616 |
+
b = Index([np.nan, dup, 1, 2])
|
| 617 |
+
result = a.union(b, sort=False)
|
| 618 |
+
expected = Index([np.nan, dup, 1.0, 2.0, 2.0])
|
| 619 |
+
tm.assert_index_equal(result, expected)
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
def test_union_rangeindex_sort_true():
|
| 623 |
+
# GH 53490
|
| 624 |
+
idx1 = RangeIndex(1, 100, 6)
|
| 625 |
+
idx2 = RangeIndex(1, 50, 3)
|
| 626 |
+
result = idx1.union(idx2, sort=True)
|
| 627 |
+
expected = Index(
|
| 628 |
+
[
|
| 629 |
+
1,
|
| 630 |
+
4,
|
| 631 |
+
7,
|
| 632 |
+
10,
|
| 633 |
+
13,
|
| 634 |
+
16,
|
| 635 |
+
19,
|
| 636 |
+
22,
|
| 637 |
+
25,
|
| 638 |
+
28,
|
| 639 |
+
31,
|
| 640 |
+
34,
|
| 641 |
+
37,
|
| 642 |
+
40,
|
| 643 |
+
43,
|
| 644 |
+
46,
|
| 645 |
+
49,
|
| 646 |
+
55,
|
| 647 |
+
61,
|
| 648 |
+
67,
|
| 649 |
+
73,
|
| 650 |
+
79,
|
| 651 |
+
85,
|
| 652 |
+
91,
|
| 653 |
+
97,
|
| 654 |
+
]
|
| 655 |
+
)
|
| 656 |
+
tm.assert_index_equal(result, expected)
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def test_union_with_duplicate_index_not_subset_and_non_monotonic(
|
| 660 |
+
any_dtype_for_small_pos_integer_indexes,
|
| 661 |
+
):
|
| 662 |
+
# GH#36289
|
| 663 |
+
dtype = any_dtype_for_small_pos_integer_indexes
|
| 664 |
+
a = Index([1, 0, 2], dtype=dtype)
|
| 665 |
+
b = Index([0, 0, 1], dtype=dtype)
|
| 666 |
+
expected = Index([0, 0, 1, 2], dtype=dtype)
|
| 667 |
+
if isinstance(a, CategoricalIndex):
|
| 668 |
+
expected = Index([0, 0, 1, 2])
|
| 669 |
+
|
| 670 |
+
result = a.union(b)
|
| 671 |
+
tm.assert_index_equal(result, expected)
|
| 672 |
+
|
| 673 |
+
result = b.union(a)
|
| 674 |
+
tm.assert_index_equal(result, expected)
|
| 675 |
+
|
| 676 |
+
|
| 677 |
+
def test_union_int_categorical_with_nan():
|
| 678 |
+
ci = CategoricalIndex([1, 2, np.nan])
|
| 679 |
+
assert ci.categories.dtype.kind == "i"
|
| 680 |
+
|
| 681 |
+
idx = Index([1, 2])
|
| 682 |
+
|
| 683 |
+
result = idx.union(ci)
|
| 684 |
+
expected = Index([1, 2, np.nan], dtype=np.float64)
|
| 685 |
+
tm.assert_index_equal(result, expected)
|
| 686 |
+
|
| 687 |
+
result = ci.union(idx)
|
| 688 |
+
tm.assert_index_equal(result, expected)
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
class TestSetOpsUnsorted:
|
| 692 |
+
# These may eventually belong in a dtype-specific test_setops, or
|
| 693 |
+
# parametrized over a more general fixture
|
| 694 |
+
def test_intersect_str_dates(self):
|
| 695 |
+
dt_dates = [datetime(2012, 2, 9), datetime(2012, 2, 22)]
|
| 696 |
+
|
| 697 |
+
index1 = Index(dt_dates, dtype=object)
|
| 698 |
+
index2 = Index(["aa"], dtype=object)
|
| 699 |
+
result = index2.intersection(index1)
|
| 700 |
+
|
| 701 |
+
expected = Index([], dtype=object)
|
| 702 |
+
tm.assert_index_equal(result, expected)
|
| 703 |
+
|
| 704 |
+
@pytest.mark.parametrize("index", ["string"], indirect=True)
|
| 705 |
+
def test_intersection(self, index, sort):
|
| 706 |
+
first = index[:20]
|
| 707 |
+
second = index[:10]
|
| 708 |
+
intersect = first.intersection(second, sort=sort)
|
| 709 |
+
if sort in (None, False):
|
| 710 |
+
tm.assert_index_equal(intersect.sort_values(), second.sort_values())
|
| 711 |
+
else:
|
| 712 |
+
tm.assert_index_equal(intersect, second)
|
| 713 |
+
|
| 714 |
+
# Corner cases
|
| 715 |
+
inter = first.intersection(first, sort=sort)
|
| 716 |
+
assert inter is first
|
| 717 |
+
|
| 718 |
+
@pytest.mark.parametrize(
|
| 719 |
+
"index2,keeps_name",
|
| 720 |
+
[
|
| 721 |
+
(Index([3, 4, 5, 6, 7], name="index"), True), # preserve same name
|
| 722 |
+
(Index([3, 4, 5, 6, 7], name="other"), False), # drop diff names
|
| 723 |
+
(Index([3, 4, 5, 6, 7]), False),
|
| 724 |
+
],
|
| 725 |
+
)
|
| 726 |
+
def test_intersection_name_preservation(self, index2, keeps_name, sort):
|
| 727 |
+
index1 = Index([1, 2, 3, 4, 5], name="index")
|
| 728 |
+
expected = Index([3, 4, 5])
|
| 729 |
+
result = index1.intersection(index2, sort)
|
| 730 |
+
|
| 731 |
+
if keeps_name:
|
| 732 |
+
expected.name = "index"
|
| 733 |
+
|
| 734 |
+
assert result.name == expected.name
|
| 735 |
+
tm.assert_index_equal(result, expected)
|
| 736 |
+
|
| 737 |
+
@pytest.mark.parametrize("index", ["string"], indirect=True)
|
| 738 |
+
@pytest.mark.parametrize(
|
| 739 |
+
"first_name,second_name,expected_name",
|
| 740 |
+
[("A", "A", "A"), ("A", "B", None), (None, "B", None)],
|
| 741 |
+
)
|
| 742 |
+
def test_intersection_name_preservation2(
|
| 743 |
+
self, index, first_name, second_name, expected_name, sort
|
| 744 |
+
):
|
| 745 |
+
first = index[5:20]
|
| 746 |
+
second = index[:10]
|
| 747 |
+
first.name = first_name
|
| 748 |
+
second.name = second_name
|
| 749 |
+
intersect = first.intersection(second, sort=sort)
|
| 750 |
+
assert intersect.name == expected_name
|
| 751 |
+
|
| 752 |
+
def test_chained_union(self, sort):
|
| 753 |
+
# Chained unions handles names correctly
|
| 754 |
+
i1 = Index([1, 2], name="i1")
|
| 755 |
+
i2 = Index([5, 6], name="i2")
|
| 756 |
+
i3 = Index([3, 4], name="i3")
|
| 757 |
+
union = i1.union(i2.union(i3, sort=sort), sort=sort)
|
| 758 |
+
expected = i1.union(i2, sort=sort).union(i3, sort=sort)
|
| 759 |
+
tm.assert_index_equal(union, expected)
|
| 760 |
+
|
| 761 |
+
j1 = Index([1, 2], name="j1")
|
| 762 |
+
j2 = Index([], name="j2")
|
| 763 |
+
j3 = Index([], name="j3")
|
| 764 |
+
union = j1.union(j2.union(j3, sort=sort), sort=sort)
|
| 765 |
+
expected = j1.union(j2, sort=sort).union(j3, sort=sort)
|
| 766 |
+
tm.assert_index_equal(union, expected)
|
| 767 |
+
|
| 768 |
+
@pytest.mark.parametrize("index", ["string"], indirect=True)
|
| 769 |
+
def test_union(self, index, sort):
|
| 770 |
+
first = index[5:20]
|
| 771 |
+
second = index[:10]
|
| 772 |
+
everything = index[:20]
|
| 773 |
+
|
| 774 |
+
union = first.union(second, sort=sort)
|
| 775 |
+
if sort in (None, False):
|
| 776 |
+
tm.assert_index_equal(union.sort_values(), everything.sort_values())
|
| 777 |
+
else:
|
| 778 |
+
tm.assert_index_equal(union, everything)
|
| 779 |
+
|
| 780 |
+
@pytest.mark.parametrize("klass", [np.array, Series, list])
|
| 781 |
+
@pytest.mark.parametrize("index", ["string"], indirect=True)
|
| 782 |
+
def test_union_from_iterables(self, index, klass, sort):
|
| 783 |
+
# GH#10149
|
| 784 |
+
first = index[5:20]
|
| 785 |
+
second = index[:10]
|
| 786 |
+
everything = index[:20]
|
| 787 |
+
|
| 788 |
+
case = klass(second.values)
|
| 789 |
+
result = first.union(case, sort=sort)
|
| 790 |
+
if sort in (None, False):
|
| 791 |
+
tm.assert_index_equal(result.sort_values(), everything.sort_values())
|
| 792 |
+
else:
|
| 793 |
+
tm.assert_index_equal(result, everything)
|
| 794 |
+
|
| 795 |
+
@pytest.mark.parametrize("index", ["string"], indirect=True)
|
| 796 |
+
def test_union_identity(self, index, sort):
|
| 797 |
+
first = index[5:20]
|
| 798 |
+
|
| 799 |
+
union = first.union(first, sort=sort)
|
| 800 |
+
# i.e. identity is not preserved when sort is True
|
| 801 |
+
assert (union is first) is (not sort)
|
| 802 |
+
|
| 803 |
+
# This should no longer be the same object, since [] is not consistent,
|
| 804 |
+
# both objects will be recast to dtype('O')
|
| 805 |
+
union = first.union(Index([], dtype=first.dtype), sort=sort)
|
| 806 |
+
assert (union is first) is (not sort)
|
| 807 |
+
|
| 808 |
+
union = Index([], dtype=first.dtype).union(first, sort=sort)
|
| 809 |
+
assert (union is first) is (not sort)
|
| 810 |
+
|
| 811 |
+
@pytest.mark.parametrize("index", ["string"], indirect=True)
|
| 812 |
+
@pytest.mark.parametrize("second_name,expected", [(None, None), ("name", "name")])
|
| 813 |
+
def test_difference_name_preservation(self, index, second_name, expected, sort):
|
| 814 |
+
first = index[5:20]
|
| 815 |
+
second = index[:10]
|
| 816 |
+
answer = index[10:20]
|
| 817 |
+
|
| 818 |
+
first.name = "name"
|
| 819 |
+
second.name = second_name
|
| 820 |
+
result = first.difference(second, sort=sort)
|
| 821 |
+
|
| 822 |
+
if sort is True:
|
| 823 |
+
tm.assert_index_equal(result, answer)
|
| 824 |
+
else:
|
| 825 |
+
answer.name = second_name
|
| 826 |
+
tm.assert_index_equal(result.sort_values(), answer.sort_values())
|
| 827 |
+
|
| 828 |
+
if expected is None:
|
| 829 |
+
assert result.name is None
|
| 830 |
+
else:
|
| 831 |
+
assert result.name == expected
|
| 832 |
+
|
| 833 |
+
def test_difference_empty_arg(self, index, sort):
|
| 834 |
+
first = index.copy()
|
| 835 |
+
first = first[5:20]
|
| 836 |
+
first.name = "name"
|
| 837 |
+
result = first.difference([], sort)
|
| 838 |
+
expected = index[5:20].unique()
|
| 839 |
+
expected.name = "name"
|
| 840 |
+
tm.assert_index_equal(result, expected)
|
| 841 |
+
|
| 842 |
+
def test_difference_should_not_compare(self):
|
| 843 |
+
# GH 55113
|
| 844 |
+
left = Index([1, 1])
|
| 845 |
+
right = Index([True])
|
| 846 |
+
result = left.difference(right)
|
| 847 |
+
expected = Index([1])
|
| 848 |
+
tm.assert_index_equal(result, expected)
|
| 849 |
+
|
| 850 |
+
@pytest.mark.parametrize("index", ["string"], indirect=True)
|
| 851 |
+
def test_difference_identity(self, index, sort):
|
| 852 |
+
first = index[5:20]
|
| 853 |
+
first.name = "name"
|
| 854 |
+
result = first.difference(first, sort)
|
| 855 |
+
|
| 856 |
+
assert len(result) == 0
|
| 857 |
+
assert result.name == first.name
|
| 858 |
+
|
| 859 |
+
@pytest.mark.parametrize("index", ["string"], indirect=True)
|
| 860 |
+
def test_difference_sort(self, index, sort):
|
| 861 |
+
first = index[5:20]
|
| 862 |
+
second = index[:10]
|
| 863 |
+
|
| 864 |
+
result = first.difference(second, sort)
|
| 865 |
+
expected = index[10:20]
|
| 866 |
+
|
| 867 |
+
if sort is None:
|
| 868 |
+
expected = expected.sort_values()
|
| 869 |
+
|
| 870 |
+
tm.assert_index_equal(result, expected)
|
| 871 |
+
|
| 872 |
+
@pytest.mark.parametrize("opname", ["difference", "symmetric_difference"])
|
| 873 |
+
def test_difference_incomparable(self, opname):
|
| 874 |
+
a = Index([3, Timestamp("2000"), 1])
|
| 875 |
+
b = Index([2, Timestamp("1999"), 1])
|
| 876 |
+
op = operator.methodcaller(opname, b)
|
| 877 |
+
|
| 878 |
+
with tm.assert_produces_warning(RuntimeWarning):
|
| 879 |
+
# sort=None, the default
|
| 880 |
+
result = op(a)
|
| 881 |
+
expected = Index([3, Timestamp("2000"), 2, Timestamp("1999")])
|
| 882 |
+
if opname == "difference":
|
| 883 |
+
expected = expected[:2]
|
| 884 |
+
tm.assert_index_equal(result, expected)
|
| 885 |
+
|
| 886 |
+
# sort=False
|
| 887 |
+
op = operator.methodcaller(opname, b, sort=False)
|
| 888 |
+
result = op(a)
|
| 889 |
+
tm.assert_index_equal(result, expected)
|
| 890 |
+
|
| 891 |
+
@pytest.mark.parametrize("opname", ["difference", "symmetric_difference"])
|
| 892 |
+
def test_difference_incomparable_true(self, opname):
|
| 893 |
+
a = Index([3, Timestamp("2000"), 1])
|
| 894 |
+
b = Index([2, Timestamp("1999"), 1])
|
| 895 |
+
op = operator.methodcaller(opname, b, sort=True)
|
| 896 |
+
|
| 897 |
+
msg = "'<' not supported between instances of 'Timestamp' and 'int'"
|
| 898 |
+
with pytest.raises(TypeError, match=msg):
|
| 899 |
+
op(a)
|
| 900 |
+
|
| 901 |
+
def test_symmetric_difference_mi(self, sort):
|
| 902 |
+
index1 = MultiIndex.from_tuples(zip(["foo", "bar", "baz"], [1, 2, 3]))
|
| 903 |
+
index2 = MultiIndex.from_tuples([("foo", 1), ("bar", 3)])
|
| 904 |
+
result = index1.symmetric_difference(index2, sort=sort)
|
| 905 |
+
expected = MultiIndex.from_tuples([("bar", 2), ("baz", 3), ("bar", 3)])
|
| 906 |
+
if sort is None:
|
| 907 |
+
expected = expected.sort_values()
|
| 908 |
+
tm.assert_index_equal(result, expected)
|
| 909 |
+
|
| 910 |
+
@pytest.mark.parametrize(
|
| 911 |
+
"index2,expected",
|
| 912 |
+
[
|
| 913 |
+
(Index([0, 1, np.nan]), Index([2.0, 3.0, 0.0])),
|
| 914 |
+
(Index([0, 1]), Index([np.nan, 2.0, 3.0, 0.0])),
|
| 915 |
+
],
|
| 916 |
+
)
|
| 917 |
+
def test_symmetric_difference_missing(self, index2, expected, sort):
|
| 918 |
+
# GH#13514 change: {nan} - {nan} == {}
|
| 919 |
+
# (GH#6444, sorting of nans, is no longer an issue)
|
| 920 |
+
index1 = Index([1, np.nan, 2, 3])
|
| 921 |
+
|
| 922 |
+
result = index1.symmetric_difference(index2, sort=sort)
|
| 923 |
+
if sort is None:
|
| 924 |
+
expected = expected.sort_values()
|
| 925 |
+
tm.assert_index_equal(result, expected)
|
| 926 |
+
|
| 927 |
+
def test_symmetric_difference_non_index(self, sort):
|
| 928 |
+
index1 = Index([1, 2, 3, 4], name="index1")
|
| 929 |
+
index2 = np.array([2, 3, 4, 5])
|
| 930 |
+
expected = Index([1, 5], name="index1")
|
| 931 |
+
result = index1.symmetric_difference(index2, sort=sort)
|
| 932 |
+
if sort in (None, True):
|
| 933 |
+
tm.assert_index_equal(result, expected)
|
| 934 |
+
else:
|
| 935 |
+
tm.assert_index_equal(result.sort_values(), expected)
|
| 936 |
+
assert result.name == "index1"
|
| 937 |
+
|
| 938 |
+
result = index1.symmetric_difference(index2, result_name="new_name", sort=sort)
|
| 939 |
+
expected.name = "new_name"
|
| 940 |
+
if sort in (None, True):
|
| 941 |
+
tm.assert_index_equal(result, expected)
|
| 942 |
+
else:
|
| 943 |
+
tm.assert_index_equal(result.sort_values(), expected)
|
| 944 |
+
assert result.name == "new_name"
|
| 945 |
+
|
| 946 |
+
def test_union_ea_dtypes(self, any_numeric_ea_and_arrow_dtype):
|
| 947 |
+
# GH#51365
|
| 948 |
+
idx = Index([1, 2, 3], dtype=any_numeric_ea_and_arrow_dtype)
|
| 949 |
+
idx2 = Index([3, 4, 5], dtype=any_numeric_ea_and_arrow_dtype)
|
| 950 |
+
result = idx.union(idx2)
|
| 951 |
+
expected = Index([1, 2, 3, 4, 5], dtype=any_numeric_ea_and_arrow_dtype)
|
| 952 |
+
tm.assert_index_equal(result, expected)
|
| 953 |
+
|
| 954 |
+
def test_union_string_array(self, any_string_dtype):
|
| 955 |
+
idx1 = Index(["a"], dtype=any_string_dtype)
|
| 956 |
+
idx2 = Index(["b"], dtype=any_string_dtype)
|
| 957 |
+
result = idx1.union(idx2)
|
| 958 |
+
expected = Index(["a", "b"], dtype=any_string_dtype)
|
| 959 |
+
tm.assert_index_equal(result, expected)
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/test_subclass.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests involving custom Index subclasses
|
| 3 |
+
"""
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
from pandas import (
|
| 7 |
+
DataFrame,
|
| 8 |
+
Index,
|
| 9 |
+
)
|
| 10 |
+
import pandas._testing as tm
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class CustomIndex(Index):
|
| 14 |
+
def __new__(cls, data, name=None):
|
| 15 |
+
# assert that this index class cannot hold strings
|
| 16 |
+
if any(isinstance(val, str) for val in data):
|
| 17 |
+
raise TypeError("CustomIndex cannot hold strings")
|
| 18 |
+
|
| 19 |
+
if name is None and hasattr(data, "name"):
|
| 20 |
+
name = data.name
|
| 21 |
+
data = np.array(data, dtype="O")
|
| 22 |
+
|
| 23 |
+
return cls._simple_new(data, name)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def test_insert_fallback_to_base_index():
|
| 27 |
+
# https://github.com/pandas-dev/pandas/issues/47071
|
| 28 |
+
|
| 29 |
+
idx = CustomIndex([1, 2, 3])
|
| 30 |
+
result = idx.insert(0, "string")
|
| 31 |
+
expected = Index(["string", 1, 2, 3], dtype=object)
|
| 32 |
+
tm.assert_index_equal(result, expected)
|
| 33 |
+
|
| 34 |
+
df = DataFrame(
|
| 35 |
+
np.random.default_rng(2).standard_normal((2, 3)),
|
| 36 |
+
columns=idx,
|
| 37 |
+
index=Index([1, 2], name="string"),
|
| 38 |
+
)
|
| 39 |
+
result = df.reset_index()
|
| 40 |
+
tm.assert_index_equal(result.columns, expected)
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__init__.py
ADDED
|
File without changes
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__pycache__/test_arithmetic.cpython-310.pyc
ADDED
|
Binary file (1.51 kB). View file
|
|
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__pycache__/test_delete.cpython-310.pyc
ADDED
|
Binary file (2.12 kB). View file
|
|
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__pycache__/test_indexing.cpython-310.pyc
ADDED
|
Binary file (11.6 kB). View file
|
|
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__pycache__/test_join.cpython-310.pyc
ADDED
|
Binary file (1.91 kB). View file
|
|
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__pycache__/test_ops.cpython-310.pyc
ADDED
|
Binary file (783 Bytes). View file
|
|
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__pycache__/test_pickle.cpython-310.pyc
ADDED
|
Binary file (745 Bytes). View file
|
|
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__pycache__/test_setops.cpython-310.pyc
ADDED
|
Binary file (7.09 kB). View file
|
|
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/__pycache__/test_timedelta_range.cpython-310.pyc
ADDED
|
Binary file (5.34 kB). View file
|
|
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/methods/__init__.py
ADDED
|
File without changes
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/methods/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (192 Bytes). View file
|
|
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/methods/__pycache__/test_factorize.cpython-310.pyc
ADDED
|
Binary file (1.53 kB). View file
|
|
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import timedelta
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
import pandas as pd
|
| 7 |
+
from pandas import (
|
| 8 |
+
Index,
|
| 9 |
+
NaT,
|
| 10 |
+
Timedelta,
|
| 11 |
+
TimedeltaIndex,
|
| 12 |
+
timedelta_range,
|
| 13 |
+
)
|
| 14 |
+
import pandas._testing as tm
|
| 15 |
+
from pandas.core.arrays import TimedeltaArray
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class TestTimedeltaIndex:
|
| 19 |
+
def test_astype_object(self):
|
| 20 |
+
idx = timedelta_range(start="1 days", periods=4, freq="D", name="idx")
|
| 21 |
+
expected_list = [
|
| 22 |
+
Timedelta("1 days"),
|
| 23 |
+
Timedelta("2 days"),
|
| 24 |
+
Timedelta("3 days"),
|
| 25 |
+
Timedelta("4 days"),
|
| 26 |
+
]
|
| 27 |
+
result = idx.astype(object)
|
| 28 |
+
expected = Index(expected_list, dtype=object, name="idx")
|
| 29 |
+
tm.assert_index_equal(result, expected)
|
| 30 |
+
assert idx.tolist() == expected_list
|
| 31 |
+
|
| 32 |
+
def test_astype_object_with_nat(self):
|
| 33 |
+
idx = TimedeltaIndex(
|
| 34 |
+
[timedelta(days=1), timedelta(days=2), NaT, timedelta(days=4)], name="idx"
|
| 35 |
+
)
|
| 36 |
+
expected_list = [
|
| 37 |
+
Timedelta("1 days"),
|
| 38 |
+
Timedelta("2 days"),
|
| 39 |
+
NaT,
|
| 40 |
+
Timedelta("4 days"),
|
| 41 |
+
]
|
| 42 |
+
result = idx.astype(object)
|
| 43 |
+
expected = Index(expected_list, dtype=object, name="idx")
|
| 44 |
+
tm.assert_index_equal(result, expected)
|
| 45 |
+
assert idx.tolist() == expected_list
|
| 46 |
+
|
| 47 |
+
def test_astype(self):
|
| 48 |
+
# GH 13149, GH 13209
|
| 49 |
+
idx = TimedeltaIndex([1e14, "NaT", NaT, np.nan], name="idx")
|
| 50 |
+
|
| 51 |
+
result = idx.astype(object)
|
| 52 |
+
expected = Index(
|
| 53 |
+
[Timedelta("1 days 03:46:40")] + [NaT] * 3, dtype=object, name="idx"
|
| 54 |
+
)
|
| 55 |
+
tm.assert_index_equal(result, expected)
|
| 56 |
+
|
| 57 |
+
result = idx.astype(np.int64)
|
| 58 |
+
expected = Index(
|
| 59 |
+
[100000000000000] + [-9223372036854775808] * 3, dtype=np.int64, name="idx"
|
| 60 |
+
)
|
| 61 |
+
tm.assert_index_equal(result, expected)
|
| 62 |
+
|
| 63 |
+
result = idx.astype(str)
|
| 64 |
+
expected = Index([str(x) for x in idx], name="idx", dtype=object)
|
| 65 |
+
tm.assert_index_equal(result, expected)
|
| 66 |
+
|
| 67 |
+
rng = timedelta_range("1 days", periods=10)
|
| 68 |
+
result = rng.astype("i8")
|
| 69 |
+
tm.assert_index_equal(result, Index(rng.asi8))
|
| 70 |
+
tm.assert_numpy_array_equal(rng.asi8, result.values)
|
| 71 |
+
|
| 72 |
+
def test_astype_uint(self):
|
| 73 |
+
arr = timedelta_range("1h", periods=2)
|
| 74 |
+
|
| 75 |
+
with pytest.raises(TypeError, match=r"Do obj.astype\('int64'\)"):
|
| 76 |
+
arr.astype("uint64")
|
| 77 |
+
with pytest.raises(TypeError, match=r"Do obj.astype\('int64'\)"):
|
| 78 |
+
arr.astype("uint32")
|
| 79 |
+
|
| 80 |
+
def test_astype_timedelta64(self):
|
| 81 |
+
# GH 13149, GH 13209
|
| 82 |
+
idx = TimedeltaIndex([1e14, "NaT", NaT, np.nan])
|
| 83 |
+
|
| 84 |
+
msg = (
|
| 85 |
+
r"Cannot convert from timedelta64\[ns\] to timedelta64. "
|
| 86 |
+
"Supported resolutions are 's', 'ms', 'us', 'ns'"
|
| 87 |
+
)
|
| 88 |
+
with pytest.raises(ValueError, match=msg):
|
| 89 |
+
idx.astype("timedelta64")
|
| 90 |
+
|
| 91 |
+
result = idx.astype("timedelta64[ns]")
|
| 92 |
+
tm.assert_index_equal(result, idx)
|
| 93 |
+
assert result is not idx
|
| 94 |
+
|
| 95 |
+
result = idx.astype("timedelta64[ns]", copy=False)
|
| 96 |
+
tm.assert_index_equal(result, idx)
|
| 97 |
+
assert result is idx
|
| 98 |
+
|
| 99 |
+
def test_astype_to_td64d_raises(self, index_or_series):
|
| 100 |
+
# We don't support "D" reso
|
| 101 |
+
scalar = Timedelta(days=31)
|
| 102 |
+
td = index_or_series(
|
| 103 |
+
[scalar, scalar, scalar + timedelta(minutes=5, seconds=3), NaT],
|
| 104 |
+
dtype="m8[ns]",
|
| 105 |
+
)
|
| 106 |
+
msg = (
|
| 107 |
+
r"Cannot convert from timedelta64\[ns\] to timedelta64\[D\]. "
|
| 108 |
+
"Supported resolutions are 's', 'ms', 'us', 'ns'"
|
| 109 |
+
)
|
| 110 |
+
with pytest.raises(ValueError, match=msg):
|
| 111 |
+
td.astype("timedelta64[D]")
|
| 112 |
+
|
| 113 |
+
def test_astype_ms_to_s(self, index_or_series):
|
| 114 |
+
scalar = Timedelta(days=31)
|
| 115 |
+
td = index_or_series(
|
| 116 |
+
[scalar, scalar, scalar + timedelta(minutes=5, seconds=3), NaT],
|
| 117 |
+
dtype="m8[ns]",
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
exp_values = np.asarray(td).astype("m8[s]")
|
| 121 |
+
exp_tda = TimedeltaArray._simple_new(exp_values, dtype=exp_values.dtype)
|
| 122 |
+
expected = index_or_series(exp_tda)
|
| 123 |
+
assert expected.dtype == "m8[s]"
|
| 124 |
+
result = td.astype("timedelta64[s]")
|
| 125 |
+
tm.assert_equal(result, expected)
|
| 126 |
+
|
| 127 |
+
def test_astype_freq_conversion(self):
|
| 128 |
+
# pre-2.0 td64 astype converted to float64. now for supported units
|
| 129 |
+
# (s, ms, us, ns) this converts to the requested dtype.
|
| 130 |
+
# This matches TDA and Series
|
| 131 |
+
tdi = timedelta_range("1 Day", periods=30)
|
| 132 |
+
|
| 133 |
+
res = tdi.astype("m8[s]")
|
| 134 |
+
exp_values = np.asarray(tdi).astype("m8[s]")
|
| 135 |
+
exp_tda = TimedeltaArray._simple_new(
|
| 136 |
+
exp_values, dtype=exp_values.dtype, freq=tdi.freq
|
| 137 |
+
)
|
| 138 |
+
expected = Index(exp_tda)
|
| 139 |
+
assert expected.dtype == "m8[s]"
|
| 140 |
+
tm.assert_index_equal(res, expected)
|
| 141 |
+
|
| 142 |
+
# check this matches Series and TimedeltaArray
|
| 143 |
+
res = tdi._data.astype("m8[s]")
|
| 144 |
+
tm.assert_equal(res, expected._values)
|
| 145 |
+
|
| 146 |
+
res = tdi.to_series().astype("m8[s]")
|
| 147 |
+
tm.assert_equal(res._values, expected._values._with_freq(None))
|
| 148 |
+
|
| 149 |
+
@pytest.mark.parametrize("dtype", [float, "datetime64", "datetime64[ns]"])
|
| 150 |
+
def test_astype_raises(self, dtype):
|
| 151 |
+
# GH 13149, GH 13209
|
| 152 |
+
idx = TimedeltaIndex([1e14, "NaT", NaT, np.nan])
|
| 153 |
+
msg = "Cannot cast TimedeltaIndex to dtype"
|
| 154 |
+
with pytest.raises(TypeError, match=msg):
|
| 155 |
+
idx.astype(dtype)
|
| 156 |
+
|
| 157 |
+
def test_astype_category(self):
|
| 158 |
+
obj = timedelta_range("1h", periods=2, freq="h")
|
| 159 |
+
|
| 160 |
+
result = obj.astype("category")
|
| 161 |
+
expected = pd.CategoricalIndex([Timedelta("1h"), Timedelta("2h")])
|
| 162 |
+
tm.assert_index_equal(result, expected)
|
| 163 |
+
|
| 164 |
+
result = obj._data.astype("category")
|
| 165 |
+
expected = expected.values
|
| 166 |
+
tm.assert_categorical_equal(result, expected)
|
| 167 |
+
|
| 168 |
+
def test_astype_array_fallback(self):
|
| 169 |
+
obj = timedelta_range("1h", periods=2)
|
| 170 |
+
result = obj.astype(bool)
|
| 171 |
+
expected = Index(np.array([True, True]))
|
| 172 |
+
tm.assert_index_equal(result, expected)
|
| 173 |
+
|
| 174 |
+
result = obj._data.astype(bool)
|
| 175 |
+
expected = np.array([True, True])
|
| 176 |
+
tm.assert_numpy_array_equal(result, expected)
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/methods/test_factorize.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
from pandas import (
|
| 4 |
+
TimedeltaIndex,
|
| 5 |
+
factorize,
|
| 6 |
+
timedelta_range,
|
| 7 |
+
)
|
| 8 |
+
import pandas._testing as tm
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class TestTimedeltaIndexFactorize:
|
| 12 |
+
def test_factorize(self):
|
| 13 |
+
idx1 = TimedeltaIndex(["1 day", "1 day", "2 day", "2 day", "3 day", "3 day"])
|
| 14 |
+
|
| 15 |
+
exp_arr = np.array([0, 0, 1, 1, 2, 2], dtype=np.intp)
|
| 16 |
+
exp_idx = TimedeltaIndex(["1 day", "2 day", "3 day"])
|
| 17 |
+
|
| 18 |
+
arr, idx = idx1.factorize()
|
| 19 |
+
tm.assert_numpy_array_equal(arr, exp_arr)
|
| 20 |
+
tm.assert_index_equal(idx, exp_idx)
|
| 21 |
+
assert idx.freq == exp_idx.freq
|
| 22 |
+
|
| 23 |
+
arr, idx = idx1.factorize(sort=True)
|
| 24 |
+
tm.assert_numpy_array_equal(arr, exp_arr)
|
| 25 |
+
tm.assert_index_equal(idx, exp_idx)
|
| 26 |
+
assert idx.freq == exp_idx.freq
|
| 27 |
+
|
| 28 |
+
def test_factorize_preserves_freq(self):
|
| 29 |
+
# GH#38120 freq should be preserved
|
| 30 |
+
idx3 = timedelta_range("1 day", periods=4, freq="s")
|
| 31 |
+
exp_arr = np.array([0, 1, 2, 3], dtype=np.intp)
|
| 32 |
+
arr, idx = idx3.factorize()
|
| 33 |
+
tm.assert_numpy_array_equal(arr, exp_arr)
|
| 34 |
+
tm.assert_index_equal(idx, idx3)
|
| 35 |
+
assert idx.freq == idx3.freq
|
| 36 |
+
|
| 37 |
+
arr, idx = factorize(idx3)
|
| 38 |
+
tm.assert_numpy_array_equal(arr, exp_arr)
|
| 39 |
+
tm.assert_index_equal(idx, idx3)
|
| 40 |
+
assert idx.freq == idx3.freq
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/methods/test_repeat.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
from pandas import (
|
| 4 |
+
TimedeltaIndex,
|
| 5 |
+
timedelta_range,
|
| 6 |
+
)
|
| 7 |
+
import pandas._testing as tm
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class TestRepeat:
|
| 11 |
+
def test_repeat(self):
|
| 12 |
+
index = timedelta_range("1 days", periods=2, freq="D")
|
| 13 |
+
exp = TimedeltaIndex(["1 days", "1 days", "2 days", "2 days"])
|
| 14 |
+
for res in [index.repeat(2), np.repeat(index, 2)]:
|
| 15 |
+
tm.assert_index_equal(res, exp)
|
| 16 |
+
assert res.freq is None
|
| 17 |
+
|
| 18 |
+
index = TimedeltaIndex(["1 days", "NaT", "3 days"])
|
| 19 |
+
exp = TimedeltaIndex(
|
| 20 |
+
[
|
| 21 |
+
"1 days",
|
| 22 |
+
"1 days",
|
| 23 |
+
"1 days",
|
| 24 |
+
"NaT",
|
| 25 |
+
"NaT",
|
| 26 |
+
"NaT",
|
| 27 |
+
"3 days",
|
| 28 |
+
"3 days",
|
| 29 |
+
"3 days",
|
| 30 |
+
]
|
| 31 |
+
)
|
| 32 |
+
for res in [index.repeat(3), np.repeat(index, 3)]:
|
| 33 |
+
tm.assert_index_equal(res, exp)
|
| 34 |
+
assert res.freq is None
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_arithmetic.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Arithmetic tests for TimedeltaIndex are generally about the result's `freq` attribute.
|
| 2 |
+
# Other cases can be shared in tests.arithmetic.test_timedelta64
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
from pandas import (
|
| 6 |
+
NaT,
|
| 7 |
+
Timedelta,
|
| 8 |
+
timedelta_range,
|
| 9 |
+
)
|
| 10 |
+
import pandas._testing as tm
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class TestTimedeltaIndexArithmetic:
|
| 14 |
+
def test_arithmetic_zero_freq(self):
|
| 15 |
+
# GH#51575 don't get a .freq with freq.n = 0
|
| 16 |
+
tdi = timedelta_range(0, periods=100, freq="ns")
|
| 17 |
+
result = tdi / 2
|
| 18 |
+
assert result.freq is None
|
| 19 |
+
expected = tdi[:50].repeat(2)
|
| 20 |
+
tm.assert_index_equal(result, expected)
|
| 21 |
+
|
| 22 |
+
result2 = tdi // 2
|
| 23 |
+
assert result2.freq is None
|
| 24 |
+
expected2 = expected
|
| 25 |
+
tm.assert_index_equal(result2, expected2)
|
| 26 |
+
|
| 27 |
+
result3 = tdi * 0
|
| 28 |
+
assert result3.freq is None
|
| 29 |
+
expected3 = tdi[:1].repeat(100)
|
| 30 |
+
tm.assert_index_equal(result3, expected3)
|
| 31 |
+
|
| 32 |
+
def test_tdi_division(self, index_or_series):
|
| 33 |
+
# doc example
|
| 34 |
+
|
| 35 |
+
scalar = Timedelta(days=31)
|
| 36 |
+
td = index_or_series(
|
| 37 |
+
[scalar, scalar, scalar + Timedelta(minutes=5, seconds=3), NaT],
|
| 38 |
+
dtype="m8[ns]",
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
result = td / np.timedelta64(1, "D")
|
| 42 |
+
expected = index_or_series(
|
| 43 |
+
[31, 31, (31 * 86400 + 5 * 60 + 3) / 86400.0, np.nan]
|
| 44 |
+
)
|
| 45 |
+
tm.assert_equal(result, expected)
|
| 46 |
+
|
| 47 |
+
result = td / np.timedelta64(1, "s")
|
| 48 |
+
expected = index_or_series(
|
| 49 |
+
[31 * 86400, 31 * 86400, 31 * 86400 + 5 * 60 + 3, np.nan]
|
| 50 |
+
)
|
| 51 |
+
tm.assert_equal(result, expected)
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_constructors.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import timedelta
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
import pandas as pd
|
| 7 |
+
from pandas import (
|
| 8 |
+
Timedelta,
|
| 9 |
+
TimedeltaIndex,
|
| 10 |
+
timedelta_range,
|
| 11 |
+
to_timedelta,
|
| 12 |
+
)
|
| 13 |
+
import pandas._testing as tm
|
| 14 |
+
from pandas.core.arrays.timedeltas import TimedeltaArray
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class TestTimedeltaIndex:
|
| 18 |
+
def test_closed_deprecated(self):
|
| 19 |
+
# GH#52628
|
| 20 |
+
msg = "The 'closed' keyword"
|
| 21 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 22 |
+
TimedeltaIndex([], closed=True)
|
| 23 |
+
|
| 24 |
+
def test_array_of_dt64_nat_raises(self):
|
| 25 |
+
# GH#39462
|
| 26 |
+
nat = np.datetime64("NaT", "ns")
|
| 27 |
+
arr = np.array([nat], dtype=object)
|
| 28 |
+
|
| 29 |
+
msg = "Invalid type for timedelta scalar"
|
| 30 |
+
with pytest.raises(TypeError, match=msg):
|
| 31 |
+
TimedeltaIndex(arr)
|
| 32 |
+
|
| 33 |
+
with pytest.raises(TypeError, match=msg):
|
| 34 |
+
TimedeltaArray._from_sequence(arr, dtype="m8[ns]")
|
| 35 |
+
|
| 36 |
+
with pytest.raises(TypeError, match=msg):
|
| 37 |
+
to_timedelta(arr)
|
| 38 |
+
|
| 39 |
+
@pytest.mark.parametrize("unit", ["Y", "y", "M"])
|
| 40 |
+
def test_unit_m_y_raises(self, unit):
|
| 41 |
+
msg = "Units 'M', 'Y', and 'y' are no longer supported"
|
| 42 |
+
depr_msg = "The 'unit' keyword in TimedeltaIndex construction is deprecated"
|
| 43 |
+
with pytest.raises(ValueError, match=msg):
|
| 44 |
+
with tm.assert_produces_warning(FutureWarning, match=depr_msg):
|
| 45 |
+
TimedeltaIndex([1, 3, 7], unit)
|
| 46 |
+
|
| 47 |
+
def test_int64_nocopy(self):
|
| 48 |
+
# GH#23539 check that a copy isn't made when we pass int64 data
|
| 49 |
+
# and copy=False
|
| 50 |
+
arr = np.arange(10, dtype=np.int64)
|
| 51 |
+
tdi = TimedeltaIndex(arr, copy=False)
|
| 52 |
+
assert tdi._data._ndarray.base is arr
|
| 53 |
+
|
| 54 |
+
def test_infer_from_tdi(self):
|
| 55 |
+
# GH#23539
|
| 56 |
+
# fast-path for inferring a frequency if the passed data already
|
| 57 |
+
# has one
|
| 58 |
+
tdi = timedelta_range("1 second", periods=10**7, freq="1s")
|
| 59 |
+
|
| 60 |
+
result = TimedeltaIndex(tdi, freq="infer")
|
| 61 |
+
assert result.freq == tdi.freq
|
| 62 |
+
|
| 63 |
+
# check that inferred_freq was not called by checking that the
|
| 64 |
+
# value has not been cached
|
| 65 |
+
assert "inferred_freq" not in getattr(result, "_cache", {})
|
| 66 |
+
|
| 67 |
+
def test_infer_from_tdi_mismatch(self):
|
| 68 |
+
# GH#23539
|
| 69 |
+
# fast-path for invalidating a frequency if the passed data already
|
| 70 |
+
# has one and it does not match the `freq` input
|
| 71 |
+
tdi = timedelta_range("1 second", periods=100, freq="1s")
|
| 72 |
+
|
| 73 |
+
depr_msg = "TimedeltaArray.__init__ is deprecated"
|
| 74 |
+
msg = (
|
| 75 |
+
"Inferred frequency .* from passed values does "
|
| 76 |
+
"not conform to passed frequency"
|
| 77 |
+
)
|
| 78 |
+
with pytest.raises(ValueError, match=msg):
|
| 79 |
+
TimedeltaIndex(tdi, freq="D")
|
| 80 |
+
|
| 81 |
+
with pytest.raises(ValueError, match=msg):
|
| 82 |
+
# GH#23789
|
| 83 |
+
with tm.assert_produces_warning(FutureWarning, match=depr_msg):
|
| 84 |
+
TimedeltaArray(tdi, freq="D")
|
| 85 |
+
|
| 86 |
+
with pytest.raises(ValueError, match=msg):
|
| 87 |
+
TimedeltaIndex(tdi._data, freq="D")
|
| 88 |
+
|
| 89 |
+
with pytest.raises(ValueError, match=msg):
|
| 90 |
+
with tm.assert_produces_warning(FutureWarning, match=depr_msg):
|
| 91 |
+
TimedeltaArray(tdi._data, freq="D")
|
| 92 |
+
|
| 93 |
+
def test_dt64_data_invalid(self):
|
| 94 |
+
# GH#23539
|
| 95 |
+
# passing tz-aware DatetimeIndex raises, naive or ndarray[datetime64]
|
| 96 |
+
# raise as of GH#29794
|
| 97 |
+
dti = pd.date_range("2016-01-01", periods=3)
|
| 98 |
+
|
| 99 |
+
msg = "cannot be converted to timedelta64"
|
| 100 |
+
with pytest.raises(TypeError, match=msg):
|
| 101 |
+
TimedeltaIndex(dti.tz_localize("Europe/Brussels"))
|
| 102 |
+
|
| 103 |
+
with pytest.raises(TypeError, match=msg):
|
| 104 |
+
TimedeltaIndex(dti)
|
| 105 |
+
|
| 106 |
+
with pytest.raises(TypeError, match=msg):
|
| 107 |
+
TimedeltaIndex(np.asarray(dti))
|
| 108 |
+
|
| 109 |
+
def test_float64_ns_rounded(self):
|
| 110 |
+
# GH#23539 without specifying a unit, floats are regarded as nanos,
|
| 111 |
+
# and fractional portions are truncated
|
| 112 |
+
tdi = TimedeltaIndex([2.3, 9.7])
|
| 113 |
+
expected = TimedeltaIndex([2, 9])
|
| 114 |
+
tm.assert_index_equal(tdi, expected)
|
| 115 |
+
|
| 116 |
+
# integral floats are non-lossy
|
| 117 |
+
tdi = TimedeltaIndex([2.0, 9.0])
|
| 118 |
+
expected = TimedeltaIndex([2, 9])
|
| 119 |
+
tm.assert_index_equal(tdi, expected)
|
| 120 |
+
|
| 121 |
+
# NaNs get converted to NaT
|
| 122 |
+
tdi = TimedeltaIndex([2.0, np.nan])
|
| 123 |
+
expected = TimedeltaIndex([Timedelta(nanoseconds=2), pd.NaT])
|
| 124 |
+
tm.assert_index_equal(tdi, expected)
|
| 125 |
+
|
| 126 |
+
def test_float64_unit_conversion(self):
|
| 127 |
+
# GH#23539
|
| 128 |
+
tdi = to_timedelta([1.5, 2.25], unit="D")
|
| 129 |
+
expected = TimedeltaIndex([Timedelta(days=1.5), Timedelta(days=2.25)])
|
| 130 |
+
tm.assert_index_equal(tdi, expected)
|
| 131 |
+
|
| 132 |
+
def test_construction_base_constructor(self):
|
| 133 |
+
arr = [Timedelta("1 days"), pd.NaT, Timedelta("3 days")]
|
| 134 |
+
tm.assert_index_equal(pd.Index(arr), TimedeltaIndex(arr))
|
| 135 |
+
tm.assert_index_equal(pd.Index(np.array(arr)), TimedeltaIndex(np.array(arr)))
|
| 136 |
+
|
| 137 |
+
arr = [np.nan, pd.NaT, Timedelta("1 days")]
|
| 138 |
+
tm.assert_index_equal(pd.Index(arr), TimedeltaIndex(arr))
|
| 139 |
+
tm.assert_index_equal(pd.Index(np.array(arr)), TimedeltaIndex(np.array(arr)))
|
| 140 |
+
|
| 141 |
+
@pytest.mark.filterwarnings(
|
| 142 |
+
"ignore:The 'unit' keyword in TimedeltaIndex construction:FutureWarning"
|
| 143 |
+
)
|
| 144 |
+
def test_constructor(self):
|
| 145 |
+
expected = TimedeltaIndex(
|
| 146 |
+
[
|
| 147 |
+
"1 days",
|
| 148 |
+
"1 days 00:00:05",
|
| 149 |
+
"2 days",
|
| 150 |
+
"2 days 00:00:02",
|
| 151 |
+
"0 days 00:00:03",
|
| 152 |
+
]
|
| 153 |
+
)
|
| 154 |
+
result = TimedeltaIndex(
|
| 155 |
+
[
|
| 156 |
+
"1 days",
|
| 157 |
+
"1 days, 00:00:05",
|
| 158 |
+
np.timedelta64(2, "D"),
|
| 159 |
+
timedelta(days=2, seconds=2),
|
| 160 |
+
pd.offsets.Second(3),
|
| 161 |
+
]
|
| 162 |
+
)
|
| 163 |
+
tm.assert_index_equal(result, expected)
|
| 164 |
+
|
| 165 |
+
expected = TimedeltaIndex(
|
| 166 |
+
["0 days 00:00:00", "0 days 00:00:01", "0 days 00:00:02"]
|
| 167 |
+
)
|
| 168 |
+
result = TimedeltaIndex(range(3), unit="s")
|
| 169 |
+
tm.assert_index_equal(result, expected)
|
| 170 |
+
expected = TimedeltaIndex(
|
| 171 |
+
["0 days 00:00:00", "0 days 00:00:05", "0 days 00:00:09"]
|
| 172 |
+
)
|
| 173 |
+
result = TimedeltaIndex([0, 5, 9], unit="s")
|
| 174 |
+
tm.assert_index_equal(result, expected)
|
| 175 |
+
expected = TimedeltaIndex(
|
| 176 |
+
["0 days 00:00:00.400", "0 days 00:00:00.450", "0 days 00:00:01.200"]
|
| 177 |
+
)
|
| 178 |
+
result = TimedeltaIndex([400, 450, 1200], unit="ms")
|
| 179 |
+
tm.assert_index_equal(result, expected)
|
| 180 |
+
|
| 181 |
+
def test_constructor_iso(self):
|
| 182 |
+
# GH #21877
|
| 183 |
+
expected = timedelta_range("1s", periods=9, freq="s")
|
| 184 |
+
durations = [f"P0DT0H0M{i}S" for i in range(1, 10)]
|
| 185 |
+
result = to_timedelta(durations)
|
| 186 |
+
tm.assert_index_equal(result, expected)
|
| 187 |
+
|
| 188 |
+
def test_timedelta_range_fractional_period(self):
|
| 189 |
+
msg = "Non-integer 'periods' in pd.date_range, pd.timedelta_range"
|
| 190 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 191 |
+
rng = timedelta_range("1 days", periods=10.5)
|
| 192 |
+
exp = timedelta_range("1 days", periods=10)
|
| 193 |
+
tm.assert_index_equal(rng, exp)
|
| 194 |
+
|
| 195 |
+
def test_constructor_coverage(self):
|
| 196 |
+
msg = "periods must be a number, got foo"
|
| 197 |
+
with pytest.raises(TypeError, match=msg):
|
| 198 |
+
timedelta_range(start="1 days", periods="foo", freq="D")
|
| 199 |
+
|
| 200 |
+
msg = (
|
| 201 |
+
r"TimedeltaIndex\(\.\.\.\) must be called with a collection of some kind, "
|
| 202 |
+
"'1 days' was passed"
|
| 203 |
+
)
|
| 204 |
+
with pytest.raises(TypeError, match=msg):
|
| 205 |
+
TimedeltaIndex("1 days")
|
| 206 |
+
|
| 207 |
+
# generator expression
|
| 208 |
+
gen = (timedelta(i) for i in range(10))
|
| 209 |
+
result = TimedeltaIndex(gen)
|
| 210 |
+
expected = TimedeltaIndex([timedelta(i) for i in range(10)])
|
| 211 |
+
tm.assert_index_equal(result, expected)
|
| 212 |
+
|
| 213 |
+
# NumPy string array
|
| 214 |
+
strings = np.array(["1 days", "2 days", "3 days"])
|
| 215 |
+
result = TimedeltaIndex(strings)
|
| 216 |
+
expected = to_timedelta([1, 2, 3], unit="d")
|
| 217 |
+
tm.assert_index_equal(result, expected)
|
| 218 |
+
|
| 219 |
+
from_ints = TimedeltaIndex(expected.asi8)
|
| 220 |
+
tm.assert_index_equal(from_ints, expected)
|
| 221 |
+
|
| 222 |
+
# non-conforming freq
|
| 223 |
+
msg = (
|
| 224 |
+
"Inferred frequency None from passed values does not conform to "
|
| 225 |
+
"passed frequency D"
|
| 226 |
+
)
|
| 227 |
+
with pytest.raises(ValueError, match=msg):
|
| 228 |
+
TimedeltaIndex(["1 days", "2 days", "4 days"], freq="D")
|
| 229 |
+
|
| 230 |
+
msg = (
|
| 231 |
+
"Of the four parameters: start, end, periods, and freq, exactly "
|
| 232 |
+
"three must be specified"
|
| 233 |
+
)
|
| 234 |
+
with pytest.raises(ValueError, match=msg):
|
| 235 |
+
timedelta_range(periods=10, freq="D")
|
| 236 |
+
|
| 237 |
+
def test_constructor_name(self):
|
| 238 |
+
idx = timedelta_range(start="1 days", periods=1, freq="D", name="TEST")
|
| 239 |
+
assert idx.name == "TEST"
|
| 240 |
+
|
| 241 |
+
# GH10025
|
| 242 |
+
idx2 = TimedeltaIndex(idx, name="something else")
|
| 243 |
+
assert idx2.name == "something else"
|
| 244 |
+
|
| 245 |
+
def test_constructor_no_precision_raises(self):
|
| 246 |
+
# GH-24753, GH-24739
|
| 247 |
+
|
| 248 |
+
msg = "with no precision is not allowed"
|
| 249 |
+
with pytest.raises(ValueError, match=msg):
|
| 250 |
+
TimedeltaIndex(["2000"], dtype="timedelta64")
|
| 251 |
+
|
| 252 |
+
msg = "The 'timedelta64' dtype has no unit. Please pass in"
|
| 253 |
+
with pytest.raises(ValueError, match=msg):
|
| 254 |
+
pd.Index(["2000"], dtype="timedelta64")
|
| 255 |
+
|
| 256 |
+
def test_constructor_wrong_precision_raises(self):
|
| 257 |
+
msg = "Supported timedelta64 resolutions are 's', 'ms', 'us', 'ns'"
|
| 258 |
+
with pytest.raises(ValueError, match=msg):
|
| 259 |
+
TimedeltaIndex(["2000"], dtype="timedelta64[D]")
|
| 260 |
+
|
| 261 |
+
# "timedelta64[us]" was unsupported pre-2.0, but now this works.
|
| 262 |
+
tdi = TimedeltaIndex(["2000"], dtype="timedelta64[us]")
|
| 263 |
+
assert tdi.dtype == "m8[us]"
|
| 264 |
+
|
| 265 |
+
def test_explicit_none_freq(self):
|
| 266 |
+
# Explicitly passing freq=None is respected
|
| 267 |
+
tdi = timedelta_range(1, periods=5)
|
| 268 |
+
assert tdi.freq is not None
|
| 269 |
+
|
| 270 |
+
result = TimedeltaIndex(tdi, freq=None)
|
| 271 |
+
assert result.freq is None
|
| 272 |
+
|
| 273 |
+
result = TimedeltaIndex(tdi._data, freq=None)
|
| 274 |
+
assert result.freq is None
|
| 275 |
+
|
| 276 |
+
msg = "TimedeltaArray.__init__ is deprecated"
|
| 277 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 278 |
+
tda = TimedeltaArray(tdi, freq=None)
|
| 279 |
+
assert tda.freq is None
|
| 280 |
+
|
| 281 |
+
def test_from_categorical(self):
|
| 282 |
+
tdi = timedelta_range(1, periods=5)
|
| 283 |
+
|
| 284 |
+
cat = pd.Categorical(tdi)
|
| 285 |
+
|
| 286 |
+
result = TimedeltaIndex(cat)
|
| 287 |
+
tm.assert_index_equal(result, tdi)
|
| 288 |
+
|
| 289 |
+
ci = pd.CategoricalIndex(tdi)
|
| 290 |
+
result = TimedeltaIndex(ci)
|
| 291 |
+
tm.assert_index_equal(result, tdi)
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_delete.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pandas import (
|
| 2 |
+
TimedeltaIndex,
|
| 3 |
+
timedelta_range,
|
| 4 |
+
)
|
| 5 |
+
import pandas._testing as tm
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class TestTimedeltaIndexDelete:
|
| 9 |
+
def test_delete(self):
|
| 10 |
+
idx = timedelta_range(start="1 Days", periods=5, freq="D", name="idx")
|
| 11 |
+
|
| 12 |
+
# preserve freq
|
| 13 |
+
expected_0 = timedelta_range(start="2 Days", periods=4, freq="D", name="idx")
|
| 14 |
+
expected_4 = timedelta_range(start="1 Days", periods=4, freq="D", name="idx")
|
| 15 |
+
|
| 16 |
+
# reset freq to None
|
| 17 |
+
expected_1 = TimedeltaIndex(
|
| 18 |
+
["1 day", "3 day", "4 day", "5 day"], freq=None, name="idx"
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
cases = {
|
| 22 |
+
0: expected_0,
|
| 23 |
+
-5: expected_0,
|
| 24 |
+
-1: expected_4,
|
| 25 |
+
4: expected_4,
|
| 26 |
+
1: expected_1,
|
| 27 |
+
}
|
| 28 |
+
for n, expected in cases.items():
|
| 29 |
+
result = idx.delete(n)
|
| 30 |
+
tm.assert_index_equal(result, expected)
|
| 31 |
+
assert result.name == expected.name
|
| 32 |
+
assert result.freq == expected.freq
|
| 33 |
+
|
| 34 |
+
with tm.external_error_raised((IndexError, ValueError)):
|
| 35 |
+
# either depending on numpy version
|
| 36 |
+
idx.delete(5)
|
| 37 |
+
|
| 38 |
+
def test_delete_slice(self):
|
| 39 |
+
idx = timedelta_range(start="1 days", periods=10, freq="D", name="idx")
|
| 40 |
+
|
| 41 |
+
# preserve freq
|
| 42 |
+
expected_0_2 = timedelta_range(start="4 days", periods=7, freq="D", name="idx")
|
| 43 |
+
expected_7_9 = timedelta_range(start="1 days", periods=7, freq="D", name="idx")
|
| 44 |
+
|
| 45 |
+
# reset freq to None
|
| 46 |
+
expected_3_5 = TimedeltaIndex(
|
| 47 |
+
["1 d", "2 d", "3 d", "7 d", "8 d", "9 d", "10d"], freq=None, name="idx"
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
cases = {
|
| 51 |
+
(0, 1, 2): expected_0_2,
|
| 52 |
+
(7, 8, 9): expected_7_9,
|
| 53 |
+
(3, 4, 5): expected_3_5,
|
| 54 |
+
}
|
| 55 |
+
for n, expected in cases.items():
|
| 56 |
+
result = idx.delete(n)
|
| 57 |
+
tm.assert_index_equal(result, expected)
|
| 58 |
+
assert result.name == expected.name
|
| 59 |
+
assert result.freq == expected.freq
|
| 60 |
+
|
| 61 |
+
result = idx.delete(slice(n[0], n[-1] + 1))
|
| 62 |
+
tm.assert_index_equal(result, expected)
|
| 63 |
+
assert result.name == expected.name
|
| 64 |
+
assert result.freq == expected.freq
|
| 65 |
+
|
| 66 |
+
def test_delete_doesnt_infer_freq(self):
|
| 67 |
+
# GH#30655 behavior matches DatetimeIndex
|
| 68 |
+
|
| 69 |
+
tdi = TimedeltaIndex(["1 Day", "2 Days", None, "3 Days", "4 Days"])
|
| 70 |
+
result = tdi.delete(2)
|
| 71 |
+
assert result.freq is None
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_formats.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
import pandas as pd
|
| 4 |
+
from pandas import (
|
| 5 |
+
Series,
|
| 6 |
+
TimedeltaIndex,
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class TestTimedeltaIndexRendering:
|
| 11 |
+
def test_repr_round_days_non_nano(self):
|
| 12 |
+
# GH#55405
|
| 13 |
+
# we should get "1 days", not "1 days 00:00:00" with non-nano
|
| 14 |
+
tdi = TimedeltaIndex(["1 days"], freq="D").as_unit("s")
|
| 15 |
+
result = repr(tdi)
|
| 16 |
+
expected = "TimedeltaIndex(['1 days'], dtype='timedelta64[s]', freq='D')"
|
| 17 |
+
assert result == expected
|
| 18 |
+
|
| 19 |
+
result2 = repr(Series(tdi))
|
| 20 |
+
expected2 = "0 1 days\ndtype: timedelta64[s]"
|
| 21 |
+
assert result2 == expected2
|
| 22 |
+
|
| 23 |
+
@pytest.mark.parametrize("method", ["__repr__", "__str__"])
|
| 24 |
+
def test_representation(self, method):
|
| 25 |
+
idx1 = TimedeltaIndex([], freq="D")
|
| 26 |
+
idx2 = TimedeltaIndex(["1 days"], freq="D")
|
| 27 |
+
idx3 = TimedeltaIndex(["1 days", "2 days"], freq="D")
|
| 28 |
+
idx4 = TimedeltaIndex(["1 days", "2 days", "3 days"], freq="D")
|
| 29 |
+
idx5 = TimedeltaIndex(["1 days 00:00:01", "2 days", "3 days"])
|
| 30 |
+
|
| 31 |
+
exp1 = "TimedeltaIndex([], dtype='timedelta64[ns]', freq='D')"
|
| 32 |
+
|
| 33 |
+
exp2 = "TimedeltaIndex(['1 days'], dtype='timedelta64[ns]', freq='D')"
|
| 34 |
+
|
| 35 |
+
exp3 = "TimedeltaIndex(['1 days', '2 days'], dtype='timedelta64[ns]', freq='D')"
|
| 36 |
+
|
| 37 |
+
exp4 = (
|
| 38 |
+
"TimedeltaIndex(['1 days', '2 days', '3 days'], "
|
| 39 |
+
"dtype='timedelta64[ns]', freq='D')"
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
exp5 = (
|
| 43 |
+
"TimedeltaIndex(['1 days 00:00:01', '2 days 00:00:00', "
|
| 44 |
+
"'3 days 00:00:00'], dtype='timedelta64[ns]', freq=None)"
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
with pd.option_context("display.width", 300):
|
| 48 |
+
for idx, expected in zip(
|
| 49 |
+
[idx1, idx2, idx3, idx4, idx5], [exp1, exp2, exp3, exp4, exp5]
|
| 50 |
+
):
|
| 51 |
+
result = getattr(idx, method)()
|
| 52 |
+
assert result == expected
|
| 53 |
+
|
| 54 |
+
# TODO: this is a Series.__repr__ test
|
| 55 |
+
def test_representation_to_series(self):
|
| 56 |
+
idx1 = TimedeltaIndex([], freq="D")
|
| 57 |
+
idx2 = TimedeltaIndex(["1 days"], freq="D")
|
| 58 |
+
idx3 = TimedeltaIndex(["1 days", "2 days"], freq="D")
|
| 59 |
+
idx4 = TimedeltaIndex(["1 days", "2 days", "3 days"], freq="D")
|
| 60 |
+
idx5 = TimedeltaIndex(["1 days 00:00:01", "2 days", "3 days"])
|
| 61 |
+
|
| 62 |
+
exp1 = """Series([], dtype: timedelta64[ns])"""
|
| 63 |
+
|
| 64 |
+
exp2 = "0 1 days\ndtype: timedelta64[ns]"
|
| 65 |
+
|
| 66 |
+
exp3 = "0 1 days\n1 2 days\ndtype: timedelta64[ns]"
|
| 67 |
+
|
| 68 |
+
exp4 = "0 1 days\n1 2 days\n2 3 days\ndtype: timedelta64[ns]"
|
| 69 |
+
|
| 70 |
+
exp5 = (
|
| 71 |
+
"0 1 days 00:00:01\n"
|
| 72 |
+
"1 2 days 00:00:00\n"
|
| 73 |
+
"2 3 days 00:00:00\n"
|
| 74 |
+
"dtype: timedelta64[ns]"
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
with pd.option_context("display.width", 300):
|
| 78 |
+
for idx, expected in zip(
|
| 79 |
+
[idx1, idx2, idx3, idx4, idx5], [exp1, exp2, exp3, exp4, exp5]
|
| 80 |
+
):
|
| 81 |
+
result = repr(Series(idx))
|
| 82 |
+
assert result == expected
|
| 83 |
+
|
| 84 |
+
def test_summary(self):
|
| 85 |
+
# GH#9116
|
| 86 |
+
idx1 = TimedeltaIndex([], freq="D")
|
| 87 |
+
idx2 = TimedeltaIndex(["1 days"], freq="D")
|
| 88 |
+
idx3 = TimedeltaIndex(["1 days", "2 days"], freq="D")
|
| 89 |
+
idx4 = TimedeltaIndex(["1 days", "2 days", "3 days"], freq="D")
|
| 90 |
+
idx5 = TimedeltaIndex(["1 days 00:00:01", "2 days", "3 days"])
|
| 91 |
+
|
| 92 |
+
exp1 = "TimedeltaIndex: 0 entries\nFreq: D"
|
| 93 |
+
|
| 94 |
+
exp2 = "TimedeltaIndex: 1 entries, 1 days to 1 days\nFreq: D"
|
| 95 |
+
|
| 96 |
+
exp3 = "TimedeltaIndex: 2 entries, 1 days to 2 days\nFreq: D"
|
| 97 |
+
|
| 98 |
+
exp4 = "TimedeltaIndex: 3 entries, 1 days to 3 days\nFreq: D"
|
| 99 |
+
|
| 100 |
+
exp5 = "TimedeltaIndex: 3 entries, 1 days 00:00:01 to 3 days 00:00:00"
|
| 101 |
+
|
| 102 |
+
for idx, expected in zip(
|
| 103 |
+
[idx1, idx2, idx3, idx4, idx5], [exp1, exp2, exp3, exp4, exp5]
|
| 104 |
+
):
|
| 105 |
+
result = idx._summary()
|
| 106 |
+
assert result == expected
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_freq_attr.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
from pandas import TimedeltaIndex
|
| 4 |
+
|
| 5 |
+
from pandas.tseries.offsets import (
|
| 6 |
+
DateOffset,
|
| 7 |
+
Day,
|
| 8 |
+
Hour,
|
| 9 |
+
MonthEnd,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class TestFreq:
|
| 14 |
+
@pytest.mark.parametrize("values", [["0 days", "2 days", "4 days"], []])
|
| 15 |
+
@pytest.mark.parametrize("freq", ["2D", Day(2), "48h", Hour(48)])
|
| 16 |
+
def test_freq_setter(self, values, freq):
|
| 17 |
+
# GH#20678
|
| 18 |
+
idx = TimedeltaIndex(values)
|
| 19 |
+
|
| 20 |
+
# can set to an offset, converting from string if necessary
|
| 21 |
+
idx._data.freq = freq
|
| 22 |
+
assert idx.freq == freq
|
| 23 |
+
assert isinstance(idx.freq, DateOffset)
|
| 24 |
+
|
| 25 |
+
# can reset to None
|
| 26 |
+
idx._data.freq = None
|
| 27 |
+
assert idx.freq is None
|
| 28 |
+
|
| 29 |
+
def test_with_freq_empty_requires_tick(self):
|
| 30 |
+
idx = TimedeltaIndex([])
|
| 31 |
+
|
| 32 |
+
off = MonthEnd(1)
|
| 33 |
+
msg = "TimedeltaArray/Index freq must be a Tick"
|
| 34 |
+
with pytest.raises(TypeError, match=msg):
|
| 35 |
+
idx._with_freq(off)
|
| 36 |
+
with pytest.raises(TypeError, match=msg):
|
| 37 |
+
idx._data._with_freq(off)
|
| 38 |
+
|
| 39 |
+
def test_freq_setter_errors(self):
|
| 40 |
+
# GH#20678
|
| 41 |
+
idx = TimedeltaIndex(["0 days", "2 days", "4 days"])
|
| 42 |
+
|
| 43 |
+
# setting with an incompatible freq
|
| 44 |
+
msg = (
|
| 45 |
+
"Inferred frequency 2D from passed values does not conform to "
|
| 46 |
+
"passed frequency 5D"
|
| 47 |
+
)
|
| 48 |
+
with pytest.raises(ValueError, match=msg):
|
| 49 |
+
idx._data.freq = "5D"
|
| 50 |
+
|
| 51 |
+
# setting with a non-fixed frequency
|
| 52 |
+
msg = r"<2 \* BusinessDays> is a non-fixed frequency"
|
| 53 |
+
with pytest.raises(ValueError, match=msg):
|
| 54 |
+
idx._data.freq = "2B"
|
| 55 |
+
|
| 56 |
+
# setting with non-freq string
|
| 57 |
+
with pytest.raises(ValueError, match="Invalid frequency"):
|
| 58 |
+
idx._data.freq = "foo"
|
| 59 |
+
|
| 60 |
+
def test_freq_view_safe(self):
|
| 61 |
+
# Setting the freq for one TimedeltaIndex shouldn't alter the freq
|
| 62 |
+
# for another that views the same data
|
| 63 |
+
|
| 64 |
+
tdi = TimedeltaIndex(["0 days", "2 days", "4 days"], freq="2D")
|
| 65 |
+
tda = tdi._data
|
| 66 |
+
|
| 67 |
+
tdi2 = TimedeltaIndex(tda)._with_freq(None)
|
| 68 |
+
assert tdi2.freq is None
|
| 69 |
+
|
| 70 |
+
# Original was not altered
|
| 71 |
+
assert tdi.freq == "2D"
|
| 72 |
+
assert tda.freq == "2D"
|
omnilmm/lib/python3.10/site-pack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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
import re
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
from pandas import (
|
| 8 |
+
Index,
|
| 9 |
+
NaT,
|
| 10 |
+
Timedelta,
|
| 11 |
+
TimedeltaIndex,
|
| 12 |
+
Timestamp,
|
| 13 |
+
notna,
|
| 14 |
+
offsets,
|
| 15 |
+
timedelta_range,
|
| 16 |
+
to_timedelta,
|
| 17 |
+
)
|
| 18 |
+
import pandas._testing as tm
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class TestGetItem:
|
| 22 |
+
def test_getitem_slice_keeps_name(self):
|
| 23 |
+
# GH#4226
|
| 24 |
+
tdi = timedelta_range("1d", "5d", freq="h", name="timebucket")
|
| 25 |
+
assert tdi[1:].name == tdi.name
|
| 26 |
+
|
| 27 |
+
def test_getitem(self):
|
| 28 |
+
idx1 = timedelta_range("1 day", "31 day", freq="D", name="idx")
|
| 29 |
+
|
| 30 |
+
for idx in [idx1]:
|
| 31 |
+
result = idx[0]
|
| 32 |
+
assert result == Timedelta("1 day")
|
| 33 |
+
|
| 34 |
+
result = idx[0:5]
|
| 35 |
+
expected = timedelta_range("1 day", "5 day", freq="D", name="idx")
|
| 36 |
+
tm.assert_index_equal(result, expected)
|
| 37 |
+
assert result.freq == expected.freq
|
| 38 |
+
|
| 39 |
+
result = idx[0:10:2]
|
| 40 |
+
expected = timedelta_range("1 day", "9 day", freq="2D", name="idx")
|
| 41 |
+
tm.assert_index_equal(result, expected)
|
| 42 |
+
assert result.freq == expected.freq
|
| 43 |
+
|
| 44 |
+
result = idx[-20:-5:3]
|
| 45 |
+
expected = timedelta_range("12 day", "24 day", freq="3D", name="idx")
|
| 46 |
+
tm.assert_index_equal(result, expected)
|
| 47 |
+
assert result.freq == expected.freq
|
| 48 |
+
|
| 49 |
+
result = idx[4::-1]
|
| 50 |
+
expected = TimedeltaIndex(
|
| 51 |
+
["5 day", "4 day", "3 day", "2 day", "1 day"], freq="-1D", name="idx"
|
| 52 |
+
)
|
| 53 |
+
tm.assert_index_equal(result, expected)
|
| 54 |
+
assert result.freq == expected.freq
|
| 55 |
+
|
| 56 |
+
@pytest.mark.parametrize(
|
| 57 |
+
"key",
|
| 58 |
+
[
|
| 59 |
+
Timestamp("1970-01-01"),
|
| 60 |
+
Timestamp("1970-01-02"),
|
| 61 |
+
datetime(1970, 1, 1),
|
| 62 |
+
Timestamp("1970-01-03").to_datetime64(),
|
| 63 |
+
# non-matching NA values
|
| 64 |
+
np.datetime64("NaT"),
|
| 65 |
+
],
|
| 66 |
+
)
|
| 67 |
+
def test_timestamp_invalid_key(self, key):
|
| 68 |
+
# GH#20464
|
| 69 |
+
tdi = timedelta_range(0, periods=10)
|
| 70 |
+
with pytest.raises(KeyError, match=re.escape(repr(key))):
|
| 71 |
+
tdi.get_loc(key)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class TestGetLoc:
|
| 75 |
+
def test_get_loc_key_unit_mismatch(self):
|
| 76 |
+
idx = to_timedelta(["0 days", "1 days", "2 days"])
|
| 77 |
+
key = idx[1].as_unit("ms")
|
| 78 |
+
loc = idx.get_loc(key)
|
| 79 |
+
assert loc == 1
|
| 80 |
+
|
| 81 |
+
def test_get_loc_key_unit_mismatch_not_castable(self):
|
| 82 |
+
tdi = to_timedelta(["0 days", "1 days", "2 days"]).astype("m8[s]")
|
| 83 |
+
assert tdi.dtype == "m8[s]"
|
| 84 |
+
key = tdi[0].as_unit("ns") + Timedelta(1)
|
| 85 |
+
|
| 86 |
+
with pytest.raises(KeyError, match=r"Timedelta\('0 days 00:00:00.000000001'\)"):
|
| 87 |
+
tdi.get_loc(key)
|
| 88 |
+
|
| 89 |
+
assert key not in tdi
|
| 90 |
+
|
| 91 |
+
def test_get_loc(self):
|
| 92 |
+
idx = to_timedelta(["0 days", "1 days", "2 days"])
|
| 93 |
+
|
| 94 |
+
# GH 16909
|
| 95 |
+
assert idx.get_loc(idx[1].to_timedelta64()) == 1
|
| 96 |
+
|
| 97 |
+
# GH 16896
|
| 98 |
+
assert idx.get_loc("0 days") == 0
|
| 99 |
+
|
| 100 |
+
def test_get_loc_nat(self):
|
| 101 |
+
tidx = TimedeltaIndex(["1 days 01:00:00", "NaT", "2 days 01:00:00"])
|
| 102 |
+
|
| 103 |
+
assert tidx.get_loc(NaT) == 1
|
| 104 |
+
assert tidx.get_loc(None) == 1
|
| 105 |
+
assert tidx.get_loc(float("nan")) == 1
|
| 106 |
+
assert tidx.get_loc(np.nan) == 1
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class TestGetIndexer:
|
| 110 |
+
def test_get_indexer(self):
|
| 111 |
+
idx = to_timedelta(["0 days", "1 days", "2 days"])
|
| 112 |
+
tm.assert_numpy_array_equal(
|
| 113 |
+
idx.get_indexer(idx), np.array([0, 1, 2], dtype=np.intp)
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
target = to_timedelta(["-1 hour", "12 hours", "1 day 1 hour"])
|
| 117 |
+
tm.assert_numpy_array_equal(
|
| 118 |
+
idx.get_indexer(target, "pad"), np.array([-1, 0, 1], dtype=np.intp)
|
| 119 |
+
)
|
| 120 |
+
tm.assert_numpy_array_equal(
|
| 121 |
+
idx.get_indexer(target, "backfill"), np.array([0, 1, 2], dtype=np.intp)
|
| 122 |
+
)
|
| 123 |
+
tm.assert_numpy_array_equal(
|
| 124 |
+
idx.get_indexer(target, "nearest"), np.array([0, 1, 1], dtype=np.intp)
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
res = idx.get_indexer(target, "nearest", tolerance=Timedelta("1 hour"))
|
| 128 |
+
tm.assert_numpy_array_equal(res, np.array([0, -1, 1], dtype=np.intp))
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class TestWhere:
|
| 132 |
+
def test_where_doesnt_retain_freq(self):
|
| 133 |
+
tdi = timedelta_range("1 day", periods=3, freq="D", name="idx")
|
| 134 |
+
cond = [True, True, False]
|
| 135 |
+
expected = TimedeltaIndex([tdi[0], tdi[1], tdi[0]], freq=None, name="idx")
|
| 136 |
+
|
| 137 |
+
result = tdi.where(cond, tdi[::-1])
|
| 138 |
+
tm.assert_index_equal(result, expected)
|
| 139 |
+
|
| 140 |
+
def test_where_invalid_dtypes(self, fixed_now_ts):
|
| 141 |
+
tdi = timedelta_range("1 day", periods=3, freq="D", name="idx")
|
| 142 |
+
|
| 143 |
+
tail = tdi[2:].tolist()
|
| 144 |
+
i2 = Index([NaT, NaT] + tail)
|
| 145 |
+
mask = notna(i2)
|
| 146 |
+
|
| 147 |
+
expected = Index([NaT._value, NaT._value] + tail, dtype=object, name="idx")
|
| 148 |
+
assert isinstance(expected[0], int)
|
| 149 |
+
result = tdi.where(mask, i2.asi8)
|
| 150 |
+
tm.assert_index_equal(result, expected)
|
| 151 |
+
|
| 152 |
+
ts = i2 + fixed_now_ts
|
| 153 |
+
expected = Index([ts[0], ts[1]] + tail, dtype=object, name="idx")
|
| 154 |
+
result = tdi.where(mask, ts)
|
| 155 |
+
tm.assert_index_equal(result, expected)
|
| 156 |
+
|
| 157 |
+
per = (i2 + fixed_now_ts).to_period("D")
|
| 158 |
+
expected = Index([per[0], per[1]] + tail, dtype=object, name="idx")
|
| 159 |
+
result = tdi.where(mask, per)
|
| 160 |
+
tm.assert_index_equal(result, expected)
|
| 161 |
+
|
| 162 |
+
ts = fixed_now_ts
|
| 163 |
+
expected = Index([ts, ts] + tail, dtype=object, name="idx")
|
| 164 |
+
result = tdi.where(mask, ts)
|
| 165 |
+
tm.assert_index_equal(result, expected)
|
| 166 |
+
|
| 167 |
+
def test_where_mismatched_nat(self):
|
| 168 |
+
tdi = timedelta_range("1 day", periods=3, freq="D", name="idx")
|
| 169 |
+
cond = np.array([True, False, False])
|
| 170 |
+
|
| 171 |
+
dtnat = np.datetime64("NaT", "ns")
|
| 172 |
+
expected = Index([tdi[0], dtnat, dtnat], dtype=object, name="idx")
|
| 173 |
+
assert expected[2] is dtnat
|
| 174 |
+
result = tdi.where(cond, dtnat)
|
| 175 |
+
tm.assert_index_equal(result, expected)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class TestTake:
|
| 179 |
+
def test_take(self):
|
| 180 |
+
# GH 10295
|
| 181 |
+
idx1 = timedelta_range("1 day", "31 day", freq="D", name="idx")
|
| 182 |
+
|
| 183 |
+
for idx in [idx1]:
|
| 184 |
+
result = idx.take([0])
|
| 185 |
+
assert result == Timedelta("1 day")
|
| 186 |
+
|
| 187 |
+
result = idx.take([-1])
|
| 188 |
+
assert result == Timedelta("31 day")
|
| 189 |
+
|
| 190 |
+
result = idx.take([0, 1, 2])
|
| 191 |
+
expected = timedelta_range("1 day", "3 day", freq="D", name="idx")
|
| 192 |
+
tm.assert_index_equal(result, expected)
|
| 193 |
+
assert result.freq == expected.freq
|
| 194 |
+
|
| 195 |
+
result = idx.take([0, 2, 4])
|
| 196 |
+
expected = timedelta_range("1 day", "5 day", freq="2D", name="idx")
|
| 197 |
+
tm.assert_index_equal(result, expected)
|
| 198 |
+
assert result.freq == expected.freq
|
| 199 |
+
|
| 200 |
+
result = idx.take([7, 4, 1])
|
| 201 |
+
expected = timedelta_range("8 day", "2 day", freq="-3D", name="idx")
|
| 202 |
+
tm.assert_index_equal(result, expected)
|
| 203 |
+
assert result.freq == expected.freq
|
| 204 |
+
|
| 205 |
+
result = idx.take([3, 2, 5])
|
| 206 |
+
expected = TimedeltaIndex(["4 day", "3 day", "6 day"], name="idx")
|
| 207 |
+
tm.assert_index_equal(result, expected)
|
| 208 |
+
assert result.freq is None
|
| 209 |
+
|
| 210 |
+
result = idx.take([-3, 2, 5])
|
| 211 |
+
expected = TimedeltaIndex(["29 day", "3 day", "6 day"], name="idx")
|
| 212 |
+
tm.assert_index_equal(result, expected)
|
| 213 |
+
assert result.freq is None
|
| 214 |
+
|
| 215 |
+
def test_take_invalid_kwargs(self):
|
| 216 |
+
idx = timedelta_range("1 day", "31 day", freq="D", name="idx")
|
| 217 |
+
indices = [1, 6, 5, 9, 10, 13, 15, 3]
|
| 218 |
+
|
| 219 |
+
msg = r"take\(\) got an unexpected keyword argument 'foo'"
|
| 220 |
+
with pytest.raises(TypeError, match=msg):
|
| 221 |
+
idx.take(indices, foo=2)
|
| 222 |
+
|
| 223 |
+
msg = "the 'out' parameter is not supported"
|
| 224 |
+
with pytest.raises(ValueError, match=msg):
|
| 225 |
+
idx.take(indices, out=indices)
|
| 226 |
+
|
| 227 |
+
msg = "the 'mode' parameter is not supported"
|
| 228 |
+
with pytest.raises(ValueError, match=msg):
|
| 229 |
+
idx.take(indices, mode="clip")
|
| 230 |
+
|
| 231 |
+
def test_take_equiv_getitem(self):
|
| 232 |
+
tds = ["1day 02:00:00", "1 day 04:00:00", "1 day 10:00:00"]
|
| 233 |
+
idx = timedelta_range(start="1d", end="2d", freq="h", name="idx")
|
| 234 |
+
expected = TimedeltaIndex(tds, freq=None, name="idx")
|
| 235 |
+
|
| 236 |
+
taken1 = idx.take([2, 4, 10])
|
| 237 |
+
taken2 = idx[[2, 4, 10]]
|
| 238 |
+
|
| 239 |
+
for taken in [taken1, taken2]:
|
| 240 |
+
tm.assert_index_equal(taken, expected)
|
| 241 |
+
assert isinstance(taken, TimedeltaIndex)
|
| 242 |
+
assert taken.freq is None
|
| 243 |
+
assert taken.name == expected.name
|
| 244 |
+
|
| 245 |
+
def test_take_fill_value(self):
|
| 246 |
+
# GH 12631
|
| 247 |
+
idx = TimedeltaIndex(["1 days", "2 days", "3 days"], name="xxx")
|
| 248 |
+
result = idx.take(np.array([1, 0, -1]))
|
| 249 |
+
expected = TimedeltaIndex(["2 days", "1 days", "3 days"], name="xxx")
|
| 250 |
+
tm.assert_index_equal(result, expected)
|
| 251 |
+
|
| 252 |
+
# fill_value
|
| 253 |
+
result = idx.take(np.array([1, 0, -1]), fill_value=True)
|
| 254 |
+
expected = TimedeltaIndex(["2 days", "1 days", "NaT"], name="xxx")
|
| 255 |
+
tm.assert_index_equal(result, expected)
|
| 256 |
+
|
| 257 |
+
# allow_fill=False
|
| 258 |
+
result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True)
|
| 259 |
+
expected = TimedeltaIndex(["2 days", "1 days", "3 days"], name="xxx")
|
| 260 |
+
tm.assert_index_equal(result, expected)
|
| 261 |
+
|
| 262 |
+
msg = (
|
| 263 |
+
"When allow_fill=True and fill_value is not None, "
|
| 264 |
+
"all indices must be >= -1"
|
| 265 |
+
)
|
| 266 |
+
with pytest.raises(ValueError, match=msg):
|
| 267 |
+
idx.take(np.array([1, 0, -2]), fill_value=True)
|
| 268 |
+
with pytest.raises(ValueError, match=msg):
|
| 269 |
+
idx.take(np.array([1, 0, -5]), fill_value=True)
|
| 270 |
+
|
| 271 |
+
msg = "index -5 is out of bounds for (axis 0 with )?size 3"
|
| 272 |
+
with pytest.raises(IndexError, match=msg):
|
| 273 |
+
idx.take(np.array([1, -5]))
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
class TestMaybeCastSliceBound:
|
| 277 |
+
@pytest.fixture(params=["increasing", "decreasing", None])
|
| 278 |
+
def monotonic(self, request):
|
| 279 |
+
return request.param
|
| 280 |
+
|
| 281 |
+
@pytest.fixture
|
| 282 |
+
def tdi(self, monotonic):
|
| 283 |
+
tdi = timedelta_range("1 Day", periods=10)
|
| 284 |
+
if monotonic == "decreasing":
|
| 285 |
+
tdi = tdi[::-1]
|
| 286 |
+
elif monotonic is None:
|
| 287 |
+
taker = np.arange(10, dtype=np.intp)
|
| 288 |
+
np.random.default_rng(2).shuffle(taker)
|
| 289 |
+
tdi = tdi.take(taker)
|
| 290 |
+
return tdi
|
| 291 |
+
|
| 292 |
+
def test_maybe_cast_slice_bound_invalid_str(self, tdi):
|
| 293 |
+
# test the low-level _maybe_cast_slice_bound and that we get the
|
| 294 |
+
# expected exception+message all the way up the stack
|
| 295 |
+
msg = (
|
| 296 |
+
"cannot do slice indexing on TimedeltaIndex with these "
|
| 297 |
+
r"indexers \[foo\] of type str"
|
| 298 |
+
)
|
| 299 |
+
with pytest.raises(TypeError, match=msg):
|
| 300 |
+
tdi._maybe_cast_slice_bound("foo", side="left")
|
| 301 |
+
with pytest.raises(TypeError, match=msg):
|
| 302 |
+
tdi.get_slice_bound("foo", side="left")
|
| 303 |
+
with pytest.raises(TypeError, match=msg):
|
| 304 |
+
tdi.slice_locs("foo", None, None)
|
| 305 |
+
|
| 306 |
+
def test_slice_invalid_str_with_timedeltaindex(
|
| 307 |
+
self, tdi, frame_or_series, indexer_sl
|
| 308 |
+
):
|
| 309 |
+
obj = frame_or_series(range(10), index=tdi)
|
| 310 |
+
|
| 311 |
+
msg = (
|
| 312 |
+
"cannot do slice indexing on TimedeltaIndex with these "
|
| 313 |
+
r"indexers \[foo\] of type str"
|
| 314 |
+
)
|
| 315 |
+
with pytest.raises(TypeError, match=msg):
|
| 316 |
+
indexer_sl(obj)["foo":]
|
| 317 |
+
with pytest.raises(TypeError, match=msg):
|
| 318 |
+
indexer_sl(obj)["foo":-1]
|
| 319 |
+
with pytest.raises(TypeError, match=msg):
|
| 320 |
+
indexer_sl(obj)[:"foo"]
|
| 321 |
+
with pytest.raises(TypeError, match=msg):
|
| 322 |
+
indexer_sl(obj)[tdi[0] : "foo"]
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
class TestContains:
|
| 326 |
+
def test_contains_nonunique(self):
|
| 327 |
+
# GH#9512
|
| 328 |
+
for vals in (
|
| 329 |
+
[0, 1, 0],
|
| 330 |
+
[0, 0, -1],
|
| 331 |
+
[0, -1, -1],
|
| 332 |
+
["00:01:00", "00:01:00", "00:02:00"],
|
| 333 |
+
["00:01:00", "00:01:00", "00:00:01"],
|
| 334 |
+
):
|
| 335 |
+
idx = TimedeltaIndex(vals)
|
| 336 |
+
assert idx[0] in idx
|
| 337 |
+
|
| 338 |
+
def test_contains(self):
|
| 339 |
+
# Checking for any NaT-like objects
|
| 340 |
+
# GH#13603
|
| 341 |
+
td = to_timedelta(range(5), unit="d") + offsets.Hour(1)
|
| 342 |
+
for v in [NaT, None, float("nan"), np.nan]:
|
| 343 |
+
assert v not in td
|
| 344 |
+
|
| 345 |
+
td = to_timedelta([NaT])
|
| 346 |
+
for v in [NaT, None, float("nan"), np.nan]:
|
| 347 |
+
assert v in td
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_join.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
from pandas import (
|
| 4 |
+
DataFrame,
|
| 5 |
+
Index,
|
| 6 |
+
Timedelta,
|
| 7 |
+
timedelta_range,
|
| 8 |
+
)
|
| 9 |
+
import pandas._testing as tm
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class TestJoin:
|
| 13 |
+
def test_append_join_nondatetimeindex(self):
|
| 14 |
+
rng = timedelta_range("1 days", periods=10)
|
| 15 |
+
idx = Index(["a", "b", "c", "d"])
|
| 16 |
+
|
| 17 |
+
result = rng.append(idx)
|
| 18 |
+
assert isinstance(result[0], Timedelta)
|
| 19 |
+
|
| 20 |
+
# it works
|
| 21 |
+
rng.join(idx, how="outer")
|
| 22 |
+
|
| 23 |
+
def test_join_self(self, join_type):
|
| 24 |
+
index = timedelta_range("1 day", periods=10)
|
| 25 |
+
joined = index.join(index, how=join_type)
|
| 26 |
+
tm.assert_index_equal(index, joined)
|
| 27 |
+
|
| 28 |
+
def test_does_not_convert_mixed_integer(self):
|
| 29 |
+
df = DataFrame(np.ones((5, 5)), columns=timedelta_range("1 day", periods=5))
|
| 30 |
+
|
| 31 |
+
cols = df.columns.join(df.index, how="outer")
|
| 32 |
+
joined = cols.join(df.columns)
|
| 33 |
+
assert cols.dtype == np.dtype("O")
|
| 34 |
+
assert cols.dtype == joined.dtype
|
| 35 |
+
tm.assert_index_equal(cols, joined)
|
| 36 |
+
|
| 37 |
+
def test_join_preserves_freq(self):
|
| 38 |
+
# GH#32157
|
| 39 |
+
tdi = timedelta_range("1 day", periods=10)
|
| 40 |
+
result = tdi[:5].join(tdi[5:], how="outer")
|
| 41 |
+
assert result.freq == tdi.freq
|
| 42 |
+
tm.assert_index_equal(result, tdi)
|
| 43 |
+
|
| 44 |
+
result = tdi[:5].join(tdi[6:], how="outer")
|
| 45 |
+
assert result.freq is None
|
| 46 |
+
expected = tdi.delete(5)
|
| 47 |
+
tm.assert_index_equal(result, expected)
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_ops.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pandas import (
|
| 2 |
+
TimedeltaIndex,
|
| 3 |
+
timedelta_range,
|
| 4 |
+
)
|
| 5 |
+
import pandas._testing as tm
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class TestTimedeltaIndexOps:
|
| 9 |
+
def test_infer_freq(self, freq_sample):
|
| 10 |
+
# GH#11018
|
| 11 |
+
idx = timedelta_range("1", freq=freq_sample, periods=10)
|
| 12 |
+
result = TimedeltaIndex(idx.asi8, freq="infer")
|
| 13 |
+
tm.assert_index_equal(idx, result)
|
| 14 |
+
assert result.freq == freq_sample
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_pickle.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pandas import timedelta_range
|
| 2 |
+
import pandas._testing as tm
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class TestPickle:
|
| 6 |
+
def test_pickle_after_set_freq(self):
|
| 7 |
+
tdi = timedelta_range("1 day", periods=4, freq="s")
|
| 8 |
+
tdi = tdi._with_freq(None)
|
| 9 |
+
|
| 10 |
+
res = tm.round_trip_pickle(tdi)
|
| 11 |
+
tm.assert_index_equal(res, tdi)
|
omnilmm/lib/python3.10/site-packages/pandas/tests/indexes/timedeltas/test_scalar_compat.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests for TimedeltaIndex methods behaving like their Timedelta counterparts
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
from pandas._libs.tslibs.offsets import INVALID_FREQ_ERR_MSG
|
| 9 |
+
|
| 10 |
+
from pandas import (
|
| 11 |
+
Index,
|
| 12 |
+
Series,
|
| 13 |
+
Timedelta,
|
| 14 |
+
TimedeltaIndex,
|
| 15 |
+
timedelta_range,
|
| 16 |
+
)
|
| 17 |
+
import pandas._testing as tm
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class TestVectorizedTimedelta:
|
| 21 |
+
def test_tdi_total_seconds(self):
|
| 22 |
+
# GH#10939
|
| 23 |
+
# test index
|
| 24 |
+
rng = timedelta_range("1 days, 10:11:12.100123456", periods=2, freq="s")
|
| 25 |
+
expt = [
|
| 26 |
+
1 * 86400 + 10 * 3600 + 11 * 60 + 12 + 100123456.0 / 1e9,
|
| 27 |
+
1 * 86400 + 10 * 3600 + 11 * 60 + 13 + 100123456.0 / 1e9,
|
| 28 |
+
]
|
| 29 |
+
tm.assert_almost_equal(rng.total_seconds(), Index(expt))
|
| 30 |
+
|
| 31 |
+
# test Series
|
| 32 |
+
ser = Series(rng)
|
| 33 |
+
s_expt = Series(expt, index=[0, 1])
|
| 34 |
+
tm.assert_series_equal(ser.dt.total_seconds(), s_expt)
|
| 35 |
+
|
| 36 |
+
# with nat
|
| 37 |
+
ser[1] = np.nan
|
| 38 |
+
s_expt = Series(
|
| 39 |
+
[1 * 86400 + 10 * 3600 + 11 * 60 + 12 + 100123456.0 / 1e9, np.nan],
|
| 40 |
+
index=[0, 1],
|
| 41 |
+
)
|
| 42 |
+
tm.assert_series_equal(ser.dt.total_seconds(), s_expt)
|
| 43 |
+
|
| 44 |
+
def test_tdi_total_seconds_all_nat(self):
|
| 45 |
+
# with both nat
|
| 46 |
+
ser = Series([np.nan, np.nan], dtype="timedelta64[ns]")
|
| 47 |
+
result = ser.dt.total_seconds()
|
| 48 |
+
expected = Series([np.nan, np.nan])
|
| 49 |
+
tm.assert_series_equal(result, expected)
|
| 50 |
+
|
| 51 |
+
def test_tdi_round(self):
|
| 52 |
+
td = timedelta_range(start="16801 days", periods=5, freq="30Min")
|
| 53 |
+
elt = td[1]
|
| 54 |
+
|
| 55 |
+
expected_rng = TimedeltaIndex(
|
| 56 |
+
[
|
| 57 |
+
Timedelta("16801 days 00:00:00"),
|
| 58 |
+
Timedelta("16801 days 00:00:00"),
|
| 59 |
+
Timedelta("16801 days 01:00:00"),
|
| 60 |
+
Timedelta("16801 days 02:00:00"),
|
| 61 |
+
Timedelta("16801 days 02:00:00"),
|
| 62 |
+
]
|
| 63 |
+
)
|
| 64 |
+
expected_elt = expected_rng[1]
|
| 65 |
+
|
| 66 |
+
tm.assert_index_equal(td.round(freq="h"), expected_rng)
|
| 67 |
+
assert elt.round(freq="h") == expected_elt
|
| 68 |
+
|
| 69 |
+
msg = INVALID_FREQ_ERR_MSG
|
| 70 |
+
with pytest.raises(ValueError, match=msg):
|
| 71 |
+
td.round(freq="foo")
|
| 72 |
+
with pytest.raises(ValueError, match=msg):
|
| 73 |
+
elt.round(freq="foo")
|
| 74 |
+
|
| 75 |
+
msg = "<MonthEnd> is a non-fixed frequency"
|
| 76 |
+
with pytest.raises(ValueError, match=msg):
|
| 77 |
+
td.round(freq="ME")
|
| 78 |
+
with pytest.raises(ValueError, match=msg):
|
| 79 |
+
elt.round(freq="ME")
|
| 80 |
+
|
| 81 |
+
@pytest.mark.parametrize(
|
| 82 |
+
"freq,msg",
|
| 83 |
+
[
|
| 84 |
+
("YE", "<YearEnd: month=12> is a non-fixed frequency"),
|
| 85 |
+
("ME", "<MonthEnd> is a non-fixed frequency"),
|
| 86 |
+
("foobar", "Invalid frequency: foobar"),
|
| 87 |
+
],
|
| 88 |
+
)
|
| 89 |
+
def test_tdi_round_invalid(self, freq, msg):
|
| 90 |
+
t1 = timedelta_range("1 days", periods=3, freq="1 min 2 s 3 us")
|
| 91 |
+
|
| 92 |
+
with pytest.raises(ValueError, match=msg):
|
| 93 |
+
t1.round(freq)
|
| 94 |
+
with pytest.raises(ValueError, match=msg):
|
| 95 |
+
# Same test for TimedeltaArray
|
| 96 |
+
t1._data.round(freq)
|
| 97 |
+
|
| 98 |
+
# TODO: de-duplicate with test_tdi_round
|
| 99 |
+
def test_round(self):
|
| 100 |
+
t1 = timedelta_range("1 days", periods=3, freq="1 min 2 s 3 us")
|
| 101 |
+
t2 = -1 * t1
|
| 102 |
+
t1a = timedelta_range("1 days", periods=3, freq="1 min 2 s")
|
| 103 |
+
t1c = TimedeltaIndex(np.array([1, 1, 1], "m8[D]")).as_unit("ns")
|
| 104 |
+
|
| 105 |
+
# note that negative times round DOWN! so don't give whole numbers
|
| 106 |
+
for freq, s1, s2 in [
|
| 107 |
+
("ns", t1, t2),
|
| 108 |
+
("us", t1, t2),
|
| 109 |
+
(
|
| 110 |
+
"ms",
|
| 111 |
+
t1a,
|
| 112 |
+
TimedeltaIndex(
|
| 113 |
+
["-1 days +00:00:00", "-2 days +23:58:58", "-2 days +23:57:56"]
|
| 114 |
+
),
|
| 115 |
+
),
|
| 116 |
+
(
|
| 117 |
+
"s",
|
| 118 |
+
t1a,
|
| 119 |
+
TimedeltaIndex(
|
| 120 |
+
["-1 days +00:00:00", "-2 days +23:58:58", "-2 days +23:57:56"]
|
| 121 |
+
),
|
| 122 |
+
),
|
| 123 |
+
("12min", t1c, TimedeltaIndex(["-1 days", "-1 days", "-1 days"])),
|
| 124 |
+
("h", t1c, TimedeltaIndex(["-1 days", "-1 days", "-1 days"])),
|
| 125 |
+
("d", t1c, -1 * t1c),
|
| 126 |
+
]:
|
| 127 |
+
r1 = t1.round(freq)
|
| 128 |
+
tm.assert_index_equal(r1, s1)
|
| 129 |
+
r2 = t2.round(freq)
|
| 130 |
+
tm.assert_index_equal(r2, s2)
|
| 131 |
+
|
| 132 |
+
def test_components(self):
|
| 133 |
+
rng = timedelta_range("1 days, 10:11:12", periods=2, freq="s")
|
| 134 |
+
rng.components
|
| 135 |
+
|
| 136 |
+
# with nat
|
| 137 |
+
s = Series(rng)
|
| 138 |
+
s[1] = np.nan
|
| 139 |
+
|
| 140 |
+
result = s.dt.components
|
| 141 |
+
assert not result.iloc[0].isna().all()
|
| 142 |
+
assert result.iloc[1].isna().all()
|