diff --git a/pandas/conftest.py b/pandas/conftest.py index e4cb3270b9acf..d74c43069574f 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -408,7 +408,7 @@ def _create_mi_with_dt64tz_level(): @pytest.fixture(params=indices_dict.keys()) -def indices(request): +def index(request): """ Fixture for many "simple" kinds of indices. @@ -423,7 +423,7 @@ def indices(request): # Needed to generate cartesian product of indices -index_fixture2 = indices +index_fixture2 = index # ---------------------------------------------------------------- @@ -478,11 +478,11 @@ def _create_series(index): @pytest.fixture -def series_with_simple_index(indices): +def series_with_simple_index(index): """ Fixture for tests on series with changing types of indices. """ - return _create_series(indices) + return _create_series(index) _narrow_dtypes = [ diff --git a/pandas/tests/base/test_misc.py b/pandas/tests/base/test_misc.py index 527f806483d94..78a830c7f43d8 100644 --- a/pandas/tests/base/test_misc.py +++ b/pandas/tests/base/test_misc.py @@ -173,8 +173,7 @@ def test_searchsorted(index_or_series_obj): assert 0 <= index <= len(obj) -def test_access_by_position(indices): - index = indices +def test_access_by_position(index): if len(index) == 0: pytest.skip("Test doesn't make sense on empty data") diff --git a/pandas/tests/generic/test_generic.py b/pandas/tests/generic/test_generic.py index 05588ead54be4..94747a52136c4 100644 --- a/pandas/tests/generic/test_generic.py +++ b/pandas/tests/generic/test_generic.py @@ -251,13 +251,13 @@ def test_metadata_propagation(self): self.check_metadata(v1 & v2) self.check_metadata(v1 | v2) - def test_head_tail(self, indices): + def test_head_tail(self, index): # GH5370 - o = self._construct(shape=len(indices)) + o = self._construct(shape=len(index)) axis = o._get_axis_name(0) - setattr(o, axis, indices) + setattr(o, axis, index) o.head() @@ -273,8 +273,8 @@ def test_head_tail(self, indices): self._compare(o.tail(len(o) + 1), o) # neg index - self._compare(o.head(-3), o.head(len(indices) - 3)) - self._compare(o.tail(-3), o.tail(len(indices) - 3)) + self._compare(o.head(-3), o.head(len(index) - 3)) + self._compare(o.tail(-3), o.tail(len(index) - 3)) def test_sample(self): # Fixes issue: 2419 diff --git a/pandas/tests/generic/test_to_xarray.py b/pandas/tests/generic/test_to_xarray.py index 2fde96a1c8f89..ab56a752f7e90 100644 --- a/pandas/tests/generic/test_to_xarray.py +++ b/pandas/tests/generic/test_to_xarray.py @@ -10,10 +10,10 @@ class TestDataFrameToXArray: @td.skip_if_no("xarray", "0.10.0") - def test_to_xarray_index_types(self, indices): - if isinstance(indices, pd.MultiIndex): + def test_to_xarray_index_types(self, index): + if isinstance(index, pd.MultiIndex): pytest.skip("MultiIndex is tested separately") - if len(indices) == 0: + if len(index) == 0: pytest.skip("Test doesn't make sense for empty index") from xarray import Dataset @@ -31,7 +31,7 @@ def test_to_xarray_index_types(self, indices): } ) - df.index = indices[:3] + df.index = index[:3] df.index.name = "foo" df.columns.name = "bar" result = df.to_xarray() @@ -93,17 +93,17 @@ def test_to_xarray(self): class TestSeriesToXArray: @td.skip_if_no("xarray", "0.10.0") - def test_to_xarray_index_types(self, indices): - if isinstance(indices, pd.MultiIndex): + def test_to_xarray_index_types(self, index): + if isinstance(index, pd.MultiIndex): pytest.skip("MultiIndex is tested separately") from xarray import DataArray - s = Series(range(len(indices)), index=indices, dtype="int64") + s = Series(range(len(index)), index=index, dtype="int64") s.index.name = "foo" result = s.to_xarray() repr(result) - assert len(result) == len(indices) + assert len(result) == len(index) assert len(result.coords) == 1 tm.assert_almost_equal(list(result.coords.keys()), ["foo"]) assert isinstance(result, DataArray) diff --git a/pandas/tests/indexes/categorical/test_category.py b/pandas/tests/indexes/categorical/test_category.py index 7a1ccba08853b..7f30a77872bc1 100644 --- a/pandas/tests/indexes/categorical/test_category.py +++ b/pandas/tests/indexes/categorical/test_category.py @@ -15,7 +15,7 @@ class TestCategoricalIndex(Base): _holder = CategoricalIndex @pytest.fixture - def indices(self, request): + def index(self, request): return tm.makeCategoricalIndex(100) def create_index(self, categories=None, ordered=False): @@ -354,7 +354,7 @@ def test_identical(self): assert ci1.identical(ci1.copy()) assert not ci1.identical(ci2) - def test_ensure_copied_data(self, indices): + def test_ensure_copied_data(self, index): # gh-12309: Check the "copy" argument of each # Index.__new__ is honored. # @@ -364,12 +364,12 @@ def test_ensure_copied_data(self, indices): # FIXME: is this test still meaningful? _base = lambda ar: ar if getattr(ar, "base", None) is None else ar.base - result = CategoricalIndex(indices.values, copy=True) - tm.assert_index_equal(indices, result) - assert _base(indices.values) is not _base(result.values) + result = CategoricalIndex(index.values, copy=True) + tm.assert_index_equal(index, result) + assert _base(index.values) is not _base(result.values) - result = CategoricalIndex(indices.values, copy=False) - assert _base(indices.values) is _base(result.values) + result = CategoricalIndex(index.values, copy=False) + assert _base(index.values) is _base(result.values) def test_equals_categorical(self): ci1 = CategoricalIndex(["a", "b"], categories=["a", "b"], ordered=True) diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index ae297bf1069b0..30c58506f619d 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -180,21 +180,21 @@ def test_reindex_base(self): with pytest.raises(ValueError, match="Invalid fill method"): idx.get_indexer(idx, method="invalid") - def test_get_indexer_consistency(self, indices): + def test_get_indexer_consistency(self, index): # See GH 16819 - if isinstance(indices, IntervalIndex): + if isinstance(index, IntervalIndex): return - if indices.is_unique or isinstance(indices, CategoricalIndex): - indexer = indices.get_indexer(indices[0:2]) + if index.is_unique or isinstance(index, CategoricalIndex): + indexer = index.get_indexer(index[0:2]) assert isinstance(indexer, np.ndarray) assert indexer.dtype == np.intp else: e = "Reindexing only valid with uniquely valued Index objects" with pytest.raises(InvalidIndexError, match=e): - indices.get_indexer(indices[0:2]) + index.get_indexer(index[0:2]) - indexer, _ = indices.get_indexer_non_unique(indices[0:2]) + indexer, _ = index.get_indexer_non_unique(index[0:2]) assert isinstance(indexer, np.ndarray) assert indexer.dtype == np.intp @@ -224,20 +224,20 @@ def test_repr_max_seq_item_setting(self): repr(idx) assert "..." not in str(idx) - def test_copy_name(self, indices): + def test_copy_name(self, index): # gh-12309: Check that the "name" argument # passed at initialization is honored. - if isinstance(indices, MultiIndex): + if isinstance(index, MultiIndex): return - first = type(indices)(indices, copy=True, name="mario") + first = type(index)(index, copy=True, name="mario") second = type(first)(first, copy=False) # Even though "copy=False", we want a new object. assert first is not second # Not using tm.assert_index_equal() since names differ. - assert indices.equals(first) + assert index.equals(first) assert first.name == "mario" assert second.name == "mario" @@ -245,78 +245,76 @@ def test_copy_name(self, indices): s1 = Series(2, index=first) s2 = Series(3, index=second[:-1]) - if not isinstance(indices, CategoricalIndex): + if not isinstance(index, CategoricalIndex): # See gh-13365 s3 = s1 * s2 assert s3.index.name == "mario" - def test_ensure_copied_data(self, indices): + def test_ensure_copied_data(self, index): # Check the "copy" argument of each Index.__new__ is honoured # GH12309 init_kwargs = {} - if isinstance(indices, PeriodIndex): + if isinstance(index, PeriodIndex): # Needs "freq" specification: - init_kwargs["freq"] = indices.freq - elif isinstance(indices, (RangeIndex, MultiIndex, CategoricalIndex)): + init_kwargs["freq"] = index.freq + elif isinstance(index, (RangeIndex, MultiIndex, CategoricalIndex)): # RangeIndex cannot be initialized from data # MultiIndex and CategoricalIndex are tested separately return - index_type = type(indices) - result = index_type(indices.values, copy=True, **init_kwargs) - if is_datetime64tz_dtype(indices.dtype): - result = result.tz_localize("UTC").tz_convert(indices.tz) - if isinstance(indices, (DatetimeIndex, TimedeltaIndex)): - indices = indices._with_freq(None) + index_type = type(index) + result = index_type(index.values, copy=True, **init_kwargs) + if is_datetime64tz_dtype(index.dtype): + result = result.tz_localize("UTC").tz_convert(index.tz) + if isinstance(index, (DatetimeIndex, TimedeltaIndex)): + index = index._with_freq(None) - tm.assert_index_equal(indices, result) + tm.assert_index_equal(index, result) - if isinstance(indices, PeriodIndex): + if isinstance(index, PeriodIndex): # .values an object array of Period, thus copied - result = index_type(ordinal=indices.asi8, copy=False, **init_kwargs) - tm.assert_numpy_array_equal(indices.asi8, result.asi8, check_same="same") - elif isinstance(indices, IntervalIndex): + result = index_type(ordinal=index.asi8, copy=False, **init_kwargs) + tm.assert_numpy_array_equal(index.asi8, result.asi8, check_same="same") + elif isinstance(index, IntervalIndex): # checked in test_interval.py pass else: - result = index_type(indices.values, copy=False, **init_kwargs) - tm.assert_numpy_array_equal( - indices.values, result.values, check_same="same" - ) + result = index_type(index.values, copy=False, **init_kwargs) + tm.assert_numpy_array_equal(index.values, result.values, check_same="same") - def test_memory_usage(self, indices): - indices._engine.clear_mapping() - result = indices.memory_usage() - if indices.empty: + def test_memory_usage(self, index): + index._engine.clear_mapping() + result = index.memory_usage() + if index.empty: # we report 0 for no-length assert result == 0 return # non-zero length - indices.get_loc(indices[0]) - result2 = indices.memory_usage() - result3 = indices.memory_usage(deep=True) + index.get_loc(index[0]) + result2 = index.memory_usage() + result3 = index.memory_usage(deep=True) # RangeIndex, IntervalIndex # don't have engines - if not isinstance(indices, (RangeIndex, IntervalIndex)): + if not isinstance(index, (RangeIndex, IntervalIndex)): assert result2 > result - if indices.inferred_type == "object": + if index.inferred_type == "object": assert result3 > result2 - def test_argsort(self, request, indices): + def test_argsort(self, request, index): # separately tested - if isinstance(indices, CategoricalIndex): + if isinstance(index, CategoricalIndex): return - result = indices.argsort() - expected = np.array(indices).argsort() + result = index.argsort() + expected = np.array(index).argsort() tm.assert_numpy_array_equal(result, expected, check_dtype=False) - def test_numpy_argsort(self, indices): - result = np.argsort(indices) - expected = indices.argsort() + def test_numpy_argsort(self, index): + result = np.argsort(index) + expected = index.argsort() tm.assert_numpy_array_equal(result, expected) # these are the only two types that perform @@ -326,34 +324,34 @@ def test_numpy_argsort(self, indices): # defined in pandas.core.indexes/base.py - they # cannot be changed at the moment due to # backwards compatibility concerns - if isinstance(type(indices), (CategoricalIndex, RangeIndex)): + if isinstance(type(index), (CategoricalIndex, RangeIndex)): msg = "the 'axis' parameter is not supported" with pytest.raises(ValueError, match=msg): - np.argsort(indices, axis=1) + np.argsort(index, axis=1) msg = "the 'kind' parameter is not supported" with pytest.raises(ValueError, match=msg): - np.argsort(indices, kind="mergesort") + np.argsort(index, kind="mergesort") msg = "the 'order' parameter is not supported" with pytest.raises(ValueError, match=msg): - np.argsort(indices, order=("a", "b")) + np.argsort(index, order=("a", "b")) - def test_take(self, indices): + def test_take(self, index): indexer = [4, 3, 0, 2] - if len(indices) < 5: + if len(index) < 5: # not enough elements; ignore return - result = indices.take(indexer) - expected = indices[indexer] + result = index.take(indexer) + expected = index[indexer] assert result.equals(expected) - if not isinstance(indices, (DatetimeIndex, PeriodIndex, TimedeltaIndex)): + if not isinstance(index, (DatetimeIndex, PeriodIndex, TimedeltaIndex)): # GH 10791 msg = r"'(.*Index)' object has no attribute 'freq'" with pytest.raises(AttributeError, match=msg): - indices.freq + index.freq def test_take_invalid_kwargs(self): idx = self.create_index() @@ -413,22 +411,22 @@ def test_where(self, klass): @pytest.mark.parametrize( "method", ["intersection", "union", "difference", "symmetric_difference"] ) - def test_set_ops_error_cases(self, case, method, indices): + def test_set_ops_error_cases(self, case, method, index): # non-iterable input msg = "Input must be Index or array-like" with pytest.raises(TypeError, match=msg): - getattr(indices, method)(case) + getattr(index, method)(case) - def test_intersection_base(self, indices): - if isinstance(indices, CategoricalIndex): + def test_intersection_base(self, index): + if isinstance(index, CategoricalIndex): return - first = indices[:5] - second = indices[:3] + first = index[:5] + second = index[:3] intersect = first.intersection(second) assert tm.equalContents(intersect, second) - if is_datetime64tz_dtype(indices.dtype): + if is_datetime64tz_dtype(index.dtype): # The second.values below will drop tz, so the rest of this test # is not applicable. return @@ -439,19 +437,19 @@ def test_intersection_base(self, indices): result = first.intersection(case) assert tm.equalContents(result, second) - if isinstance(indices, MultiIndex): + if isinstance(index, MultiIndex): msg = "other must be a MultiIndex or a list of tuples" with pytest.raises(TypeError, match=msg): first.intersection([1, 2, 3]) - def test_union_base(self, indices): - first = indices[3:] - second = indices[:5] - everything = indices + def test_union_base(self, index): + first = index[3:] + second = index[:5] + everything = index union = first.union(second) assert tm.equalContents(union, everything) - if is_datetime64tz_dtype(indices.dtype): + if is_datetime64tz_dtype(index.dtype): # The second.values below will drop tz, so the rest of this test # is not applicable. return @@ -459,29 +457,29 @@ def test_union_base(self, indices): # GH 10149 cases = [klass(second.values) for klass in [np.array, Series, list]] for case in cases: - if not isinstance(indices, CategoricalIndex): + if not isinstance(index, CategoricalIndex): result = first.union(case) assert tm.equalContents(result, everything) - if isinstance(indices, MultiIndex): + if isinstance(index, MultiIndex): msg = "other must be a MultiIndex or a list of tuples" with pytest.raises(TypeError, match=msg): first.union([1, 2, 3]) - def test_difference_base(self, sort, indices): - first = indices[2:] - second = indices[:4] - if isinstance(indices, CategoricalIndex) or indices.is_boolean(): + def test_difference_base(self, sort, index): + first = index[2:] + second = index[:4] + if isinstance(index, CategoricalIndex) or index.is_boolean(): answer = [] else: - answer = indices[4:] + answer = index[4:] result = first.difference(second, sort) assert tm.equalContents(result, answer) # GH 10149 cases = [klass(second.values) for klass in [np.array, Series, list]] for case in cases: - if isinstance(indices, (DatetimeIndex, TimedeltaIndex)): + if isinstance(index, (DatetimeIndex, TimedeltaIndex)): assert type(result) == type(answer) tm.assert_numpy_array_equal( result.sort_values().asi8, answer.sort_values().asi8 @@ -490,18 +488,18 @@ def test_difference_base(self, sort, indices): result = first.difference(case, sort) assert tm.equalContents(result, answer) - if isinstance(indices, MultiIndex): + if isinstance(index, MultiIndex): msg = "other must be a MultiIndex or a list of tuples" with pytest.raises(TypeError, match=msg): first.difference([1, 2, 3], sort) - def test_symmetric_difference(self, indices): - if isinstance(indices, CategoricalIndex): + def test_symmetric_difference(self, index): + if isinstance(index, CategoricalIndex): return - first = indices[1:] - second = indices[:-1] - answer = indices[[0, -1]] + first = index[1:] + second = index[:-1] + answer = index[[0, -1]] result = first.symmetric_difference(second) assert tm.equalContents(result, answer) @@ -511,64 +509,64 @@ def test_symmetric_difference(self, indices): result = first.symmetric_difference(case) assert tm.equalContents(result, answer) - if isinstance(indices, MultiIndex): + if isinstance(index, MultiIndex): msg = "other must be a MultiIndex or a list of tuples" with pytest.raises(TypeError, match=msg): first.symmetric_difference([1, 2, 3]) - def test_insert_base(self, indices): - result = indices[1:4] + def test_insert_base(self, index): + result = index[1:4] - if not len(indices): + if not len(index): return # test 0th element - assert indices[0:4].equals(result.insert(0, indices[0])) + assert index[0:4].equals(result.insert(0, index[0])) - def test_delete_base(self, indices): - if not len(indices): + def test_delete_base(self, index): + if not len(index): return - if isinstance(indices, RangeIndex): + if isinstance(index, RangeIndex): # tested in class return - expected = indices[1:] - result = indices.delete(0) + expected = index[1:] + result = index.delete(0) assert result.equals(expected) assert result.name == expected.name - expected = indices[:-1] - result = indices.delete(-1) + expected = index[:-1] + result = index.delete(-1) assert result.equals(expected) assert result.name == expected.name - length = len(indices) + length = len(index) msg = f"index {length} is out of bounds for axis 0 with size {length}" with pytest.raises(IndexError, match=msg): - indices.delete(length) + index.delete(length) - def test_equals(self, indices): - if isinstance(indices, IntervalIndex): + def test_equals(self, index): + if isinstance(index, IntervalIndex): # IntervalIndex tested separately return - assert indices.equals(indices) - assert indices.equals(indices.copy()) - assert indices.equals(indices.astype(object)) + assert index.equals(index) + assert index.equals(index.copy()) + assert index.equals(index.astype(object)) - assert not indices.equals(list(indices)) - assert not indices.equals(np.array(indices)) + assert not index.equals(list(index)) + assert not index.equals(np.array(index)) # Cannot pass in non-int64 dtype to RangeIndex - if not isinstance(indices, RangeIndex): - same_values = Index(indices, dtype=object) - assert indices.equals(same_values) - assert same_values.equals(indices) + if not isinstance(index, RangeIndex): + same_values = Index(index, dtype=object) + assert index.equals(same_values) + assert same_values.equals(index) - if indices.nlevels == 1: + if index.nlevels == 1: # do not test MultiIndex - assert not indices.equals(Series(indices)) + assert not index.equals(Series(index)) def test_equals_op(self): # GH9947, GH10637 @@ -634,50 +632,50 @@ def test_equals_op(self): tm.assert_numpy_array_equal(index_a == item, expected3) tm.assert_series_equal(series_a == item, Series(expected3)) - def test_hasnans_isnans(self, indices): + def test_hasnans_isnans(self, index): # GH 11343, added tests for hasnans / isnans - if isinstance(indices, MultiIndex): + if isinstance(index, MultiIndex): return # cases in indices doesn't include NaN - idx = indices.copy(deep=True) + idx = index.copy(deep=True) expected = np.array([False] * len(idx), dtype=bool) tm.assert_numpy_array_equal(idx._isnan, expected) assert idx.hasnans is False - idx = indices.copy(deep=True) + idx = index.copy(deep=True) values = np.asarray(idx.values) - if len(indices) == 0: + if len(index) == 0: return - elif isinstance(indices, DatetimeIndexOpsMixin): + elif isinstance(index, DatetimeIndexOpsMixin): values[1] = iNaT - elif isinstance(indices, (Int64Index, UInt64Index)): + elif isinstance(index, (Int64Index, UInt64Index)): return else: values[1] = np.nan - if isinstance(indices, PeriodIndex): - idx = type(indices)(values, freq=indices.freq) + if isinstance(index, PeriodIndex): + idx = type(index)(values, freq=index.freq) else: - idx = type(indices)(values) + idx = type(index)(values) expected = np.array([False] * len(idx), dtype=bool) expected[1] = True tm.assert_numpy_array_equal(idx._isnan, expected) assert idx.hasnans is True - def test_fillna(self, indices): + def test_fillna(self, index): # GH 11343 - if len(indices) == 0: + if len(index) == 0: pass - elif isinstance(indices, MultiIndex): - idx = indices.copy(deep=True) + elif isinstance(index, MultiIndex): + idx = index.copy(deep=True) msg = "isna is not defined for MultiIndex" with pytest.raises(NotImplementedError, match=msg): idx.fillna(idx[0]) else: - idx = indices.copy(deep=True) + idx = index.copy(deep=True) result = idx.fillna(idx[0]) tm.assert_index_equal(result, idx) assert result is not idx @@ -686,47 +684,43 @@ def test_fillna(self, indices): with pytest.raises(TypeError, match=msg): idx.fillna([idx[0]]) - idx = indices.copy(deep=True) + idx = index.copy(deep=True) values = np.asarray(idx.values) - if isinstance(indices, DatetimeIndexOpsMixin): + if isinstance(index, DatetimeIndexOpsMixin): values[1] = iNaT - elif isinstance(indices, (Int64Index, UInt64Index)): + elif isinstance(index, (Int64Index, UInt64Index)): return else: values[1] = np.nan - if isinstance(indices, PeriodIndex): - idx = type(indices)(values, freq=indices.freq) + if isinstance(index, PeriodIndex): + idx = type(index)(values, freq=index.freq) else: - idx = type(indices)(values) + idx = type(index)(values) expected = np.array([False] * len(idx), dtype=bool) expected[1] = True tm.assert_numpy_array_equal(idx._isnan, expected) assert idx.hasnans is True - def test_nulls(self, indices): + def test_nulls(self, index): # this is really a smoke test for the methods # as these are adequately tested for function elsewhere - if len(indices) == 0: - tm.assert_numpy_array_equal(indices.isna(), np.array([], dtype=bool)) - elif isinstance(indices, MultiIndex): - idx = indices.copy() + if len(index) == 0: + tm.assert_numpy_array_equal(index.isna(), np.array([], dtype=bool)) + elif isinstance(index, MultiIndex): + idx = index.copy() msg = "isna is not defined for MultiIndex" with pytest.raises(NotImplementedError, match=msg): idx.isna() - elif not indices.hasnans: - tm.assert_numpy_array_equal( - indices.isna(), np.zeros(len(indices), dtype=bool) - ) - tm.assert_numpy_array_equal( - indices.notna(), np.ones(len(indices), dtype=bool) - ) + elif not index.hasnans: + tm.assert_numpy_array_equal(index.isna(), np.zeros(len(index), dtype=bool)) + tm.assert_numpy_array_equal(index.notna(), np.ones(len(index), dtype=bool)) else: - result = isna(indices) - tm.assert_numpy_array_equal(indices.isna(), result) - tm.assert_numpy_array_equal(indices.notna(), ~result) + result = isna(index) + tm.assert_numpy_array_equal(index.isna(), result) + tm.assert_numpy_array_equal(index.notna(), ~result) def test_empty(self): # GH 15270 diff --git a/pandas/tests/indexes/datetimes/test_datetimelike.py b/pandas/tests/indexes/datetimes/test_datetimelike.py index e4785e5f80256..7345ae3032463 100644 --- a/pandas/tests/indexes/datetimes/test_datetimelike.py +++ b/pandas/tests/indexes/datetimes/test_datetimelike.py @@ -14,7 +14,7 @@ class TestDatetimeIndex(DatetimeLike): params=[tm.makeDateIndex(10), date_range("20130110", periods=10, freq="-1D")], ids=["index_inc", "index_dec"], ) - def indices(self, request): + def index(self, request): return request.param def create_index(self) -> DatetimeIndex: diff --git a/pandas/tests/indexes/interval/test_base.py b/pandas/tests/indexes/interval/test_base.py index d8c2ba8413cfb..891640234d26e 100644 --- a/pandas/tests/indexes/interval/test_base.py +++ b/pandas/tests/indexes/interval/test_base.py @@ -15,7 +15,7 @@ class TestBase(Base): _holder = IntervalIndex @pytest.fixture - def indices(self): + def index(self): return tm.makeIntervalIndex(10) def create_index(self, closed="right"): diff --git a/pandas/tests/indexes/period/test_period.py b/pandas/tests/indexes/period/test_period.py index 8d767663fc208..15a88ab3819ce 100644 --- a/pandas/tests/indexes/period/test_period.py +++ b/pandas/tests/indexes/period/test_period.py @@ -32,7 +32,7 @@ class TestPeriodIndex(DatetimeLike): ], ids=["index_inc", "index_dec"], ) - def indices(self, request): + def index(self, request): return request.param def create_index(self) -> PeriodIndex: diff --git a/pandas/tests/indexes/ranges/test_range.py b/pandas/tests/indexes/ranges/test_range.py index 2438cd352f86f..5b6f9cb358b7d 100644 --- a/pandas/tests/indexes/ranges/test_range.py +++ b/pandas/tests/indexes/ranges/test_range.py @@ -27,7 +27,7 @@ class TestRangeIndex(Numeric): ], ids=["index_inc", "index_dec"], ) - def indices(self, request): + def index(self, request): return request.param def create_index(self) -> RangeIndex: @@ -324,9 +324,9 @@ def test_explicit_conversions(self): result = a - fidx tm.assert_index_equal(result, expected) - def test_has_duplicates(self, indices): - assert indices.is_unique - assert not indices.has_duplicates + def test_has_duplicates(self, index): + assert index.is_unique + assert not index.has_duplicates def test_extended_gcd(self): index = self.create_index() diff --git a/pandas/tests/indexes/test_any_index.py b/pandas/tests/indexes/test_any_index.py index 8cbea846bc870..5e7065f785309 100644 --- a/pandas/tests/indexes/test_any_index.py +++ b/pandas/tests/indexes/test_any_index.py @@ -8,85 +8,84 @@ import pandas._testing as tm -def test_boolean_context_compat(indices): +def test_boolean_context_compat(index): with pytest.raises(ValueError, match="The truth value of a"): - if indices: + if index: pass -def test_sort(indices): +def test_sort(index): msg = "cannot sort an Index object in-place, use sort_values instead" with pytest.raises(TypeError, match=msg): - indices.sort() + index.sort() -def test_hash_error(indices): - index = indices +def test_hash_error(index): with pytest.raises(TypeError, match=f"unhashable type: '{type(index).__name__}'"): - hash(indices) + hash(index) -def test_mutability(indices): - if not len(indices): +def test_mutability(index): + if not len(index): return msg = "Index does not support mutable operations" with pytest.raises(TypeError, match=msg): - indices[0] = indices[0] + index[0] = index[0] -def test_wrong_number_names(indices): - names = indices.nlevels * ["apple", "banana", "carrot"] +def test_wrong_number_names(index): + names = index.nlevels * ["apple", "banana", "carrot"] with pytest.raises(ValueError, match="^Length"): - indices.names = names + index.names = names class TestConversion: - def test_to_series(self, indices): + def test_to_series(self, index): # assert that we are creating a copy of the index - ser = indices.to_series() - assert ser.values is not indices.values - assert ser.index is not indices - assert ser.name == indices.name + ser = index.to_series() + assert ser.values is not index.values + assert ser.index is not index + assert ser.name == index.name - def test_to_series_with_arguments(self, indices): + def test_to_series_with_arguments(self, index): # GH#18699 # index kwarg - ser = indices.to_series(index=indices) + ser = index.to_series(index=index) - assert ser.values is not indices.values - assert ser.index is indices - assert ser.name == indices.name + assert ser.values is not index.values + assert ser.index is index + assert ser.name == index.name # name kwarg - ser = indices.to_series(name="__test") + ser = index.to_series(name="__test") - assert ser.values is not indices.values - assert ser.index is not indices - assert ser.name != indices.name + assert ser.values is not index.values + assert ser.index is not index + assert ser.name != index.name - def test_tolist_matches_list(self, indices): - assert indices.tolist() == list(indices) + def test_tolist_matches_list(self, index): + assert index.tolist() == list(index) class TestRoundTrips: - def test_pickle_roundtrip(self, indices): - result = tm.round_trip_pickle(indices) - tm.assert_index_equal(result, indices) + def test_pickle_roundtrip(self, index): + result = tm.round_trip_pickle(index) + tm.assert_index_equal(result, index) if result.nlevels > 1: # GH#8367 round-trip with timezone - assert indices.equal_levels(result) + assert index.equal_levels(result) class TestIndexing: - def test_slice_keeps_name(self, indices): - assert indices.name == indices[1:].name + def test_slice_keeps_name(self, index): + assert index.name == index[1:].name class TestRendering: - def test_str(self, indices): + def test_str(self, index): # test the string repr - indices.name = "foo" - assert "'foo'" in str(indices) - assert type(indices).__name__ in str(indices) + index.name = "foo" + assert "'foo'" in str(index) + assert type(index).__name__ in str(index) diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index f31b49ab82f3b..099c7ced5e2ce 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -54,35 +54,35 @@ def test_can_hold_identifiers(self): key = index[0] assert index._can_hold_identifiers_and_holds_name(key) is True - @pytest.mark.parametrize("indices", ["datetime"], indirect=True) - def test_new_axis(self, indices): + @pytest.mark.parametrize("index", ["datetime"], indirect=True) + def test_new_axis(self, index): with tm.assert_produces_warning(DeprecationWarning): # GH#30588 multi-dimensional indexing deprecated - new_index = indices[None, :] + new_index = index[None, :] assert new_index.ndim == 2 assert isinstance(new_index, np.ndarray) - @pytest.mark.parametrize("indices", ["int", "uint", "float"], indirect=True) - def test_copy_and_deepcopy(self, indices): - new_copy2 = indices.copy(dtype=int) + @pytest.mark.parametrize("index", ["int", "uint", "float"], indirect=True) + def test_copy_and_deepcopy(self, index): + new_copy2 = index.copy(dtype=int) assert new_copy2.dtype.kind == "i" - def test_constructor_regular(self, indices): - tm.assert_contains_all(indices, indices) + def test_constructor_regular(self, index): + tm.assert_contains_all(index, index) - @pytest.mark.parametrize("indices", ["string"], indirect=True) - def test_constructor_casting(self, indices): + @pytest.mark.parametrize("index", ["string"], indirect=True) + def test_constructor_casting(self, index): # casting - arr = np.array(indices) + arr = np.array(index) new_index = Index(arr) tm.assert_contains_all(arr, new_index) - tm.assert_index_equal(indices, new_index) + tm.assert_index_equal(index, new_index) - @pytest.mark.parametrize("indices", ["string"], indirect=True) - def test_constructor_copy(self, indices): + @pytest.mark.parametrize("index", ["string"], indirect=True) + def test_constructor_copy(self, index): # copy # index = self.create_index() - arr = np.array(indices) + arr = np.array(index) new_index = Index(arr, copy=True, name="name") assert isinstance(new_index, Index) assert new_index.name == "name" @@ -436,7 +436,7 @@ def test_constructor_overflow_int64(self): Index([np.iinfo(np.uint64).max - 1], dtype="int64") @pytest.mark.parametrize( - "indices", + "index", [ "datetime", "float", @@ -450,11 +450,11 @@ def test_constructor_overflow_int64(self): ], indirect=True, ) - def test_view_with_args(self, indices): - indices.view("i8") + def test_view_with_args(self, index): + index.view("i8") @pytest.mark.parametrize( - "indices", + "index", [ "unicode", "string", @@ -464,21 +464,21 @@ def test_view_with_args(self, indices): ], indirect=True, ) - def test_view_with_args_object_array_raises(self, indices): + def test_view_with_args_object_array_raises(self, index): msg = "Cannot change data-type for object array" with pytest.raises(TypeError, match=msg): - indices.view("i8") + index.view("i8") - @pytest.mark.parametrize("indices", ["int", "range"], indirect=True) - def test_astype(self, indices): - casted = indices.astype("i8") + @pytest.mark.parametrize("index", ["int", "range"], indirect=True) + def test_astype(self, index): + casted = index.astype("i8") # it works! casted.get_loc(5) # pass on name - indices.name = "foobar" - casted = indices.astype("i8") + index.name = "foobar" + casted = index.astype("i8") assert casted.name == "foobar" def test_equals_object(self): @@ -546,17 +546,17 @@ def test_is_(self): ind2 = Index(arr, copy=False) assert not ind1.is_(ind2) - @pytest.mark.parametrize("indices", ["datetime"], indirect=True) - def test_asof(self, indices): - d = indices[0] - assert indices.asof(d) == d - assert isna(indices.asof(d - timedelta(1))) + @pytest.mark.parametrize("index", ["datetime"], indirect=True) + def test_asof(self, index): + d = index[0] + assert index.asof(d) == d + assert isna(index.asof(d - timedelta(1))) - d = indices[-1] - assert indices.asof(d + timedelta(1)) == d + d = index[-1] + assert index.asof(d + timedelta(1)) == d - d = indices[0].to_pydatetime() - assert isinstance(indices.asof(d), Timestamp) + d = index[0].to_pydatetime() + assert isinstance(index.asof(d), Timestamp) def test_asof_datetime_partial(self): index = pd.date_range("2010-01-01", periods=2, freq="m") @@ -578,17 +578,17 @@ def test_nanosecond_index_access(self): expected_ts = np_datetime64_compat("2013-01-01 00:00:00.000000050+0000", "ns") assert first_value == x[Timestamp(expected_ts)] - @pytest.mark.parametrize("indices", ["string"], indirect=True) - def test_booleanindex(self, indices): - bool_index = np.ones(len(indices), dtype=bool) + @pytest.mark.parametrize("index", ["string"], indirect=True) + def test_booleanindex(self, index): + bool_index = np.ones(len(index), dtype=bool) bool_index[5:30:2] = False - sub_index = indices[bool_index] + sub_index = index[bool_index] for i, val in enumerate(sub_index): assert sub_index.get_loc(val) == i - sub_index = indices[list(bool_index)] + sub_index = index[list(bool_index)] for i, val in enumerate(sub_index): assert sub_index.get_loc(val) == i @@ -598,32 +598,32 @@ def test_fancy(self): for i in sl: assert i == sl[sl.get_loc(i)] - @pytest.mark.parametrize("indices", ["string", "int", "float"], indirect=True) + @pytest.mark.parametrize("index", ["string", "int", "float"], indirect=True) @pytest.mark.parametrize("dtype", [np.int_, np.bool_]) - def test_empty_fancy(self, indices, dtype): + def test_empty_fancy(self, index, dtype): empty_arr = np.array([], dtype=dtype) - empty_index = type(indices)([]) + empty_index = type(index)([]) - assert indices[[]].identical(empty_index) - assert indices[empty_arr].identical(empty_index) + assert index[[]].identical(empty_index) + assert index[empty_arr].identical(empty_index) - @pytest.mark.parametrize("indices", ["string", "int", "float"], indirect=True) - def test_empty_fancy_raises(self, indices): + @pytest.mark.parametrize("index", ["string", "int", "float"], indirect=True) + def test_empty_fancy_raises(self, index): # pd.DatetimeIndex is excluded, because it overrides getitem and should # be tested separately. empty_farr = np.array([], dtype=np.float_) - empty_index = type(indices)([]) + empty_index = type(index)([]) - assert indices[[]].identical(empty_index) + assert index[[]].identical(empty_index) # np.ndarray only accepts ndarray of int & bool dtypes, so should Index msg = r"arrays used as indices must be of integer \(or boolean\) type" with pytest.raises(IndexError, match=msg): - indices[empty_farr] + index[empty_farr] - @pytest.mark.parametrize("indices", ["string"], indirect=True) - def test_intersection(self, indices, sort): - first = indices[:20] - second = indices[:10] + @pytest.mark.parametrize("index", ["string"], indirect=True) + def test_intersection(self, index, sort): + first = index[:20] + second = index[:10] intersect = first.intersection(second, sort=sort) if sort is None: tm.assert_index_equal(intersect, second.sort_values()) @@ -652,16 +652,16 @@ def test_intersection_name_preservation(self, index2, keeps_name, sort): assert result.name == expected.name tm.assert_index_equal(result, expected) - @pytest.mark.parametrize("indices", ["string"], indirect=True) + @pytest.mark.parametrize("index", ["string"], indirect=True) @pytest.mark.parametrize( "first_name,second_name,expected_name", [("A", "A", "A"), ("A", "B", None), (None, "B", None)], ) def test_intersection_name_preservation2( - self, indices, first_name, second_name, expected_name, sort + self, index, first_name, second_name, expected_name, sort ): - first = indices[5:20] - second = indices[:10] + first = index[5:20] + second = index[:10] first.name = first_name second.name = second_name intersect = first.intersection(second, sort=sort) @@ -731,11 +731,11 @@ def test_chained_union(self, sort): expected = j1.union(j2, sort=sort).union(j3, sort=sort) tm.assert_index_equal(union, expected) - @pytest.mark.parametrize("indices", ["string"], indirect=True) - def test_union(self, indices, sort): - first = indices[5:20] - second = indices[:10] - everything = indices[:20] + @pytest.mark.parametrize("index", ["string"], indirect=True) + def test_union(self, index, sort): + first = index[5:20] + second = index[:10] + everything = index[:20] union = first.union(second, sort=sort) if sort is None: @@ -769,12 +769,12 @@ def test_union_sort_special_true(self, slice_): tm.assert_index_equal(result, expected) @pytest.mark.parametrize("klass", [np.array, Series, list]) - @pytest.mark.parametrize("indices", ["string"], indirect=True) - def test_union_from_iterables(self, indices, klass, sort): + @pytest.mark.parametrize("index", ["string"], indirect=True) + def test_union_from_iterables(self, index, klass, sort): # GH 10149 - first = indices[5:20] - second = indices[:10] - everything = indices[:20] + first = index[5:20] + second = index[:10] + everything = index[:20] case = klass(second.values) result = first.union(case, sort=sort) @@ -782,9 +782,9 @@ def test_union_from_iterables(self, indices, klass, sort): tm.assert_index_equal(result, everything.sort_values()) assert tm.equalContents(result, everything) - @pytest.mark.parametrize("indices", ["string"], indirect=True) - def test_union_identity(self, indices, sort): - first = indices[5:20] + @pytest.mark.parametrize("index", ["string"], indirect=True) + def test_union_identity(self, index, sort): + first = index[5:20] union = first.union(first, sort=sort) # i.e. identity is not preserved when sort is True @@ -838,9 +838,9 @@ def test_union_dt_as_obj(self, sort): tm.assert_contains_all(index, second_cat) tm.assert_contains_all(date_index, first_cat) - def test_map_identity_mapping(self, indices): + def test_map_identity_mapping(self, index): # GH 12766 - tm.assert_index_equal(indices, indices.map(lambda x: x)) + tm.assert_index_equal(index, index.map(lambda x: x)) def test_map_with_tuples(self): # GH 12766 @@ -901,22 +901,22 @@ def test_map_dictlike_simple(self, mapper): lambda values, index: pd.Series(values, index), ], ) - def test_map_dictlike(self, indices, mapper): + def test_map_dictlike(self, index, mapper): # GH 12756 - if isinstance(indices, CategoricalIndex): + if isinstance(index, CategoricalIndex): # Tested in test_categorical return - elif not indices.is_unique: + elif not index.is_unique: # Cannot map duplicated index return - if indices.empty: + if index.empty: # to match proper result coercion for uints expected = Index([]) else: - expected = Index(np.arange(len(indices), 0, -1)) + expected = Index(np.arange(len(index), 0, -1)) - result = indices.map(mapper(expected, indices)) + result = index.map(mapper(expected, index)) tm.assert_index_equal(result, expected) @pytest.mark.parametrize( @@ -953,12 +953,12 @@ def test_append_empty_preserve_name(self, name, expected): result = left.append(right) assert result.name == expected - @pytest.mark.parametrize("indices", ["string"], indirect=True) + @pytest.mark.parametrize("index", ["string"], indirect=True) @pytest.mark.parametrize("second_name,expected", [(None, None), ("name", "name")]) - def test_difference_name_preservation(self, indices, second_name, expected, sort): - first = indices[5:20] - second = indices[:10] - answer = indices[10:20] + def test_difference_name_preservation(self, index, second_name, expected, sort): + first = index[5:20] + second = index[:10] + answer = index[10:20] first.name = "name" second.name = second_name @@ -971,31 +971,31 @@ def test_difference_name_preservation(self, indices, second_name, expected, sort else: assert result.name == expected - @pytest.mark.parametrize("indices", ["string"], indirect=True) - def test_difference_empty_arg(self, indices, sort): - first = indices[5:20] + @pytest.mark.parametrize("index", ["string"], indirect=True) + def test_difference_empty_arg(self, index, sort): + first = index[5:20] first.name = "name" result = first.difference([], sort) assert tm.equalContents(result, first) assert result.name == first.name - @pytest.mark.parametrize("indices", ["string"], indirect=True) - def test_difference_identity(self, indices, sort): - first = indices[5:20] + @pytest.mark.parametrize("index", ["string"], indirect=True) + def test_difference_identity(self, index, sort): + first = index[5:20] first.name = "name" result = first.difference(first, sort) assert len(result) == 0 assert result.name == first.name - @pytest.mark.parametrize("indices", ["string"], indirect=True) - def test_difference_sort(self, indices, sort): - first = indices[5:20] - second = indices[:10] + @pytest.mark.parametrize("index", ["string"], indirect=True) + def test_difference_sort(self, index, sort): + first = index[5:20] + second = index[:10] result = first.difference(second, sort) - expected = indices[10:20] + expected = index[10:20] if sort is None: expected = expected.sort_values() @@ -1088,25 +1088,25 @@ def test_symmetric_difference_non_index(self, sort): assert tm.equalContents(result, expected) assert result.name == "new_name" - def test_difference_type(self, indices, sort): + def test_difference_type(self, index, sort): # GH 20040 # If taking difference of a set and itself, it # needs to preserve the type of the index - if not indices.is_unique: + if not index.is_unique: return - result = indices.difference(indices, sort=sort) - expected = indices.drop(indices) + result = index.difference(index, sort=sort) + expected = index.drop(index) tm.assert_index_equal(result, expected) - def test_intersection_difference(self, indices, sort): + def test_intersection_difference(self, index, sort): # GH 20040 # Test that the intersection of an index with an # empty index produces the same index as the difference # of an index with itself. Test for all types - if not indices.is_unique: + if not index.is_unique: return - inter = indices.intersection(indices.drop(indices)) - diff = indices.difference(indices, sort=sort) + inter = index.intersection(index.drop(index)) + diff = index.difference(index, sort=sort) tm.assert_index_equal(inter, diff) def test_is_mixed_deprecated(self): @@ -1116,7 +1116,7 @@ def test_is_mixed_deprecated(self): index.is_mixed() @pytest.mark.parametrize( - "indices, expected", + "index, expected", [ ("string", False), ("bool", False), @@ -1125,13 +1125,13 @@ def test_is_mixed_deprecated(self): ("datetime", False), ("float", True), ], - indirect=["indices"], + indirect=["index"], ) - def test_is_numeric(self, indices, expected): - assert indices.is_numeric() is expected + def test_is_numeric(self, index, expected): + assert index.is_numeric() is expected @pytest.mark.parametrize( - "indices, expected", + "index, expected", [ ("string", True), ("bool", True), @@ -1140,13 +1140,13 @@ def test_is_numeric(self, indices, expected): ("datetime", False), ("float", False), ], - indirect=["indices"], + indirect=["index"], ) - def test_is_object(self, indices, expected): - assert indices.is_object() is expected + def test_is_object(self, index, expected): + assert index.is_object() is expected @pytest.mark.parametrize( - "indices, expected", + "index, expected", [ ("string", False), ("bool", False), @@ -1155,13 +1155,13 @@ def test_is_object(self, indices, expected): ("datetime", True), ("float", False), ], - indirect=["indices"], + indirect=["index"], ) - def test_is_all_dates(self, indices, expected): - assert indices.is_all_dates is expected + def test_is_all_dates(self, index, expected): + assert index.is_all_dates is expected - def test_summary(self, indices): - self._check_method_works(Index._summary, indices) + def test_summary(self, index): + self._check_method_works(Index._summary, index) def test_summary_bug(self): # GH3869` @@ -1171,8 +1171,8 @@ def test_summary_bug(self): assert "~:{range}:0" in result assert "{other}%s" in result - def test_format(self, indices): - self._check_method_works(Index.format, indices) + def test_format(self, index): + self._check_method_works(Index.format, index) def test_format_bug(self): # GH 14626 @@ -1538,37 +1538,37 @@ def test_slice_locs_negative_step(self, in_slice, expected): expected = pd.Index(list(expected)) tm.assert_index_equal(result, expected) - @pytest.mark.parametrize("indices", ["string", "int", "float"], indirect=True) - def test_drop_by_str_label(self, indices): - n = len(indices) - drop = indices[list(range(5, 10))] - dropped = indices.drop(drop) + @pytest.mark.parametrize("index", ["string", "int", "float"], indirect=True) + def test_drop_by_str_label(self, index): + n = len(index) + drop = index[list(range(5, 10))] + dropped = index.drop(drop) - expected = indices[list(range(5)) + list(range(10, n))] + expected = index[list(range(5)) + list(range(10, n))] tm.assert_index_equal(dropped, expected) - dropped = indices.drop(indices[0]) - expected = indices[1:] + dropped = index.drop(index[0]) + expected = index[1:] tm.assert_index_equal(dropped, expected) - @pytest.mark.parametrize("indices", ["string", "int", "float"], indirect=True) + @pytest.mark.parametrize("index", ["string", "int", "float"], indirect=True) @pytest.mark.parametrize("keys", [["foo", "bar"], ["1", "bar"]]) - def test_drop_by_str_label_raises_missing_keys(self, indices, keys): + def test_drop_by_str_label_raises_missing_keys(self, index, keys): with pytest.raises(KeyError, match=""): - indices.drop(keys) + index.drop(keys) - @pytest.mark.parametrize("indices", ["string", "int", "float"], indirect=True) - def test_drop_by_str_label_errors_ignore(self, indices): - n = len(indices) - drop = indices[list(range(5, 10))] + @pytest.mark.parametrize("index", ["string", "int", "float"], indirect=True) + def test_drop_by_str_label_errors_ignore(self, index): + n = len(index) + drop = index[list(range(5, 10))] mixed = drop.tolist() + ["foo"] - dropped = indices.drop(mixed, errors="ignore") + dropped = index.drop(mixed, errors="ignore") - expected = indices[list(range(5)) + list(range(10, n))] + expected = index[list(range(5)) + list(range(10, n))] tm.assert_index_equal(dropped, expected) - dropped = indices.drop(["foo", "bar"], errors="ignore") - expected = indices[list(range(n))] + dropped = index.drop(["foo", "bar"], errors="ignore") + expected = index[list(range(n))] tm.assert_index_equal(dropped, expected) def test_drop_by_numeric_label_loc(self): @@ -1688,20 +1688,20 @@ def test_set_value_deprecated(self): assert arr[1] == 80 @pytest.mark.parametrize( - "indices", ["string", "int", "datetime", "timedelta"], indirect=True + "index", ["string", "int", "datetime", "timedelta"], indirect=True ) - def test_get_value(self, indices): + def test_get_value(self, index): # TODO: Remove function? GH 19728 values = np.random.randn(100) - value = indices[67] + value = index[67] with pytest.raises(AttributeError, match="has no attribute '_values'"): # Index.get_value requires a Series, not an ndarray with tm.assert_produces_warning(FutureWarning): - indices.get_value(values, value) + index.get_value(values, value) with tm.assert_produces_warning(FutureWarning): - result = indices.get_value(Series(values, index=values), value) + result = index.get_value(Series(values, index=values), value) tm.assert_almost_equal(result, values[67]) @pytest.mark.parametrize("values", [["foo", "bar", "quux"], {"foo", "bar", "quux"}]) @@ -1779,15 +1779,13 @@ def test_isin_level_kwarg(self, level, index): index.name = "foobar" tm.assert_numpy_array_equal(expected, index.isin(values, level="foobar")) - def test_isin_level_kwarg_bad_level_raises(self, indices): - index = indices + def test_isin_level_kwarg_bad_level_raises(self, index): for level in [10, index.nlevels, -(index.nlevels + 1)]: with pytest.raises(IndexError, match="Too many levels"): index.isin([], level=level) @pytest.mark.parametrize("label", [1.0, "foobar", "xyzzy", np.nan]) - def test_isin_level_kwarg_bad_label_raises(self, label, indices): - index = indices + def test_isin_level_kwarg_bad_label_raises(self, label, index): if isinstance(index, MultiIndex): index = index.rename(["foo", "bar"] + index.names[2:]) msg = f"'Level {label} not found'" @@ -1823,10 +1821,10 @@ def test_boolean_cmp(self, values): tm.assert_numpy_array_equal(result, expected) - @pytest.mark.parametrize("indices", ["string"], indirect=True) + @pytest.mark.parametrize("index", ["string"], indirect=True) @pytest.mark.parametrize("name,level", [(None, 0), ("a", "a")]) - def test_get_level_values(self, indices, name, level): - expected = indices.copy() + def test_get_level_values(self, index, name, level): + expected = index.copy() if name: expected.name = name @@ -1838,13 +1836,13 @@ def test_slice_keep_name(self): assert index.name == index[1:].name @pytest.mark.parametrize( - "indices", + "index", ["unicode", "string", "datetime", "int", "uint", "float"], indirect=True, ) - def test_join_self(self, indices, join_type): - joined = indices.join(indices, how=join_type) - assert indices is joined + def test_join_self(self, index, join_type): + joined = index.join(index, how=join_type) + assert index is joined @pytest.mark.parametrize("method", ["strip", "rstrip", "lstrip"]) def test_str_attribute(self, method): @@ -2215,14 +2213,14 @@ async def test_tab_complete_warning(self, ip): with provisionalcompleter("ignore"): list(ip.Completer.completions("idx.", 4)) - def test_contains_method_removed(self, indices): + def test_contains_method_removed(self, index): # GH#30103 method removed for all types except IntervalIndex - if isinstance(indices, pd.IntervalIndex): - indices.contains(1) + if isinstance(index, pd.IntervalIndex): + index.contains(1) else: - msg = f"'{type(indices).__name__}' object has no attribute 'contains'" + msg = f"'{type(index).__name__}' object has no attribute 'contains'" with pytest.raises(AttributeError, match=msg): - indices.contains(1) + index.contains(1) class TestMixedIntIndex(Base): @@ -2232,7 +2230,7 @@ class TestMixedIntIndex(Base): _holder = Index @pytest.fixture(params=[[0, "a", 1, "b", 2, "c"]], ids=["mixedIndex"]) - def indices(self, request): + def index(self, request): return Index(request.param) def create_index(self) -> Index: @@ -2494,13 +2492,13 @@ def test_ensure_index_mixed_closed_intervals(self): "divmod", ], ) -def test_generated_op_names(opname, indices): - if isinstance(indices, ABCIndex) and opname == "rsub": +def test_generated_op_names(opname, index): + if isinstance(index, ABCIndex) and opname == "rsub": # pd.Index.__rsub__ does not exist; though the method does exist # for subclasses. see GH#19723 return opname = f"__{opname}__" - method = getattr(indices, opname) + method = getattr(index, opname) assert method.__name__ == opname @@ -2566,20 +2564,19 @@ def test_validate_1d_input(): ser.index = np.array([[2, 3]] * 4) -def test_convert_almost_null_slice(indices): +def test_convert_almost_null_slice(index): # slice with None at both ends, but not step - idx = indices key = slice(None, None, "foo") - if isinstance(idx, pd.IntervalIndex): + if isinstance(index, pd.IntervalIndex): msg = "label-based slicing with step!=1 is not supported for IntervalIndex" with pytest.raises(ValueError, match=msg): - idx._convert_slice_indexer(key, "loc") + index._convert_slice_indexer(key, "loc") else: msg = "'>=' not supported between instances of 'str' and 'int'" with pytest.raises(TypeError, match=msg): - idx._convert_slice_indexer(key, "loc") + index._convert_slice_indexer(key, "loc") dtlike_dtypes = [ diff --git a/pandas/tests/indexes/test_common.py b/pandas/tests/indexes/test_common.py index a08001e042f36..02a173eb4958d 100644 --- a/pandas/tests/indexes/test_common.py +++ b/pandas/tests/indexes/test_common.py @@ -18,32 +18,32 @@ class TestCommon: - def test_droplevel(self, indices): + def test_droplevel(self, index): # GH 21115 - if isinstance(indices, MultiIndex): + if isinstance(index, MultiIndex): # Tested separately in test_multi.py return - assert indices.droplevel([]).equals(indices) + assert index.droplevel([]).equals(index) - for level in indices.name, [indices.name]: - if isinstance(indices.name, tuple) and level is indices.name: + for level in index.name, [index.name]: + if isinstance(index.name, tuple) and level is index.name: # GH 21121 : droplevel with tuple name continue with pytest.raises(ValueError): - indices.droplevel(level) + index.droplevel(level) for level in "wrong", ["wrong"]: with pytest.raises( KeyError, match=r"'Requested level \(wrong\) does not match index name \(None\)'", ): - indices.droplevel(level) + index.droplevel(level) - def test_constructor_non_hashable_name(self, indices): + def test_constructor_non_hashable_name(self, index): # GH 20527 - if isinstance(indices, MultiIndex): + if isinstance(index, MultiIndex): pytest.skip("multiindex handled in test_multi.py") message = "Index.name must be a hashable type" @@ -51,25 +51,25 @@ def test_constructor_non_hashable_name(self, indices): # With .rename() with pytest.raises(TypeError, match=message): - indices.rename(name=renamed) + index.rename(name=renamed) # With .set_names() with pytest.raises(TypeError, match=message): - indices.set_names(names=renamed) + index.set_names(names=renamed) - def test_constructor_unwraps_index(self, indices): - if isinstance(indices, pd.MultiIndex): + def test_constructor_unwraps_index(self, index): + if isinstance(index, pd.MultiIndex): raise pytest.skip("MultiIndex has no ._data") - a = indices + a = index b = type(a)(a) tm.assert_equal(a._data, b._data) @pytest.mark.parametrize("itm", [101, "no_int"]) # FutureWarning from non-tuple sequence of nd indexing @pytest.mark.filterwarnings("ignore::FutureWarning") - def test_getitem_error(self, indices, itm): + def test_getitem_error(self, index, itm): with pytest.raises(IndexError): - indices[itm] + index[itm] @pytest.mark.parametrize( "fname, sname, expected_name", @@ -81,123 +81,123 @@ def test_getitem_error(self, indices, itm): (None, None, None), ], ) - def test_corner_union(self, indices, fname, sname, expected_name): + def test_corner_union(self, index, fname, sname, expected_name): # GH 9943 9862 # Test unions with various name combinations # Do not test MultiIndex or repeats - if isinstance(indices, MultiIndex) or not indices.is_unique: + if isinstance(index, MultiIndex) or not index.is_unique: pytest.skip("Not for MultiIndex or repeated indices") # Test copy.union(copy) - first = indices.copy().set_names(fname) - second = indices.copy().set_names(sname) + first = index.copy().set_names(fname) + second = index.copy().set_names(sname) union = first.union(second) - expected = indices.copy().set_names(expected_name) + expected = index.copy().set_names(expected_name) tm.assert_index_equal(union, expected) # Test copy.union(empty) - first = indices.copy().set_names(fname) - second = indices.drop(indices).set_names(sname) + first = index.copy().set_names(fname) + second = index.drop(index).set_names(sname) union = first.union(second) - expected = indices.copy().set_names(expected_name) + expected = index.copy().set_names(expected_name) tm.assert_index_equal(union, expected) # Test empty.union(copy) - first = indices.drop(indices).set_names(fname) - second = indices.copy().set_names(sname) + first = index.drop(index).set_names(fname) + second = index.copy().set_names(sname) union = first.union(second) - expected = indices.copy().set_names(expected_name) + expected = index.copy().set_names(expected_name) tm.assert_index_equal(union, expected) # Test empty.union(empty) - first = indices.drop(indices).set_names(fname) - second = indices.drop(indices).set_names(sname) + first = index.drop(index).set_names(fname) + second = index.drop(index).set_names(sname) union = first.union(second) - expected = indices.drop(indices).set_names(expected_name) + expected = index.drop(index).set_names(expected_name) tm.assert_index_equal(union, expected) - def test_to_flat_index(self, indices): + def test_to_flat_index(self, index): # 22866 - if isinstance(indices, MultiIndex): + if isinstance(index, MultiIndex): pytest.skip("Separate expectation for MultiIndex") - result = indices.to_flat_index() - tm.assert_index_equal(result, indices) + result = index.to_flat_index() + tm.assert_index_equal(result, index) - def test_set_name_methods(self, indices): + def test_set_name_methods(self, index): new_name = "This is the new name for this index" # don't tests a MultiIndex here (as its tested separated) - if isinstance(indices, MultiIndex): + if isinstance(index, MultiIndex): pytest.skip("Skip check for MultiIndex") - original_name = indices.name - new_ind = indices.set_names([new_name]) + original_name = index.name + new_ind = index.set_names([new_name]) assert new_ind.name == new_name - assert indices.name == original_name - res = indices.rename(new_name, inplace=True) + assert index.name == original_name + res = index.rename(new_name, inplace=True) # should return None assert res is None - assert indices.name == new_name - assert indices.names == [new_name] + assert index.name == new_name + assert index.names == [new_name] # FIXME: dont leave commented-out # with pytest.raises(TypeError, match="list-like"): # # should still fail even if it would be the right length # ind.set_names("a") with pytest.raises(ValueError, match="Level must be None"): - indices.set_names("a", level=0) + index.set_names("a", level=0) # rename in place just leaves tuples and other containers alone name = ("A", "B") - indices.rename(name, inplace=True) - assert indices.name == name - assert indices.names == [name] + index.rename(name, inplace=True) + assert index.name == name + assert index.names == [name] - def test_copy_and_deepcopy(self, indices): + def test_copy_and_deepcopy(self, index): from copy import copy, deepcopy - if isinstance(indices, MultiIndex): + if isinstance(index, MultiIndex): pytest.skip("Skip check for MultiIndex") for func in (copy, deepcopy): - idx_copy = func(indices) - assert idx_copy is not indices - assert idx_copy.equals(indices) + idx_copy = func(index) + assert idx_copy is not index + assert idx_copy.equals(index) - new_copy = indices.copy(deep=True, name="banana") + new_copy = index.copy(deep=True, name="banana") assert new_copy.name == "banana" - def test_unique(self, indices): + def test_unique(self, index): # don't test a MultiIndex here (as its tested separated) # don't test a CategoricalIndex because categories change (GH 18291) - if isinstance(indices, (MultiIndex, CategoricalIndex)): + if isinstance(index, (MultiIndex, CategoricalIndex)): pytest.skip("Skip check for MultiIndex/CategoricalIndex") # GH 17896 - expected = indices.drop_duplicates() - for level in 0, indices.name, None: - result = indices.unique(level=level) + expected = index.drop_duplicates() + for level in 0, index.name, None: + result = index.unique(level=level) tm.assert_index_equal(result, expected) msg = "Too many levels: Index has only 1 level, not 4" with pytest.raises(IndexError, match=msg): - indices.unique(level=3) + index.unique(level=3) msg = ( fr"Requested level \(wrong\) does not match index name " - fr"\({re.escape(indices.name.__repr__())}\)" + fr"\({re.escape(index.name.__repr__())}\)" ) with pytest.raises(KeyError, match=msg): - indices.unique(level="wrong") + index.unique(level="wrong") - def test_get_unique_index(self, indices): + def test_get_unique_index(self, index): # MultiIndex tested separately - if not len(indices) or isinstance(indices, MultiIndex): + if not len(index) or isinstance(index, MultiIndex): pytest.skip("Skip check for empty Index and MultiIndex") - idx = indices[[0] * 5] - idx_unique = indices[[0]] + idx = index[[0] * 5] + idx_unique = index[[0]] # We test against `idx_unique`, so first we make sure it's unique # and doesn't contain nans. @@ -212,109 +212,109 @@ def test_get_unique_index(self, indices): tm.assert_index_equal(result, idx_unique) # nans: - if not indices._can_hold_na: + if not index._can_hold_na: pytest.skip("Skip na-check if index cannot hold na") - if is_period_dtype(indices.dtype): - vals = indices[[0] * 5]._data + if is_period_dtype(index.dtype): + vals = index[[0] * 5]._data vals[0] = pd.NaT - elif needs_i8_conversion(indices.dtype): - vals = indices.asi8[[0] * 5] + elif needs_i8_conversion(index.dtype): + vals = index.asi8[[0] * 5] vals[0] = iNaT else: - vals = indices.values[[0] * 5] + vals = index.values[[0] * 5] vals[0] = np.nan vals_unique = vals[:2] - idx_nan = indices._shallow_copy(vals) - idx_unique_nan = indices._shallow_copy(vals_unique) + idx_nan = index._shallow_copy(vals) + idx_unique_nan = index._shallow_copy(vals_unique) assert idx_unique_nan.is_unique is True - assert idx_nan.dtype == indices.dtype - assert idx_unique_nan.dtype == indices.dtype + assert idx_nan.dtype == index.dtype + assert idx_unique_nan.dtype == index.dtype for dropna, expected in zip([False, True], [idx_unique_nan, idx_unique]): for i in [idx_nan, idx_unique_nan]: result = i._get_unique_index(dropna=dropna) tm.assert_index_equal(result, expected) - def test_mutability(self, indices): - if not len(indices): + def test_mutability(self, index): + if not len(index): pytest.skip("Skip check for empty Index") msg = "Index does not support mutable operations" with pytest.raises(TypeError, match=msg): - indices[0] = indices[0] + index[0] = index[0] - def test_view(self, indices): - assert indices.view().name == indices.name + def test_view(self, index): + assert index.view().name == index.name - def test_searchsorted_monotonic(self, indices): + def test_searchsorted_monotonic(self, index): # GH17271 # not implemented for tuple searches in MultiIndex # or Intervals searches in IntervalIndex - if isinstance(indices, (MultiIndex, pd.IntervalIndex)): + if isinstance(index, (MultiIndex, pd.IntervalIndex)): pytest.skip("Skip check for MultiIndex/IntervalIndex") # nothing to test if the index is empty - if indices.empty: + if index.empty: pytest.skip("Skip check for empty Index") - value = indices[0] + value = index[0] # determine the expected results (handle dupes for 'right') - expected_left, expected_right = 0, (indices == value).argmin() + expected_left, expected_right = 0, (index == value).argmin() if expected_right == 0: # all values are the same, expected_right should be length - expected_right = len(indices) + expected_right = len(index) # test _searchsorted_monotonic in all cases # test searchsorted only for increasing - if indices.is_monotonic_increasing: - ssm_left = indices._searchsorted_monotonic(value, side="left") + if index.is_monotonic_increasing: + ssm_left = index._searchsorted_monotonic(value, side="left") assert expected_left == ssm_left - ssm_right = indices._searchsorted_monotonic(value, side="right") + ssm_right = index._searchsorted_monotonic(value, side="right") assert expected_right == ssm_right - ss_left = indices.searchsorted(value, side="left") + ss_left = index.searchsorted(value, side="left") assert expected_left == ss_left - ss_right = indices.searchsorted(value, side="right") + ss_right = index.searchsorted(value, side="right") assert expected_right == ss_right - elif indices.is_monotonic_decreasing: - ssm_left = indices._searchsorted_monotonic(value, side="left") + elif index.is_monotonic_decreasing: + ssm_left = index._searchsorted_monotonic(value, side="left") assert expected_left == ssm_left - ssm_right = indices._searchsorted_monotonic(value, side="right") + ssm_right = index._searchsorted_monotonic(value, side="right") assert expected_right == ssm_right else: # non-monotonic should raise. with pytest.raises(ValueError): - indices._searchsorted_monotonic(value, side="left") + index._searchsorted_monotonic(value, side="left") - def test_pickle(self, indices): - original_name, indices.name = indices.name, "foo" - unpickled = tm.round_trip_pickle(indices) - assert indices.equals(unpickled) - indices.name = original_name + def test_pickle(self, index): + original_name, index.name = index.name, "foo" + unpickled = tm.round_trip_pickle(index) + assert index.equals(unpickled) + index.name = original_name - def test_drop_duplicates(self, indices, keep): - if isinstance(indices, MultiIndex): + def test_drop_duplicates(self, index, keep): + if isinstance(index, MultiIndex): pytest.skip("MultiIndex is tested separately") - if isinstance(indices, RangeIndex): + if isinstance(index, RangeIndex): pytest.skip( "RangeIndex is tested in test_drop_duplicates_no_duplicates " "as it cannot hold duplicates" ) - if len(indices) == 0: + if len(index) == 0: pytest.skip( "empty index is tested in test_drop_duplicates_no_duplicates " "as it cannot hold duplicates" ) # make unique index - holder = type(indices) - unique_values = list(set(indices)) + holder = type(index) + unique_values = list(set(index)) unique_idx = holder(unique_values) # make duplicated index @@ -332,17 +332,17 @@ def test_drop_duplicates(self, indices, keep): expected_dropped = holder(pd.Series(idx).drop_duplicates(keep=keep)) tm.assert_index_equal(idx.drop_duplicates(keep=keep), expected_dropped) - def test_drop_duplicates_no_duplicates(self, indices): - if isinstance(indices, MultiIndex): + def test_drop_duplicates_no_duplicates(self, index): + if isinstance(index, MultiIndex): pytest.skip("MultiIndex is tested separately") # make unique index - if isinstance(indices, RangeIndex): + if isinstance(index, RangeIndex): # RangeIndex cannot have duplicates - unique_idx = indices + unique_idx = index else: - holder = type(indices) - unique_values = list(set(indices)) + holder = type(index) + unique_values = list(set(index)) unique_idx = holder(unique_values) # check on unique index @@ -353,20 +353,20 @@ def test_drop_duplicates_no_duplicates(self, indices): # validate shallow copy assert result_dropped is not unique_idx - def test_drop_duplicates_inplace(self, indices): + def test_drop_duplicates_inplace(self, index): msg = r"drop_duplicates\(\) got an unexpected keyword argument" with pytest.raises(TypeError, match=msg): - indices.drop_duplicates(inplace=True) + index.drop_duplicates(inplace=True) - def test_has_duplicates(self, indices): - holder = type(indices) - if not len(indices) or isinstance(indices, (MultiIndex, RangeIndex)): + def test_has_duplicates(self, index): + holder = type(index) + if not len(index) or isinstance(index, (MultiIndex, RangeIndex)): # MultiIndex tested separately in: # tests/indexes/multi/test_unique_and_duplicates. # RangeIndex is unique by definition. pytest.skip("Skip check for empty Index, MultiIndex, and RangeIndex") - idx = holder([indices[0]] * 5) + idx = holder([index[0]] * 5) assert idx.is_unique is False assert idx.has_duplicates is True @@ -375,23 +375,23 @@ def test_has_duplicates(self, indices): ["int64", "uint64", "float64", "category", "datetime64[ns]", "timedelta64[ns]"], ) @pytest.mark.parametrize("copy", [True, False]) - def test_astype_preserves_name(self, indices, dtype, copy): + def test_astype_preserves_name(self, index, dtype, copy): # https://github.com/pandas-dev/pandas/issues/32013 - if isinstance(indices, MultiIndex): - indices.names = ["idx" + str(i) for i in range(indices.nlevels)] + if isinstance(index, MultiIndex): + index.names = ["idx" + str(i) for i in range(index.nlevels)] else: - indices.name = "idx" + index.name = "idx" try: # Some of these conversions cannot succeed so we use a try / except if copy: - result = indices.copy(dtype=dtype) + result = index.copy(dtype=dtype) else: - result = indices.astype(dtype) + result = index.astype(dtype) except (ValueError, TypeError, NotImplementedError, SystemError): return - if isinstance(indices, MultiIndex): - assert result.names == indices.names + if isinstance(index, MultiIndex): + assert result.names == index.names else: - assert result.name == indices.name + assert result.name == index.name diff --git a/pandas/tests/indexes/test_numeric.py b/pandas/tests/indexes/test_numeric.py index 081090731a9b4..33de0800658f2 100644 --- a/pandas/tests/indexes/test_numeric.py +++ b/pandas/tests/indexes/test_numeric.py @@ -97,7 +97,7 @@ class TestFloat64Index(Numeric): ], ids=["mixed", "float", "mixed_dec", "float_dec"], ) - def indices(self, request): + def index(self, request): return Float64Index(request.param) @pytest.fixture @@ -111,8 +111,8 @@ def float_index(self): def create_index(self) -> Float64Index: return Float64Index(np.arange(5, dtype="float64")) - def test_repr_roundtrip(self, indices): - tm.assert_index_equal(eval(repr(indices)), indices) + def test_repr_roundtrip(self, index): + tm.assert_index_equal(eval(repr(index)), index) def check_is_index(self, i): assert isinstance(i, Index) @@ -428,7 +428,7 @@ class TestInt64Index(NumericInt): @pytest.fixture( params=[range(0, 20, 2), range(19, -1, -1)], ids=["index_inc", "index_dec"] ) - def indices(self, request): + def index(self, request): return Int64Index(request.param) def create_index(self) -> Int64Index: @@ -537,7 +537,7 @@ class TestUInt64Index(NumericInt): ], ids=["index_inc", "index_dec"], ) - def indices(self, request): + def index(self, request): return UInt64Index(request.param) @pytest.fixture diff --git a/pandas/tests/indexes/test_numpy_compat.py b/pandas/tests/indexes/test_numpy_compat.py index 3340945ca1690..043539c173427 100644 --- a/pandas/tests/indexes/test_numpy_compat.py +++ b/pandas/tests/indexes/test_numpy_compat.py @@ -44,78 +44,76 @@ ], ids=lambda x: x.__name__, ) -def test_numpy_ufuncs_basic(indices, func): +def test_numpy_ufuncs_basic(index, func): # test ufuncs of numpy, see: # https://numpy.org/doc/stable/reference/ufuncs.html - idx = indices - if isinstance(idx, DatetimeIndexOpsMixin): + if isinstance(index, DatetimeIndexOpsMixin): # raise TypeError or ValueError (PeriodIndex) with pytest.raises(Exception): with np.errstate(all="ignore"): - func(idx) - elif isinstance(idx, (Float64Index, Int64Index, UInt64Index)): + func(index) + elif isinstance(index, (Float64Index, Int64Index, UInt64Index)): # coerces to float (e.g. np.sin) with np.errstate(all="ignore"): - result = func(idx) - exp = Index(func(idx.values), name=idx.name) + result = func(index) + exp = Index(func(index.values), name=index.name) tm.assert_index_equal(result, exp) assert isinstance(result, Float64Index) else: # raise AttributeError or TypeError - if len(idx) == 0: + if len(index) == 0: pass else: with pytest.raises(Exception): with np.errstate(all="ignore"): - func(idx) + func(index) @pytest.mark.parametrize( "func", [np.isfinite, np.isinf, np.isnan, np.signbit], ids=lambda x: x.__name__ ) -def test_numpy_ufuncs_other(indices, func): +def test_numpy_ufuncs_other(index, func): # test ufuncs of numpy, see: # https://numpy.org/doc/stable/reference/ufuncs.html - idx = indices - if isinstance(idx, (DatetimeIndex, TimedeltaIndex)): - if isinstance(idx, DatetimeIndex) and idx.tz is not None: + if isinstance(index, (DatetimeIndex, TimedeltaIndex)): + if isinstance(index, DatetimeIndex) and index.tz is not None: if func in [np.isfinite, np.isnan, np.isinf]: pytest.xfail(reason="__array_ufunc__ is not defined") if not _np_version_under1p18 and func in [np.isfinite, np.isinf, np.isnan]: # numpy 1.18(dev) changed isinf and isnan to not raise on dt64/tfd64 - result = func(idx) + result = func(index) assert isinstance(result, np.ndarray) elif not _np_version_under1p17 and func in [np.isfinite]: # ok under numpy >= 1.17 # Results in bool array - result = func(idx) + result = func(index) assert isinstance(result, np.ndarray) else: # raise TypeError or ValueError (PeriodIndex) with pytest.raises(Exception): - func(idx) + func(index) - elif isinstance(idx, PeriodIndex): + elif isinstance(index, PeriodIndex): # raise TypeError or ValueError (PeriodIndex) with pytest.raises(Exception): - func(idx) + func(index) - elif isinstance(idx, (Float64Index, Int64Index, UInt64Index)): + elif isinstance(index, (Float64Index, Int64Index, UInt64Index)): # Results in bool array - result = func(idx) + result = func(index) assert isinstance(result, np.ndarray) assert not isinstance(result, Index) else: - if len(idx) == 0: + if len(index) == 0: pass else: with pytest.raises(Exception): - func(idx) + func(index) def test_elementwise_comparison_warning(): diff --git a/pandas/tests/indexes/test_setops.py b/pandas/tests/indexes/test_setops.py index 818d5474eddf5..1a40fe550be61 100644 --- a/pandas/tests/indexes/test_setops.py +++ b/pandas/tests/indexes/test_setops.py @@ -20,18 +20,18 @@ } -def test_union_same_types(indices): +def test_union_same_types(index): # Union with a non-unique, non-monotonic index raises error # Only needed for bool index factory - idx1 = indices.sort_values() - idx2 = indices.sort_values() + idx1 = index.sort_values() + idx2 = index.sort_values() assert idx1.union(idx2).dtype == idx1.dtype -def test_union_different_types(indices, index_fixture2): +def test_union_different_types(index, index_fixture2): # This test only considers combinations of indices # GH 23525 - idx1, idx2 = indices, index_fixture2 + idx1, idx2 = index, index_fixture2 type_pair = tuple(sorted([type(idx1), type(idx2)], key=lambda x: str(x))) if type_pair in COMPATIBLE_INCONSISTENT_PAIRS: pytest.xfail("This test only considers non compatible indexes.") diff --git a/pandas/tests/indexes/timedeltas/test_timedelta.py b/pandas/tests/indexes/timedeltas/test_timedelta.py index a0521658ffc1e..4a1749ff734c1 100644 --- a/pandas/tests/indexes/timedeltas/test_timedelta.py +++ b/pandas/tests/indexes/timedeltas/test_timedelta.py @@ -25,7 +25,7 @@ class TestTimedeltaIndex(DatetimeLike): _holder = TimedeltaIndex @pytest.fixture - def indices(self): + def index(self): return tm.makeTimedeltaIndex(10) def create_index(self) -> TimedeltaIndex: diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index 5c0230e75021c..62e9c6ee81369 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -67,9 +67,9 @@ def test_setitem_ndarray_1d(self): (lambda x: x.iloc, "iloc"), ], ) - def test_getitem_ndarray_3d(self, indices, obj, idxr, idxr_id): + def test_getitem_ndarray_3d(self, index, obj, idxr, idxr_id): # GH 25567 - obj = obj(indices) + obj = obj(index) idxr = idxr(obj) nd3 = np.random.randint(5, size=(2, 2, 2)) @@ -105,17 +105,13 @@ def test_getitem_ndarray_3d(self, indices, obj, idxr, idxr_id): (lambda x: x.iloc, "iloc"), ], ) - def test_setitem_ndarray_3d(self, indices, obj, idxr, idxr_id): + def test_setitem_ndarray_3d(self, index, obj, idxr, idxr_id): # GH 25567 - obj = obj(indices) + obj = obj(index) idxr = idxr(obj) nd3 = np.random.randint(5, size=(2, 2, 2)) - if ( - (len(indices) == 0) - and (idxr_id == "iloc") - and isinstance(obj, pd.DataFrame) - ): + if (len(index) == 0) and (idxr_id == "iloc") and isinstance(obj, pd.DataFrame): # gh-32896 pytest.skip("This is currently failing. There's an xfailed test below.") @@ -123,7 +119,7 @@ def test_setitem_ndarray_3d(self, indices, obj, idxr, idxr_id): err = ValueError msg = f"Cannot set values with ndim > {obj.ndim}" elif ( - isinstance(indices, pd.IntervalIndex) + isinstance(index, pd.IntervalIndex) and idxr_id == "setitem" and obj.ndim == 1 ): diff --git a/pandas/tests/series/methods/test_to_period.py b/pandas/tests/series/methods/test_to_period.py index 5bc4a36498c58..b40fc81931e20 100644 --- a/pandas/tests/series/methods/test_to_period.py +++ b/pandas/tests/series/methods/test_to_period.py @@ -47,9 +47,8 @@ def test_to_period(self): expected.columns = exp_idx tm.assert_frame_equal(df.to_period(axis=1), expected) - def test_to_period_raises(self, indices): + def test_to_period_raises(self, index): # https://github.com/pandas-dev/pandas/issues/33327 - index = indices ser = Series(index=index, dtype=object) if not isinstance(index, DatetimeIndex): msg = f"unsupported Type {type(index).__name__}" diff --git a/pandas/tests/series/methods/test_to_timestamp.py b/pandas/tests/series/methods/test_to_timestamp.py index 296a1c15619f2..13a2042a2f639 100644 --- a/pandas/tests/series/methods/test_to_timestamp.py +++ b/pandas/tests/series/methods/test_to_timestamp.py @@ -55,9 +55,8 @@ def _get_with_delta(delta, freq="A-DEC"): tm.assert_index_equal(result.index, exp_index) assert result.name == "foo" - def test_to_timestamp_raises(self, indices): + def test_to_timestamp_raises(self, index): # https://github.com/pandas-dev/pandas/issues/33327 - index = indices ser = Series(index=index, dtype=object) if not isinstance(index, PeriodIndex): msg = f"unsupported Type {type(index).__name__}" diff --git a/pandas/tests/series/test_apply.py b/pandas/tests/series/test_apply.py index d51dceae53a1c..308398642895c 100644 --- a/pandas/tests/series/test_apply.py +++ b/pandas/tests/series/test_apply.py @@ -528,11 +528,11 @@ def test_map(self, datetime_series): exp = Series([np.nan, "B", "C", "D"]) tm.assert_series_equal(a.map(c), exp) - def test_map_empty(self, indices): - if isinstance(indices, MultiIndex): + def test_map_empty(self, index): + if isinstance(index, MultiIndex): pytest.skip("Initializing a Series from a MultiIndex is not supported") - s = Series(indices) + s = Series(index) result = s.map({}) expected = pd.Series(np.nan, index=s.index)