Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- lib/python3.12/site-packages/pandas/tests/indexes/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/__pycache__/conftest.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/__pycache__/test_any_index.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/__pycache__/test_base.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/__pycache__/test_common.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/__pycache__/test_datetimelike.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/__pycache__/test_engines.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/__pycache__/test_frozen.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/__pycache__/test_index_new.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/__pycache__/test_indexing.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/__pycache__/test_numpy_compat.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/__pycache__/test_old_base.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/__pycache__/test_setops.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/__pycache__/test_subclass.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/base_class/__init__.pyAdded
- lib/python3.12/site-packages/pandas/tests/indexes/base_class/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/base_class/__pycache__/test_constructors.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/base_class/__pycache__/test_formats.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/base_class/__pycache__/test_indexing.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/base_class/__pycache__/test_pickle.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/base_class/__pycache__/test_reshape.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/base_class/__pycache__/test_setops.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/base_class/__pycache__/test_where.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/base_class/test_constructors.pyAdded+80
- lib/python3.12/site-packages/pandas/tests/indexes/base_class/test_formats.pyAdded+163
- lib/python3.12/site-packages/pandas/tests/indexes/base_class/test_indexing.pyAdded+104
- lib/python3.12/site-packages/pandas/tests/indexes/base_class/test_pickle.pyAdded+11
- lib/python3.12/site-packages/pandas/tests/indexes/base_class/test_reshape.pyAdded+95
- lib/python3.12/site-packages/pandas/tests/indexes/base_class/test_setops.pyAdded+266
- lib/python3.12/site-packages/pandas/tests/indexes/base_class/test_where.pyAdded+13
- lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/__init__.pyAdded
- lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_drop_duplicates.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_equals.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_indexing.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_is_monotonic.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_nat.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_sort_values.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_value_counts.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/test_drop_duplicates.pyAdded+89
- lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/test_equals.pyAdded+181
- lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/test_indexing.pyAdded+45
- lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/test_is_monotonic.pyAdded+46
- lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/test_nat.pyAdded+53
- lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/test_sort_values.pyAdded+315
- lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/test_value_counts.pyAdded+103
- lib/python3.12/site-packages/pandas/tests/indexes/interval/__init__.pyAdded
- lib/python3.12/site-packages/pandas/tests/indexes/interval/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/interval/__pycache__/test_astype.cpython-312.pycAdded
- lib/python3.12/site-packages/pandas/tests/indexes/interval/__pycache__/test_constructors.cpython-312.pycAdded
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980import numpy as npimport pytest
import pandas as pdfrom pandas import ( Index, MultiIndex, Series,)import pandas._testing as tm
class TestIndexConstructor: # Tests for the Index constructor, specifically for cases that do # not return a subclass
@pytest.mark.parametrize("value", [1, np.int64(1)]) def test_constructor_corner(self, value): # corner case msg = ( r"Index\(\.\.\.\) must be called with a collection of some " f"kind, {value} was passed" ) with pytest.raises(TypeError, match=msg): Index(value)
@pytest.mark.parametrize("index_vals", [[("A", 1), "B"], ["B", ("A", 1)]]) def test_construction_list_mixed_tuples(self, index_vals): # see gh-10697: if we are constructing from a mixed list of tuples, # make sure that we are independent of the sorting order. index = Index(index_vals) assert isinstance(index, Index) assert not isinstance(index, MultiIndex)
def test_constructor_cast(self): msg = "could not convert string to float" with pytest.raises(ValueError, match=msg): Index(["a", "b", "c"], dtype=float)
@pytest.mark.parametrize("tuple_list", [[()], [(), ()]]) def test_construct_empty_tuples(self, tuple_list): # GH #45608 result = Index(tuple_list) expected = MultiIndex.from_tuples(tuple_list)
tm.assert_index_equal(result, expected)
def test_index_string_inference(self): # GH#54430 pytest.importorskip("pyarrow") dtype = "string[pyarrow_numpy]" expected = Index(["a", "b"], dtype=dtype) with pd.option_context("future.infer_string", True): ser = Index(["a", "b"]) tm.assert_index_equal(ser, expected)
expected = Index(["a", 1], dtype="object") with pd.option_context("future.infer_string", True): ser = Index(["a", 1]) tm.assert_index_equal(ser, expected)
def test_inference_on_pandas_objects(self): # GH#56012 idx = Index([pd.Timestamp("2019-12-31")], dtype=object) with tm.assert_produces_warning(FutureWarning, match="Dtype inference"): result = Index(idx) assert result.dtype != np.object_
ser = Series([pd.Timestamp("2019-12-31")], dtype=object)
with tm.assert_produces_warning(FutureWarning, match="Dtype inference"): result = Index(ser) assert result.dtype != np.object_
def test_constructor_not_read_only(self): # GH#57130 ser = Series([1, 2], dtype=object) with pd.option_context("mode.copy_on_write", True): idx = Index(ser) assert idx._values.flags.writeable123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163import numpy as npimport pytest
from pandas._config import using_pyarrow_string_dtypeimport pandas._config.config as cf
from pandas import Indeximport pandas._testing as tm
class TestIndexRendering: def test_repr_is_valid_construction_code(self): # for the case of Index, where the repr is traditional rather than # stylized idx = Index(["a", "b"]) res = eval(repr(idx)) tm.assert_index_equal(res, idx)
@pytest.mark.xfail(using_pyarrow_string_dtype(), reason="repr different") @pytest.mark.parametrize( "index,expected", [ # ASCII # short ( Index(["a", "bb", "ccc"]), """Index(['a', 'bb', 'ccc'], dtype='object')""", ), # multiple lines ( Index(["a", "bb", "ccc"] * 10), "Index(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', " "'bb', 'ccc', 'a', 'bb', 'ccc',\n" " 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', " "'bb', 'ccc', 'a', 'bb', 'ccc',\n" " 'a', 'bb', 'ccc', 'a', 'bb', 'ccc'],\n" " dtype='object')", ), # truncated ( Index(["a", "bb", "ccc"] * 100), "Index(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a',\n" " ...\n" " 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc'],\n" " dtype='object', length=300)", ), # Non-ASCII # short ( Index(["あ", "いい", "ううう"]), """Index(['あ', 'いい', 'ううう'], dtype='object')""", ), # multiple lines ( Index(["あ", "いい", "ううう"] * 10), ( "Index(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', " "'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう',\n" " 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', " "'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう',\n" " 'あ', 'いい', 'ううう', 'あ', 'いい', " "'ううう'],\n" " dtype='object')" ), ), # truncated ( Index(["あ", "いい", "ううう"] * 100), ( "Index(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', " "'あ', 'いい', 'ううう', 'あ',\n" " ...\n" " 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', " "'ううう', 'あ', 'いい', 'ううう'],\n" " dtype='object', length=300)" ), ), ], ) def test_string_index_repr(self, index, expected): result = repr(index) assert result == expected
@pytest.mark.xfail(using_pyarrow_string_dtype(), reason="repr different") @pytest.mark.parametrize( "index,expected", [ # short ( Index(["あ", "いい", "ううう"]), ("Index(['あ', 'いい', 'ううう'], dtype='object')"), ), # multiple lines ( Index(["あ", "いい", "ううう"] * 10), ( "Index(['あ', 'いい', 'ううう', 'あ', 'いい', " "'ううう', 'あ', 'いい', 'ううう',\n" " 'あ', 'いい', 'ううう', 'あ', 'いい', " "'ううう', 'あ', 'いい', 'ううう',\n" " 'あ', 'いい', 'ううう', 'あ', 'いい', " "'ううう', 'あ', 'いい', 'ううう',\n" " 'あ', 'いい', 'ううう'],\n" " dtype='object')" "" ), ), # truncated ( Index(["あ", "いい", "ううう"] * 100), ( "Index(['あ', 'いい', 'ううう', 'あ', 'いい', " "'ううう', 'あ', 'いい', 'ううう',\n" " 'あ',\n" " ...\n" " 'ううう', 'あ', 'いい', 'ううう', 'あ', " "'いい', 'ううう', 'あ', 'いい',\n" " 'ううう'],\n" " dtype='object', length=300)" ), ), ], ) def test_string_index_repr_with_unicode_option(self, index, expected): # Enable Unicode option ----------------------------------------- with cf.option_context("display.unicode.east_asian_width", True): result = repr(index) assert result == expected
def test_repr_summary(self): with cf.option_context("display.max_seq_items", 10): result = repr(Index(np.arange(1000))) assert len(result) < 200 assert "..." in result
def test_summary_bug(self): # GH#3869 ind = Index(["{other}%s", "~:{range}:0"], name="A") result = ind._summary() # shouldn't be formatted accidentally. assert "~:{range}:0" in result assert "{other}%s" in result
def test_index_repr_bool_nan(self): # GH32146 arr = Index([True, False, np.nan], dtype=object) msg = "Index.format is deprecated" with tm.assert_produces_warning(FutureWarning, match=msg): exp1 = arr.format() out1 = ["True", "False", "NaN"] assert out1 == exp1
exp2 = repr(arr) out2 = "Index([True, False, nan], dtype='object')" assert out2 == exp2
def test_format_different_scalar_lengths(self): # GH#35439 idx = Index(["aaaaaaaaa", "b"]) expected = ["aaaaaaaaa", "b"] msg = r"Index\.format is deprecated" with tm.assert_produces_warning(FutureWarning, match=msg): assert idx.format() == expected123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104import numpy as npimport pytest
from pandas._libs import index as libindex
import pandas as pdfrom pandas import ( Index, NaT,)import pandas._testing as tm
class TestGetSliceBounds: @pytest.mark.parametrize("side, expected", [("left", 4), ("right", 5)]) def test_get_slice_bounds_within(self, side, expected): index = Index(list("abcdef")) result = index.get_slice_bound("e", side=side) assert result == expected
@pytest.mark.parametrize("side", ["left", "right"]) @pytest.mark.parametrize( "data, bound, expected", [(list("abcdef"), "x", 6), (list("bcdefg"), "a", 0)] ) def test_get_slice_bounds_outside(self, side, expected, data, bound): index = Index(data) result = index.get_slice_bound(bound, side=side) assert result == expected
def test_get_slice_bounds_invalid_side(self): with pytest.raises(ValueError, match="Invalid value for side kwarg"): Index([]).get_slice_bound("a", side="middle")
class TestGetIndexerNonUnique: def test_get_indexer_non_unique_dtype_mismatch(self): # GH#25459 indexes, missing = Index(["A", "B"]).get_indexer_non_unique(Index([0])) tm.assert_numpy_array_equal(np.array([-1], dtype=np.intp), indexes) tm.assert_numpy_array_equal(np.array([0], dtype=np.intp), missing)
@pytest.mark.parametrize( "idx_values,idx_non_unique", [ ([np.nan, 100, 200, 100], [np.nan, 100]), ([np.nan, 100.0, 200.0, 100.0], [np.nan, 100.0]), ], ) def test_get_indexer_non_unique_int_index(self, idx_values, idx_non_unique): indexes, missing = Index(idx_values).get_indexer_non_unique(Index([np.nan])) tm.assert_numpy_array_equal(np.array([0], dtype=np.intp), indexes) tm.assert_numpy_array_equal(np.array([], dtype=np.intp), missing)
indexes, missing = Index(idx_values).get_indexer_non_unique( Index(idx_non_unique) ) tm.assert_numpy_array_equal(np.array([0, 1, 3], dtype=np.intp), indexes) tm.assert_numpy_array_equal(np.array([], dtype=np.intp), missing)
class TestGetLoc: @pytest.mark.slow # to_flat_index takes a while def test_get_loc_tuple_monotonic_above_size_cutoff(self, monkeypatch): # Go through the libindex path for which using # _bin_search vs ndarray.searchsorted makes a difference
with monkeypatch.context(): monkeypatch.setattr(libindex, "_SIZE_CUTOFF", 100) lev = list("ABCD") dti = pd.date_range("2016-01-01", periods=10)
mi = pd.MultiIndex.from_product([lev, range(5), dti]) oidx = mi.to_flat_index()
loc = len(oidx) // 2 tup = oidx[loc]
res = oidx.get_loc(tup) assert res == loc
def test_get_loc_nan_object_dtype_nonmonotonic_nonunique(self): # case that goes through _maybe_get_bool_indexer idx = Index(["foo", np.nan, None, "foo", 1.0, None], dtype=object)
# we dont raise KeyError on nan res = idx.get_loc(np.nan) assert res == 1
# we only match on None, not on np.nan res = idx.get_loc(None) expected = np.array([False, False, True, False, False, True]) tm.assert_numpy_array_equal(res, expected)
# we don't match at all on mismatched NA with pytest.raises(KeyError, match="NaT"): idx.get_loc(NaT)
def test_getitem_boolean_ea_indexer(): # GH#45806 ser = pd.Series([True, False, pd.NA], dtype="boolean") result = ser.index[ser] expected = Index([0]) tm.assert_index_equal(result, expected)1234567891011from pandas import Indeximport pandas._testing as tm
def test_pickle_preserves_object_dtype(): # GH#43188, GH#43155 don't infer numeric dtype index = Index([1, 2, 3], dtype=object)
result = tm.round_trip_pickle(index) assert result.dtype == object tm.assert_index_equal(index, result)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495"""Tests for ndarray-like method on the base Index class"""import numpy as npimport pytest
from pandas import Indeximport pandas._testing as tm
class TestReshape: def test_repeat(self): repeats = 2 index = Index([1, 2, 3]) expected = Index([1, 1, 2, 2, 3, 3])
result = index.repeat(repeats) tm.assert_index_equal(result, expected)
def test_insert(self): # GH 7256 # validate neg/pos inserts result = Index(["b", "c", "d"])
# test 0th element tm.assert_index_equal(Index(["a", "b", "c", "d"]), result.insert(0, "a"))
# test Nth element that follows Python list behavior tm.assert_index_equal(Index(["b", "c", "e", "d"]), result.insert(-1, "e"))
# test loc +/- neq (0, -1) tm.assert_index_equal(result.insert(1, "z"), result.insert(-2, "z"))
# test empty null_index = Index([]) tm.assert_index_equal(Index(["a"], dtype=object), null_index.insert(0, "a"))
def test_insert_missing(self, nulls_fixture, using_infer_string): # GH#22295 # test there is no mangling of NA values expected = Index(["a", nulls_fixture, "b", "c"], dtype=object) result = Index(list("abc"), dtype=object).insert( 1, Index([nulls_fixture], dtype=object) ) tm.assert_index_equal(result, expected)
@pytest.mark.parametrize( "val", [(1, 2), np.datetime64("2019-12-31"), np.timedelta64(1, "D")] ) @pytest.mark.parametrize("loc", [-1, 2]) def test_insert_datetime_into_object(self, loc, val): # GH#44509 idx = Index(["1", "2", "3"]) result = idx.insert(loc, val) expected = Index(["1", "2", val, "3"]) tm.assert_index_equal(result, expected) assert type(expected[2]) is type(val)
def test_insert_none_into_string_numpy(self): # GH#55365 pytest.importorskip("pyarrow") index = Index(["a", "b", "c"], dtype="string[pyarrow_numpy]") result = index.insert(-1, None) expected = Index(["a", "b", None, "c"], dtype="string[pyarrow_numpy]") tm.assert_index_equal(result, expected)
@pytest.mark.parametrize( "pos,expected", [ (0, Index(["b", "c", "d"], name="index")), (-1, Index(["a", "b", "c"], name="index")), ], ) def test_delete(self, pos, expected): index = Index(["a", "b", "c", "d"], name="index") result = index.delete(pos) tm.assert_index_equal(result, expected) assert result.name == expected.name
def test_delete_raises(self): index = Index(["a", "b", "c", "d"], name="index") msg = "index 5 is out of bounds for axis 0 with size 4" with pytest.raises(IndexError, match=msg): index.delete(5)
def test_append_multiple(self): index = Index(["a", "b", "c", "d", "e", "f"])
foos = [index[:2], index[2:4], index[4:]] result = foos[0].append(foos[1:]) tm.assert_index_equal(result, index)
# empty result = index.append([]) tm.assert_index_equal(result, index)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266from datetime import datetime
import numpy as npimport pytest
import pandas as pdfrom pandas import ( Index, Series,)import pandas._testing as tmfrom pandas.core.algorithms import safe_sort
def equal_contents(arr1, arr2) -> bool: """ Checks if the set of unique elements of arr1 and arr2 are equivalent. """ return frozenset(arr1) == frozenset(arr2)
class TestIndexSetOps: @pytest.mark.parametrize( "method", ["union", "intersection", "difference", "symmetric_difference"] ) def test_setops_sort_validation(self, method): idx1 = Index(["a", "b"]) idx2 = Index(["b", "c"])
with pytest.raises(ValueError, match="The 'sort' keyword only takes"): getattr(idx1, method)(idx2, sort=2)
# sort=True is supported as of GH#?? getattr(idx1, method)(idx2, sort=True)
def test_setops_preserve_object_dtype(self): idx = Index([1, 2, 3], dtype=object) result = idx.intersection(idx[1:]) expected = idx[1:] tm.assert_index_equal(result, expected)
# if other is not monotonic increasing, intersection goes through # a different route result = idx.intersection(idx[1:][::-1]) tm.assert_index_equal(result, expected)
result = idx._union(idx[1:], sort=None) expected = idx tm.assert_numpy_array_equal(result, expected.values)
result = idx.union(idx[1:], sort=None) tm.assert_index_equal(result, expected)
# if other is not monotonic increasing, _union goes through # a different route result = idx._union(idx[1:][::-1], sort=None) tm.assert_numpy_array_equal(result, expected.values)
result = idx.union(idx[1:][::-1], sort=None) tm.assert_index_equal(result, expected)
def test_union_base(self): index = Index([0, "a", 1, "b", 2, "c"]) first = index[3:] second = index[:5]
result = first.union(second)
expected = Index([0, 1, 2, "a", "b", "c"]) tm.assert_index_equal(result, expected)
@pytest.mark.parametrize("klass", [np.array, Series, list]) def test_union_different_type_base(self, klass): # GH 10149 index = Index([0, "a", 1, "b", 2, "c"]) first = index[3:] second = index[:5]
result = first.union(klass(second.values))
assert equal_contents(result, index)
def test_union_sort_other_incomparable(self): # https://github.com/pandas-dev/pandas/issues/24959 idx = Index([1, pd.Timestamp("2000")]) # default (sort=None) with tm.assert_produces_warning(RuntimeWarning): result = idx.union(idx[:1])
tm.assert_index_equal(result, idx)
# sort=None with tm.assert_produces_warning(RuntimeWarning): result = idx.union(idx[:1], sort=None) tm.assert_index_equal(result, idx)
# sort=False result = idx.union(idx[:1], sort=False) tm.assert_index_equal(result, idx)
def test_union_sort_other_incomparable_true(self): idx = Index([1, pd.Timestamp("2000")]) with pytest.raises(TypeError, match=".*"): idx.union(idx[:1], sort=True)
def test_intersection_equal_sort_true(self): idx = Index(["c", "a", "b"]) sorted_ = Index(["a", "b", "c"]) tm.assert_index_equal(idx.intersection(idx, sort=True), sorted_)
def test_intersection_base(self, sort): # (same results for py2 and py3 but sortedness not tested elsewhere) index = Index([0, "a", 1, "b", 2, "c"]) first = index[:5] second = index[:3]
expected = Index([0, 1, "a"]) if sort is None else Index([0, "a", 1]) result = first.intersection(second, sort=sort) tm.assert_index_equal(result, expected)
@pytest.mark.parametrize("klass", [np.array, Series, list]) def test_intersection_different_type_base(self, klass, sort): # GH 10149 index = Index([0, "a", 1, "b", 2, "c"]) first = index[:5] second = index[:3]
result = first.intersection(klass(second.values), sort=sort) assert equal_contents(result, second)
def test_intersection_nosort(self): result = Index(["c", "b", "a"]).intersection(["b", "a"]) expected = Index(["b", "a"]) tm.assert_index_equal(result, expected)
def test_intersection_equal_sort(self): idx = Index(["c", "a", "b"]) tm.assert_index_equal(idx.intersection(idx, sort=False), idx) tm.assert_index_equal(idx.intersection(idx, sort=None), idx)
def test_intersection_str_dates(self, sort): dt_dates = [datetime(2012, 2, 9), datetime(2012, 2, 22)]
i1 = Index(dt_dates, dtype=object) i2 = Index(["aa"], dtype=object) result = i2.intersection(i1, sort=sort)
assert len(result) == 0
@pytest.mark.parametrize( "index2,expected_arr", [(Index(["B", "D"]), ["B"]), (Index(["B", "D", "A"]), ["A", "B"])], ) def test_intersection_non_monotonic_non_unique(self, index2, expected_arr, sort): # non-monotonic non-unique index1 = Index(["A", "B", "A", "C"]) expected = Index(expected_arr) result = index1.intersection(index2, sort=sort) if sort is None: expected = expected.sort_values() tm.assert_index_equal(result, expected)
def test_difference_base(self, sort): # (same results for py2 and py3 but sortedness not tested elsewhere) index = Index([0, "a", 1, "b", 2, "c"]) first = index[:4] second = index[3:]
result = first.difference(second, sort) expected = Index([0, "a", 1]) if sort is None: expected = Index(safe_sort(expected)) tm.assert_index_equal(result, expected)
def test_symmetric_difference(self): # (same results for py2 and py3 but sortedness not tested elsewhere) index = Index([0, "a", 1, "b", 2, "c"]) first = index[:4] second = index[3:]
result = first.symmetric_difference(second) expected = Index([0, 1, 2, "a", "c"]) tm.assert_index_equal(result, expected)
@pytest.mark.parametrize( "method,expected,sort", [ ( "intersection", np.array( [(1, "A"), (2, "A"), (1, "B"), (2, "B")], dtype=[("num", int), ("let", "S1")], ), False, ), ( "intersection", np.array( [(1, "A"), (1, "B"), (2, "A"), (2, "B")], dtype=[("num", int), ("let", "S1")], ), None, ), ( "union", np.array( [(1, "A"), (1, "B"), (1, "C"), (2, "A"), (2, "B"), (2, "C")], dtype=[("num", int), ("let", "S1")], ), None, ), ], ) def test_tuple_union_bug(self, method, expected, sort): index1 = Index( np.array( [(1, "A"), (2, "A"), (1, "B"), (2, "B")], dtype=[("num", int), ("let", "S1")], ) ) index2 = Index( np.array( [(1, "A"), (2, "A"), (1, "B"), (2, "B"), (1, "C"), (2, "C")], dtype=[("num", int), ("let", "S1")], ) )
result = getattr(index1, method)(index2, sort=sort) assert result.ndim == 1
expected = Index(expected) tm.assert_index_equal(result, expected)
@pytest.mark.parametrize("first_list", [["b", "a"], []]) @pytest.mark.parametrize("second_list", [["a", "b"], []]) @pytest.mark.parametrize( "first_name, second_name, expected_name", [("A", "B", None), (None, "B", None), ("A", None, None)], ) def test_union_name_preservation( self, first_list, second_list, first_name, second_name, expected_name, sort ): first = Index(first_list, name=first_name) second = Index(second_list, name=second_name) union = first.union(second, sort=sort)
vals = set(first_list).union(second_list)
if sort is None and len(first_list) > 0 and len(second_list) > 0: expected = Index(sorted(vals), name=expected_name) tm.assert_index_equal(union, expected) else: expected = Index(vals, name=expected_name) tm.assert_index_equal(union.sort_values(), expected.sort_values())
@pytest.mark.parametrize( "diff_type, expected", [["difference", [1, "B"]], ["symmetric_difference", [1, 2, "B", "C"]]], ) def test_difference_object_type(self, diff_type, expected): # GH 13432 idx1 = Index([0, 1, "A", "B"]) idx2 = Index([0, 2, "A", "C"]) result = getattr(idx1, diff_type)(idx2) expected = Index(expected) tm.assert_index_equal(result, expected)12345678910111213import numpy as np
from pandas import Indeximport pandas._testing as tm
class TestWhere: def test_where_intlike_str_doesnt_cast_ints(self): idx = Index(range(3)) mask = np.array([True, False, True]) res = idx.where(mask, "2") expected = Index([0, "2", 2]) tm.assert_index_equal(res, expected)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889import numpy as npimport pytest
from pandas import ( PeriodIndex, Series, date_range, period_range, timedelta_range,)import pandas._testing as tm
class DropDuplicates: def test_drop_duplicates_metadata(self, idx): # GH#10115 result = idx.drop_duplicates() tm.assert_index_equal(idx, result) assert idx.freq == result.freq
idx_dup = idx.append(idx) result = idx_dup.drop_duplicates()
expected = idx if not isinstance(idx, PeriodIndex): # freq is reset except for PeriodIndex assert idx_dup.freq is None assert result.freq is None expected = idx._with_freq(None) else: assert result.freq == expected.freq
tm.assert_index_equal(result, expected)
@pytest.mark.parametrize( "keep, expected, index", [ ( "first", np.concatenate(([False] * 10, [True] * 5)), np.arange(0, 10, dtype=np.int64), ), ( "last", np.concatenate(([True] * 5, [False] * 10)), np.arange(5, 15, dtype=np.int64), ), ( False, np.concatenate(([True] * 5, [False] * 5, [True] * 5)), np.arange(5, 10, dtype=np.int64), ), ], ) def test_drop_duplicates(self, keep, expected, index, idx): # to check Index/Series compat idx = idx.append(idx[:5])
tm.assert_numpy_array_equal(idx.duplicated(keep=keep), expected) expected = idx[~expected]
result = idx.drop_duplicates(keep=keep) tm.assert_index_equal(result, expected)
result = Series(idx).drop_duplicates(keep=keep) expected = Series(expected, index=index) tm.assert_series_equal(result, expected)
class TestDropDuplicatesPeriodIndex(DropDuplicates): @pytest.fixture(params=["D", "3D", "h", "2h", "min", "2min", "s", "3s"]) def freq(self, request): return request.param
@pytest.fixture def idx(self, freq): return period_range("2011-01-01", periods=10, freq=freq, name="idx")
class TestDropDuplicatesDatetimeIndex(DropDuplicates): @pytest.fixture def idx(self, freq_sample): return date_range("2011-01-01", freq=freq_sample, periods=10, name="idx")
class TestDropDuplicatesTimedeltaIndex(DropDuplicates): @pytest.fixture def idx(self, freq_sample): return timedelta_range("1 day", periods=10, freq=freq_sample, name="idx")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181"""Tests shared for DatetimeIndex/TimedeltaIndex/PeriodIndex"""from datetime import ( datetime, timedelta,)
import numpy as npimport pytest
import pandas as pdfrom pandas import ( CategoricalIndex, DatetimeIndex, Index, PeriodIndex, TimedeltaIndex, date_range, period_range, timedelta_range,)import pandas._testing as tm
class EqualsTests: def test_not_equals_numeric(self, index): assert not index.equals(Index(index.asi8)) assert not index.equals(Index(index.asi8.astype("u8"))) assert not index.equals(Index(index.asi8).astype("f8"))
def test_equals(self, index): assert index.equals(index) assert index.equals(index.astype(object)) assert index.equals(CategoricalIndex(index)) assert index.equals(CategoricalIndex(index.astype(object)))
def test_not_equals_non_arraylike(self, index): assert not index.equals(list(index))
def test_not_equals_strings(self, index): other = Index([str(x) for x in index], dtype=object) assert not index.equals(other) assert not index.equals(CategoricalIndex(other))
def test_not_equals_misc_strs(self, index): other = Index(list("abc")) assert not index.equals(other)
class TestPeriodIndexEquals(EqualsTests): @pytest.fixture def index(self): return period_range("2013-01-01", periods=5, freq="D")
# TODO: de-duplicate with other test_equals2 methods @pytest.mark.parametrize("freq", ["D", "M"]) def test_equals2(self, freq): # GH#13107 idx = PeriodIndex(["2011-01-01", "2011-01-02", "NaT"], freq=freq) assert idx.equals(idx) assert idx.equals(idx.copy()) assert idx.equals(idx.astype(object)) assert idx.astype(object).equals(idx) assert idx.astype(object).equals(idx.astype(object)) assert not idx.equals(list(idx)) assert not idx.equals(pd.Series(idx))
idx2 = PeriodIndex(["2011-01-01", "2011-01-02", "NaT"], freq="h") assert not idx.equals(idx2) assert not idx.equals(idx2.copy()) assert not idx.equals(idx2.astype(object)) assert not idx.astype(object).equals(idx2) assert not idx.equals(list(idx2)) assert not idx.equals(pd.Series(idx2))
# same internal, different tz idx3 = PeriodIndex._simple_new( idx._values._simple_new(idx._values.asi8, dtype=pd.PeriodDtype("h")) ) tm.assert_numpy_array_equal(idx.asi8, idx3.asi8) assert not idx.equals(idx3) assert not idx.equals(idx3.copy()) assert not idx.equals(idx3.astype(object)) assert not idx.astype(object).equals(idx3) assert not idx.equals(list(idx3)) assert not idx.equals(pd.Series(idx3))
class TestDatetimeIndexEquals(EqualsTests): @pytest.fixture def index(self): return date_range("2013-01-01", periods=5)
def test_equals2(self): # GH#13107 idx = DatetimeIndex(["2011-01-01", "2011-01-02", "NaT"]) assert idx.equals(idx) assert idx.equals(idx.copy()) assert idx.equals(idx.astype(object)) assert idx.astype(object).equals(idx) assert idx.astype(object).equals(idx.astype(object)) assert not idx.equals(list(idx)) assert not idx.equals(pd.Series(idx))
idx2 = DatetimeIndex(["2011-01-01", "2011-01-02", "NaT"], tz="US/Pacific") assert not idx.equals(idx2) assert not idx.equals(idx2.copy()) assert not idx.equals(idx2.astype(object)) assert not idx.astype(object).equals(idx2) assert not idx.equals(list(idx2)) assert not idx.equals(pd.Series(idx2))
# same internal, different tz idx3 = DatetimeIndex(idx.asi8, tz="US/Pacific") tm.assert_numpy_array_equal(idx.asi8, idx3.asi8) assert not idx.equals(idx3) assert not idx.equals(idx3.copy()) assert not idx.equals(idx3.astype(object)) assert not idx.astype(object).equals(idx3) assert not idx.equals(list(idx3)) assert not idx.equals(pd.Series(idx3))
# check that we do not raise when comparing with OutOfBounds objects oob = Index([datetime(2500, 1, 1)] * 3, dtype=object) assert not idx.equals(oob) assert not idx2.equals(oob) assert not idx3.equals(oob)
# check that we do not raise when comparing with OutOfBounds dt64 oob2 = oob.map(np.datetime64) assert not idx.equals(oob2) assert not idx2.equals(oob2) assert not idx3.equals(oob2)
@pytest.mark.parametrize("freq", ["B", "C"]) def test_not_equals_bday(self, freq): rng = date_range("2009-01-01", "2010-01-01", freq=freq) assert not rng.equals(list(rng))
class TestTimedeltaIndexEquals(EqualsTests): @pytest.fixture def index(self): return timedelta_range("1 day", periods=10)
def test_equals2(self): # GH#13107 idx = TimedeltaIndex(["1 days", "2 days", "NaT"]) assert idx.equals(idx) assert idx.equals(idx.copy()) assert idx.equals(idx.astype(object)) assert idx.astype(object).equals(idx) assert idx.astype(object).equals(idx.astype(object)) assert not idx.equals(list(idx)) assert not idx.equals(pd.Series(idx))
idx2 = TimedeltaIndex(["2 days", "1 days", "NaT"]) assert not idx.equals(idx2) assert not idx.equals(idx2.copy()) assert not idx.equals(idx2.astype(object)) assert not idx.astype(object).equals(idx2) assert not idx.astype(object).equals(idx2.astype(object)) assert not idx.equals(list(idx2)) assert not idx.equals(pd.Series(idx2))
# Check that we dont raise OverflowError on comparisons outside the # implementation range GH#28532 oob = Index([timedelta(days=10**6)] * 3, dtype=object) assert not idx.equals(oob) assert not idx2.equals(oob)
oob2 = Index([np.timedelta64(x) for x in oob], dtype=object) assert (oob == oob2).all() assert not idx.equals(oob2) assert not idx2.equals(oob2)
oob3 = oob.map(np.timedelta64) assert (oob3 == oob).all() assert not idx.equals(oob3) assert not idx2.equals(oob3)123456789101112131415161718192021222324252627282930313233343536373839404142434445import numpy as npimport pytest
import pandas as pdfrom pandas import ( DatetimeIndex, Index,)import pandas._testing as tm
dtlike_dtypes = [ np.dtype("timedelta64[ns]"), np.dtype("datetime64[ns]"), pd.DatetimeTZDtype("ns", "Asia/Tokyo"), pd.PeriodDtype("ns"),]
@pytest.mark.parametrize("ldtype", dtlike_dtypes)@pytest.mark.parametrize("rdtype", dtlike_dtypes)def test_get_indexer_non_unique_wrong_dtype(ldtype, rdtype): vals = np.tile(3600 * 10**9 * np.arange(3, dtype=np.int64), 2)
def construct(dtype): if dtype is dtlike_dtypes[-1]: # PeriodArray will try to cast ints to strings return DatetimeIndex(vals).astype(dtype) return Index(vals, dtype=dtype)
left = construct(ldtype) right = construct(rdtype)
result = left.get_indexer_non_unique(right)
if ldtype is rdtype: ex1 = np.array([0, 3, 1, 4, 2, 5] * 2, dtype=np.intp) ex2 = np.array([], dtype=np.intp) tm.assert_numpy_array_equal(result[0], ex1) tm.assert_numpy_array_equal(result[1], ex2)
else: no_matches = np.array([-1] * 6, dtype=np.intp) missing = np.arange(6, dtype=np.intp) tm.assert_numpy_array_equal(result[0], no_matches) tm.assert_numpy_array_equal(result[1], missing)12345678910111213141516171819202122232425262728293031323334353637383940414243444546from pandas import ( Index, NaT, date_range,)
def test_is_monotonic_with_nat(): # GH#31437 # PeriodIndex.is_monotonic_increasing should behave analogously to DatetimeIndex, # in particular never be monotonic when we have NaT dti = date_range("2016-01-01", periods=3) pi = dti.to_period("D") tdi = Index(dti.view("timedelta64[ns]"))
for obj in [pi, pi._engine, dti, dti._engine, tdi, tdi._engine]: if isinstance(obj, Index): # i.e. not Engines assert obj.is_monotonic_increasing assert obj.is_monotonic_increasing assert not obj.is_monotonic_decreasing assert obj.is_unique
dti1 = dti.insert(0, NaT) pi1 = dti1.to_period("D") tdi1 = Index(dti1.view("timedelta64[ns]"))
for obj in [pi1, pi1._engine, dti1, dti1._engine, tdi1, tdi1._engine]: if isinstance(obj, Index): # i.e. not Engines assert not obj.is_monotonic_increasing assert not obj.is_monotonic_increasing assert not obj.is_monotonic_decreasing assert obj.is_unique
dti2 = dti.insert(3, NaT) pi2 = dti2.to_period("h") tdi2 = Index(dti2.view("timedelta64[ns]"))
for obj in [pi2, pi2._engine, dti2, dti2._engine, tdi2, tdi2._engine]: if isinstance(obj, Index): # i.e. not Engines assert not obj.is_monotonic_increasing assert not obj.is_monotonic_increasing assert not obj.is_monotonic_decreasing assert obj.is_unique1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253import numpy as npimport pytest
from pandas import ( DatetimeIndex, NaT, PeriodIndex, TimedeltaIndex,)import pandas._testing as tm
class NATests: def test_nat(self, index_without_na): empty_index = index_without_na[:0]
index_with_na = index_without_na.copy(deep=True) index_with_na._data[1] = NaT
assert empty_index._na_value is NaT assert index_with_na._na_value is NaT assert index_without_na._na_value is NaT
idx = index_without_na assert idx._can_hold_na
tm.assert_numpy_array_equal(idx._isnan, np.array([False, False])) assert idx.hasnans is False
idx = index_with_na assert idx._can_hold_na
tm.assert_numpy_array_equal(idx._isnan, np.array([False, True])) assert idx.hasnans is True
class TestDatetimeIndexNA(NATests): @pytest.fixture def index_without_na(self, tz_naive_fixture): tz = tz_naive_fixture return DatetimeIndex(["2011-01-01", "2011-01-02"], tz=tz)
class TestTimedeltaIndexNA(NATests): @pytest.fixture def index_without_na(self): return TimedeltaIndex(["1 days", "2 days"])
class TestPeriodIndexNA(NATests): @pytest.fixture def index_without_na(self): return PeriodIndex(["2011-01-01", "2011-01-02"], freq="D")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315import numpy as npimport pytest
from pandas import ( DatetimeIndex, Index, NaT, PeriodIndex, TimedeltaIndex, timedelta_range,)import pandas._testing as tm
def check_freq_ascending(ordered, orig, ascending): """ Check the expected freq on a PeriodIndex/DatetimeIndex/TimedeltaIndex when the original index is generated (or generate-able) with period_range/date_range/timedelta_range. """ if isinstance(ordered, PeriodIndex): assert ordered.freq == orig.freq elif isinstance(ordered, (DatetimeIndex, TimedeltaIndex)): if ascending: assert ordered.freq.n == orig.freq.n else: assert ordered.freq.n == -1 * orig.freq.n
def check_freq_nonmonotonic(ordered, orig): """ Check the expected freq on a PeriodIndex/DatetimeIndex/TimedeltaIndex when the original index is _not_ generated (or generate-able) with period_range/date_range//timedelta_range. """ if isinstance(ordered, PeriodIndex): assert ordered.freq == orig.freq elif isinstance(ordered, (DatetimeIndex, TimedeltaIndex)): assert ordered.freq is None
class TestSortValues: @pytest.fixture(params=[DatetimeIndex, TimedeltaIndex, PeriodIndex]) def non_monotonic_idx(self, request): if request.param is DatetimeIndex: return DatetimeIndex(["2000-01-04", "2000-01-01", "2000-01-02"]) elif request.param is PeriodIndex: dti = DatetimeIndex(["2000-01-04", "2000-01-01", "2000-01-02"]) return dti.to_period("D") else: return TimedeltaIndex( ["1 day 00:00:05", "1 day 00:00:01", "1 day 00:00:02"] )
def test_argmin_argmax(self, non_monotonic_idx): assert non_monotonic_idx.argmin() == 1 assert non_monotonic_idx.argmax() == 0
def test_sort_values(self, non_monotonic_idx): idx = non_monotonic_idx ordered = idx.sort_values() assert ordered.is_monotonic_increasing ordered = idx.sort_values(ascending=False) assert ordered[::-1].is_monotonic_increasing
ordered, dexer = idx.sort_values(return_indexer=True) assert ordered.is_monotonic_increasing tm.assert_numpy_array_equal(dexer, np.array([1, 2, 0], dtype=np.intp))
ordered, dexer = idx.sort_values(return_indexer=True, ascending=False) assert ordered[::-1].is_monotonic_increasing tm.assert_numpy_array_equal(dexer, np.array([0, 2, 1], dtype=np.intp))
def check_sort_values_with_freq(self, idx): ordered = idx.sort_values() tm.assert_index_equal(ordered, idx) check_freq_ascending(ordered, idx, True)
ordered = idx.sort_values(ascending=False) expected = idx[::-1] tm.assert_index_equal(ordered, expected) check_freq_ascending(ordered, idx, False)
ordered, indexer = idx.sort_values(return_indexer=True) tm.assert_index_equal(ordered, idx) tm.assert_numpy_array_equal(indexer, np.array([0, 1, 2], dtype=np.intp)) check_freq_ascending(ordered, idx, True)
ordered, indexer = idx.sort_values(return_indexer=True, ascending=False) expected = idx[::-1] tm.assert_index_equal(ordered, expected) tm.assert_numpy_array_equal(indexer, np.array([2, 1, 0], dtype=np.intp)) check_freq_ascending(ordered, idx, False)
@pytest.mark.parametrize("freq", ["D", "h"]) def test_sort_values_with_freq_timedeltaindex(self, freq): # GH#10295 idx = timedelta_range(start=f"1{freq}", periods=3, freq=freq).rename("idx")
self.check_sort_values_with_freq(idx)
@pytest.mark.parametrize( "idx", [ DatetimeIndex( ["2011-01-01", "2011-01-02", "2011-01-03"], freq="D", name="idx" ), DatetimeIndex( ["2011-01-01 09:00", "2011-01-01 10:00", "2011-01-01 11:00"], freq="h", name="tzidx", tz="Asia/Tokyo", ), ], ) def test_sort_values_with_freq_datetimeindex(self, idx): self.check_sort_values_with_freq(idx)
@pytest.mark.parametrize("freq", ["D", "2D", "4D"]) def test_sort_values_with_freq_periodindex(self, freq): # here with_freq refers to being period_range-like idx = PeriodIndex( ["2011-01-01", "2011-01-02", "2011-01-03"], freq=freq, name="idx" ) self.check_sort_values_with_freq(idx)
@pytest.mark.parametrize( "idx", [ PeriodIndex(["2011", "2012", "2013"], name="pidx", freq="Y"), Index([2011, 2012, 2013], name="idx"), # for compatibility check ], ) def test_sort_values_with_freq_periodindex2(self, idx): # here with_freq indicates this is period_range-like self.check_sort_values_with_freq(idx)
def check_sort_values_without_freq(self, idx, expected): ordered = idx.sort_values(na_position="first") tm.assert_index_equal(ordered, expected) check_freq_nonmonotonic(ordered, idx)
if not idx.isna().any(): ordered = idx.sort_values() tm.assert_index_equal(ordered, expected) check_freq_nonmonotonic(ordered, idx)
ordered = idx.sort_values(ascending=False) tm.assert_index_equal(ordered, expected[::-1]) check_freq_nonmonotonic(ordered, idx)
ordered, indexer = idx.sort_values(return_indexer=True, na_position="first") tm.assert_index_equal(ordered, expected)
exp = np.array([0, 4, 3, 1, 2], dtype=np.intp) tm.assert_numpy_array_equal(indexer, exp) check_freq_nonmonotonic(ordered, idx)
if not idx.isna().any(): ordered, indexer = idx.sort_values(return_indexer=True) tm.assert_index_equal(ordered, expected)
exp = np.array([0, 4, 3, 1, 2], dtype=np.intp) tm.assert_numpy_array_equal(indexer, exp) check_freq_nonmonotonic(ordered, idx)
ordered, indexer = idx.sort_values(return_indexer=True, ascending=False) tm.assert_index_equal(ordered, expected[::-1])
exp = np.array([2, 1, 3, 0, 4], dtype=np.intp) tm.assert_numpy_array_equal(indexer, exp) check_freq_nonmonotonic(ordered, idx)
def test_sort_values_without_freq_timedeltaindex(self): # GH#10295
idx = TimedeltaIndex( ["1 hour", "3 hour", "5 hour", "2 hour ", "1 hour"], name="idx1" ) expected = TimedeltaIndex( ["1 hour", "1 hour", "2 hour", "3 hour", "5 hour"], name="idx1" ) self.check_sort_values_without_freq(idx, expected)
@pytest.mark.parametrize( "index_dates,expected_dates", [ ( ["2011-01-01", "2011-01-03", "2011-01-05", "2011-01-02", "2011-01-01"], ["2011-01-01", "2011-01-01", "2011-01-02", "2011-01-03", "2011-01-05"], ), ( ["2011-01-01", "2011-01-03", "2011-01-05", "2011-01-02", "2011-01-01"], ["2011-01-01", "2011-01-01", "2011-01-02", "2011-01-03", "2011-01-05"], ), ( [NaT, "2011-01-03", "2011-01-05", "2011-01-02", NaT], [NaT, NaT, "2011-01-02", "2011-01-03", "2011-01-05"], ), ], ) def test_sort_values_without_freq_datetimeindex( self, index_dates, expected_dates, tz_naive_fixture ): tz = tz_naive_fixture
# without freq idx = DatetimeIndex(index_dates, tz=tz, name="idx") expected = DatetimeIndex(expected_dates, tz=tz, name="idx")
self.check_sort_values_without_freq(idx, expected)
@pytest.mark.parametrize( "idx,expected", [ ( PeriodIndex( [ "2011-01-01", "2011-01-03", "2011-01-05", "2011-01-02", "2011-01-01", ], freq="D", name="idx1", ), PeriodIndex( [ "2011-01-01", "2011-01-01", "2011-01-02", "2011-01-03", "2011-01-05", ], freq="D", name="idx1", ), ), ( PeriodIndex( [ "2011-01-01", "2011-01-03", "2011-01-05", "2011-01-02", "2011-01-01", ], freq="D", name="idx2", ), PeriodIndex( [ "2011-01-01", "2011-01-01", "2011-01-02", "2011-01-03", "2011-01-05", ], freq="D", name="idx2", ), ), ( PeriodIndex( [NaT, "2011-01-03", "2011-01-05", "2011-01-02", NaT], freq="D", name="idx3", ), PeriodIndex( [NaT, NaT, "2011-01-02", "2011-01-03", "2011-01-05"], freq="D", name="idx3", ), ), ( PeriodIndex( ["2011", "2013", "2015", "2012", "2011"], name="pidx", freq="Y" ), PeriodIndex( ["2011", "2011", "2012", "2013", "2015"], name="pidx", freq="Y" ), ), ( # For compatibility check Index([2011, 2013, 2015, 2012, 2011], name="idx"), Index([2011, 2011, 2012, 2013, 2015], name="idx"), ), ], ) def test_sort_values_without_freq_periodindex(self, idx, expected): # here without_freq means not generateable by period_range self.check_sort_values_without_freq(idx, expected)
def test_sort_values_without_freq_periodindex_nat(self): # doesn't quite fit into check_sort_values_without_freq idx = PeriodIndex(["2011", "2013", "NaT", "2011"], name="pidx", freq="D") expected = PeriodIndex(["NaT", "2011", "2011", "2013"], name="pidx", freq="D")
ordered = idx.sort_values(na_position="first") tm.assert_index_equal(ordered, expected) check_freq_nonmonotonic(ordered, idx)
ordered = idx.sort_values(ascending=False) tm.assert_index_equal(ordered, expected[::-1]) check_freq_nonmonotonic(ordered, idx)
def test_order_stability_compat(): # GH#35922. sort_values is stable both for normal and datetime-like Index pidx = PeriodIndex(["2011", "2013", "2015", "2012", "2011"], name="pidx", freq="Y") iidx = Index([2011, 2013, 2015, 2012, 2011], name="idx") ordered1, indexer1 = pidx.sort_values(return_indexer=True, ascending=False) ordered2, indexer2 = iidx.sort_values(return_indexer=True, ascending=False) tm.assert_numpy_array_equal(indexer1, indexer2)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103import numpy as np
from pandas import ( DatetimeIndex, NaT, PeriodIndex, Series, TimedeltaIndex, date_range, period_range, timedelta_range,)import pandas._testing as tm
class TestValueCounts: # GH#7735
def test_value_counts_unique_datetimeindex(self, tz_naive_fixture): tz = tz_naive_fixture orig = date_range("2011-01-01 09:00", freq="h", periods=10, tz=tz) self._check_value_counts_with_repeats(orig)
def test_value_counts_unique_timedeltaindex(self): orig = timedelta_range("1 days 09:00:00", freq="h", periods=10) self._check_value_counts_with_repeats(orig)
def test_value_counts_unique_periodindex(self): orig = period_range("2011-01-01 09:00", freq="h", periods=10) self._check_value_counts_with_repeats(orig)
def _check_value_counts_with_repeats(self, orig): # create repeated values, 'n'th element is repeated by n+1 times idx = type(orig)( np.repeat(orig._values, range(1, len(orig) + 1)), dtype=orig.dtype )
exp_idx = orig[::-1] if not isinstance(exp_idx, PeriodIndex): exp_idx = exp_idx._with_freq(None) expected = Series(range(10, 0, -1), index=exp_idx, dtype="int64", name="count")
for obj in [idx, Series(idx)]: tm.assert_series_equal(obj.value_counts(), expected)
tm.assert_index_equal(idx.unique(), orig)
def test_value_counts_unique_datetimeindex2(self, tz_naive_fixture): tz = tz_naive_fixture idx = DatetimeIndex( [ "2013-01-01 09:00", "2013-01-01 09:00", "2013-01-01 09:00", "2013-01-01 08:00", "2013-01-01 08:00", NaT, ], tz=tz, ) self._check_value_counts_dropna(idx)
def test_value_counts_unique_timedeltaindex2(self): idx = TimedeltaIndex( [ "1 days 09:00:00", "1 days 09:00:00", "1 days 09:00:00", "1 days 08:00:00", "1 days 08:00:00", NaT, ] ) self._check_value_counts_dropna(idx)
def test_value_counts_unique_periodindex2(self): idx = PeriodIndex( [ "2013-01-01 09:00", "2013-01-01 09:00", "2013-01-01 09:00", "2013-01-01 08:00", "2013-01-01 08:00", NaT, ], freq="h", ) self._check_value_counts_dropna(idx)
def _check_value_counts_dropna(self, idx): exp_idx = idx[[2, 3]] expected = Series([3, 2], index=exp_idx, name="count")
for obj in [idx, Series(idx)]: tm.assert_series_equal(obj.value_counts(), expected)
exp_idx = idx[[2, 3, -1]] expected = Series([3, 2, 1], index=exp_idx, name="count")
for obj in [idx, Series(idx)]: tm.assert_series_equal(obj.value_counts(dropna=False), expected)
tm.assert_index_equal(idx.unique(), exp_idx)lib/python3.12/site-packages/pandas/tests/indexes/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/__pycache__/conftest.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/__pycache__/test_any_index.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/__pycache__/test_base.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/__pycache__/test_common.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/__pycache__/test_datetimelike.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/__pycache__/test_engines.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/__pycache__/test_frozen.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/__pycache__/test_index_new.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/__pycache__/test_indexing.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/__pycache__/test_numpy_compat.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/__pycache__/test_old_base.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/__pycache__/test_setops.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/__pycache__/test_subclass.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/base_class/__init__.pyAdded
lib/python3.12/site-packages/pandas/tests/indexes/base_class/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/base_class/__pycache__/test_constructors.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/base_class/__pycache__/test_formats.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/base_class/__pycache__/test_indexing.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/base_class/__pycache__/test_pickle.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/base_class/__pycache__/test_reshape.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/base_class/__pycache__/test_setops.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/base_class/__pycache__/test_where.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/base_class/test_constructors.pyAdded+80
lib/python3.12/site-packages/pandas/tests/indexes/base_class/test_formats.pyAdded+163
lib/python3.12/site-packages/pandas/tests/indexes/base_class/test_indexing.pyAdded+104
lib/python3.12/site-packages/pandas/tests/indexes/base_class/test_pickle.pyAdded+11
lib/python3.12/site-packages/pandas/tests/indexes/base_class/test_reshape.pyAdded+95
lib/python3.12/site-packages/pandas/tests/indexes/base_class/test_setops.pyAdded+266
lib/python3.12/site-packages/pandas/tests/indexes/base_class/test_where.pyAdded+13
lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/__init__.pyAdded
lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_drop_duplicates.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_equals.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_indexing.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_is_monotonic.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_nat.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_sort_values.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/__pycache__/test_value_counts.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/test_drop_duplicates.pyAdded+89
lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/test_equals.pyAdded+181
lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/test_indexing.pyAdded+45
lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/test_is_monotonic.pyAdded+46
lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/test_nat.pyAdded+53
lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/test_sort_values.pyAdded+315
lib/python3.12/site-packages/pandas/tests/indexes/datetimelike_/test_value_counts.pyAdded+103
lib/python3.12/site-packages/pandas/tests/indexes/interval/__init__.pyAdded
lib/python3.12/site-packages/pandas/tests/indexes/interval/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/interval/__pycache__/test_astype.cpython-312.pycAdded
lib/python3.12/site-packages/pandas/tests/indexes/interval/__pycache__/test_constructors.cpython-312.pycAdded