diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 6c7499a575fca..1cb6dc231384c 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -453,6 +453,9 @@ def __new__( if dtype is not None: return result.astype(dtype, copy=False) return result + elif dtype is not None: + # GH#45206 + data = data.astype(dtype, copy=False) disallow_kwargs(kwargs) data = extract_array(data, extract_numpy=True) diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index ef528f59a1e4e..61cfd5593abc0 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -422,9 +422,11 @@ def test_equals(self, index): # fails for IntervalIndex return + is_ea_idx = type(index) is Index and not isinstance(index.dtype, np.dtype) + assert index.equals(index) assert index.equals(index.copy()) - if not (type(index) is Index and not isinstance(index.dtype, np.dtype)): + if not is_ea_idx: # doesn't hold for e.g. IntegerDtype assert index.equals(index.astype(object)) @@ -432,7 +434,7 @@ def test_equals(self, index): assert not index.equals(np.array(index)) # Cannot pass in non-int64 dtype to RangeIndex - if not isinstance(index, RangeIndex): + if not isinstance(index, RangeIndex) and not is_ea_idx: same_values = Index(index, dtype=object) assert index.equals(same_values) assert same_values.equals(index) diff --git a/pandas/tests/indexes/test_index_new.py b/pandas/tests/indexes/test_index_new.py index f44bbac1226e1..5f57e03ea9444 100644 --- a/pandas/tests/indexes/test_index_new.py +++ b/pandas/tests/indexes/test_index_new.py @@ -25,6 +25,7 @@ Series, TimedeltaIndex, Timestamp, + array, date_range, period_range, timedelta_range, @@ -159,6 +160,13 @@ def test_constructor_datetime_and_datetime64(self, swap_objs): class TestDtypeEnforced: # check we don't silently ignore the dtype keyword + def test_constructor_object_dtype_with_ea_data(self, any_numeric_ea_dtype): + # GH#45206 + arr = array([0], dtype=any_numeric_ea_dtype) + + idx = Index(arr, dtype=object) + assert idx.dtype == object + @pytest.mark.parametrize("dtype", [object, "float64", "uint64", "category"]) def test_constructor_range_values_mismatched_dtype(self, dtype): rng = Index(range(5))