diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 370ea28832758..bc792713b5879 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -140,6 +140,7 @@ Other enhancements - :meth:`pandas.read_stata` and :class:`StataReader` support reading data from compressed files. - Add support for parsing ``ISO 8601``-like timestamps with negative signs to :meth:`pandas.Timedelta` (:issue:`37172`) - Add support for unary operators in :class:`FloatingArray` (:issue:`38749`) +- :class:`RangeIndex` can now be constructed by passing a ``range`` object directly e.g. ``pd.RangeIndex(range(3))`` (:issue:`12067`) - :meth:`round` being enabled for the nullable integer and floating dtypes (:issue:`38844`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 09c143468bc31..23cb4d5df3f7b 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -366,16 +366,11 @@ def __new__( data_dtype = getattr(data, "dtype", None) # range - if isinstance(data, RangeIndex): + if isinstance(data, (range, RangeIndex)): result = RangeIndex(start=data, copy=copy, name=name) if dtype is not None: return result.astype(dtype, copy=False) return result - elif isinstance(data, range): - result = RangeIndex.from_range(data, name=name) - if dtype is not None: - return result.astype(dtype, copy=False) - return result elif is_ea_or_datetimelike_dtype(dtype): # non-EA dtype indexes have special casting logic, so we punt here diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index bf5a9825f04d0..0c2d4a1872c98 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -116,7 +116,8 @@ def __new__( # RangeIndex if isinstance(start, RangeIndex): - start = start._range + return start.copy(name=name) + elif isinstance(start, range): return cls._simple_new(start, name=name) # validate the arguments diff --git a/pandas/tests/indexes/ranges/test_constructors.py b/pandas/tests/indexes/ranges/test_constructors.py index 599df3732a33b..9539b0ff7cdba 100644 --- a/pandas/tests/indexes/ranges/test_constructors.py +++ b/pandas/tests/indexes/ranges/test_constructors.py @@ -91,11 +91,12 @@ def test_constructor_same(self): ): RangeIndex(index, dtype="float64") - def test_constructor_range(self): + def test_constructor_range_object(self): + result = RangeIndex(range(1, 5, 2)) + expected = RangeIndex(1, 5, 2) + tm.assert_index_equal(result, expected, exact=True) - msg = "Value needs to be a scalar value, was type range" - with pytest.raises(TypeError, match=msg): - result = RangeIndex(range(1, 5, 2)) + def test_constructor_range(self): result = RangeIndex.from_range(range(1, 5, 2)) expected = RangeIndex(1, 5, 2)