Skip to content

REF: share RangeIndex methods #43952

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1027,7 +1027,8 @@ def take(
taken = algos.take(
self._values, indices, allow_fill=allow_fill, fill_value=self._na_value
)
return type(self)._simple_new(taken, name=self.name)
# _constructor so RangeIndex->Int64Index
return self._constructor._simple_new(taken, name=self.name)

@final
def _maybe_disallow_fill(self, allow_fill: bool, fill_value, indices) -> bool:
Expand Down Expand Up @@ -1097,7 +1098,8 @@ def repeat(self, repeats, axis=None):
nv.validate_repeat((), {"axis": axis})
res_values = self._values.repeat(repeats)

return type(self)._simple_new(res_values, name=self.name)
# _constructor so RangeIndex->Int64Index
return self._constructor._simple_new(res_values, name=self.name)

# --------------------------------------------------------------------
# Copying Methods
Expand Down Expand Up @@ -6298,7 +6300,8 @@ def delete(self: _IndexT, loc) -> _IndexT:
Index(['b'], dtype='object')
"""
res_values = np.delete(self._data, loc)
return type(self)._simple_new(res_values, name=self.name)
# _constructor so RangeIndex->Int64Index
return self._constructor._simple_new(res_values, name=self.name)

def insert(self, loc: int, item) -> Index:
"""
Expand Down
47 changes: 10 additions & 37 deletions pandas/core/indexes/range.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
cache_readonly,
doc,
)
from pandas.util._exceptions import rewrite_exception

from pandas.core.dtypes.common import (
ensure_platform_int,
Expand Down Expand Up @@ -189,17 +188,6 @@ def _data(self) -> np.ndarray:
"""
return np.arange(self.start, self.stop, self.step, dtype=np.int64)

@cache_readonly
def _cached_int64index(self) -> Int64Index:
return Int64Index._simple_new(self._data, name=self.name)

@property
def _int64index(self) -> Int64Index:
# wrap _cached_int64index so we can be sure its name matches self.name
res = self._cached_int64index
res._name = self._name
return res

def _get_data_as_items(self):
"""return a list of tuples of start, stop, step"""
rng = self._range
Expand Down Expand Up @@ -425,24 +413,6 @@ def _get_indexer(

# --------------------------------------------------------------------

def repeat(self, repeats, axis=None) -> Int64Index:
return self._int64index.repeat(repeats, axis=axis)

def delete(self, loc) -> Int64Index: # type: ignore[override]
return self._int64index.delete(loc)

def take(
self, indices, axis: int = 0, allow_fill: bool = True, fill_value=None, **kwargs
) -> Int64Index:
with rewrite_exception("Int64Index", type(self).__name__):
return self._int64index.take(
indices,
axis=axis,
allow_fill=allow_fill,
fill_value=fill_value,
**kwargs,
)

def tolist(self) -> list[int]:
return list(self._range)

Expand Down Expand Up @@ -683,7 +653,8 @@ def _union(self, other: Index, sort):
and (end_s - step_o <= end_o)
):
return type(self)(start_r, end_r + step_o, step_o)
return self._int64index._union(other, sort=sort)

return super()._union(other, sort=sort)

def _difference(self, other, sort=None):
# optimized set operation if we have another RangeIndex
Expand Down Expand Up @@ -857,7 +828,8 @@ def __floordiv__(self, other):
start = self.start // other
new_range = range(start, start + 1, 1)
return self._simple_new(new_range, name=self.name)
return self._int64index // other

return super().__floordiv__(other)

# --------------------------------------------------------------------
# Reductions
Expand Down Expand Up @@ -891,21 +863,22 @@ def _arith_method(self, other, op):
elif isinstance(other, (timedelta, np.timedelta64)):
# GH#19333 is_integer evaluated True on timedelta64,
# so we need to catch these explicitly
return op(self._int64index, other)
return super()._arith_method(other, op)
elif is_timedelta64_dtype(other):
# Must be an np.ndarray; GH#22390
return op(self._int64index, other)
return super()._arith_method(other, op)

if op in [
operator.pow,
ops.rpow,
operator.mod,
ops.rmod,
operator.floordiv,
ops.rfloordiv,
divmod,
ops.rdivmod,
]:
return op(self._int64index, other)
return super()._arith_method(other, op)

step: Callable | None = None
if op in [operator.mul, ops.rmul, operator.truediv, ops.rtruediv]:
Expand Down Expand Up @@ -946,5 +919,5 @@ def _arith_method(self, other, op):

except (ValueError, TypeError, ZeroDivisionError):
# Defer to Int64Index implementation
return op(self._int64index, other)
# TODO: Do attrs get handled reliably?
# test_arithmetic_explicit_conversions
return super()._arith_method(other, op)
10 changes: 7 additions & 3 deletions pandas/tests/arithmetic/test_numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -1311,18 +1311,22 @@ def test_numeric_compat2(self):
# __pow__
idx = RangeIndex(0, 1000, 2)
result = idx ** 2
expected = idx._int64index ** 2
expected = Int64Index(idx._values) ** 2
tm.assert_index_equal(Index(result.values), expected, exact=True)

# __floordiv__
cases_exact = [
(RangeIndex(0, 1000, 2), 2, RangeIndex(0, 500, 1)),
(RangeIndex(-99, -201, -3), -3, RangeIndex(33, 67, 1)),
(RangeIndex(0, 1000, 1), 2, RangeIndex(0, 1000, 1)._int64index // 2),
(
RangeIndex(0, 1000, 1),
2,
Int64Index(RangeIndex(0, 1000, 1)._values) // 2,
),
(
RangeIndex(0, 100, 1),
2.0,
RangeIndex(0, 100, 1)._int64index // 2.0,
Int64Index(RangeIndex(0, 100, 1)._values) // 2.0,
),
(RangeIndex(0), 50, RangeIndex(0)),
(RangeIndex(2, 4, 2), 3, RangeIndex(0, 1, 1)),
Expand Down
6 changes: 3 additions & 3 deletions pandas/tests/indexes/ranges/test_range.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,12 +299,12 @@ def test_identical(self, simple_index):
def test_nbytes(self):

# memory savings vs int index
i = RangeIndex(0, 1000)
assert i.nbytes < i._int64index.nbytes / 10
idx = RangeIndex(0, 1000)
assert idx.nbytes < Int64Index(idx.values).nbytes / 10

# constant memory usage
i2 = RangeIndex(0, 10)
assert i.nbytes == i2.nbytes
assert idx.nbytes == i2.nbytes

@pytest.mark.parametrize(
"start,stop,step",
Expand Down
6 changes: 3 additions & 3 deletions pandas/tests/indexes/ranges/test_setops.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ def test_union_sorted(self, unions):
tm.assert_index_equal(res1, expected_notsorted, exact=True)

res2 = idx2.union(idx1, sort=None)
res3 = idx1._int64index.union(idx2, sort=None)
res3 = Int64Index(idx1._values, name=idx1.name).union(idx2, sort=None)
tm.assert_index_equal(res2, expected_sorted, exact=True)
tm.assert_index_equal(res3, expected_sorted)

Expand Down Expand Up @@ -322,11 +322,11 @@ def test_difference_mismatched_step(self):
obj = RangeIndex.from_range(range(1, 10), name="foo")

result = obj.difference(obj[::2])
expected = obj[1::2]._int64index
expected = Int64Index(obj[1::2]._values, name=obj.name)
tm.assert_index_equal(result, expected, exact=True)

result = obj.difference(obj[1::2])
expected = obj[::2]._int64index
expected = Int64Index(obj[::2]._values, name=obj.name)
tm.assert_index_equal(result, expected, exact=True)

def test_symmetric_difference(self):
Expand Down
10 changes: 4 additions & 6 deletions pandas/tests/reductions/test_reductions.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,15 +221,15 @@ class TestIndexReductions:
def test_max_min_range(self, start, stop, step):
# GH#17607
idx = RangeIndex(start, stop, step)
expected = idx._int64index.max()
expected = idx._values.max()
result = idx.max()
assert result == expected

# skipna should be irrelevant since RangeIndex should never have NAs
result2 = idx.max(skipna=False)
assert result2 == expected

expected = idx._int64index.min()
expected = idx._values.min()
result = idx.min()
assert result == expected

Expand Down Expand Up @@ -431,13 +431,11 @@ def test_numpy_minmax_range(self):
# GH#26125
idx = RangeIndex(0, 10, 3)

expected = idx._int64index.max()
result = np.max(idx)
assert result == expected
assert result == 9

expected = idx._int64index.min()
result = np.min(idx)
assert result == expected
assert result == 0

errmsg = "the 'out' parameter is not supported"
with pytest.raises(ValueError, match=errmsg):
Expand Down