diff --git a/pandas/conftest.py b/pandas/conftest.py index 4639799d2ee03..308f63a4ebe5c 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -597,8 +597,8 @@ def _create_mi_with_dt64tz_level(): "uint": tm.makeUIntIndex(100), "range": tm.makeRangeIndex(100), "float": tm.makeFloatIndex(100), - "complex64": tm.makeFloatIndex(100).astype("complex64"), - "complex128": tm.makeFloatIndex(100).astype("complex128"), + "complex64": tm.makeNumericIndex(100, dtype="float64").astype("complex64"), + "complex128": tm.makeNumericIndex(100, dtype="float64").astype("complex128"), "num_int64": tm.makeNumericIndex(100, dtype="int64"), "num_int32": tm.makeNumericIndex(100, dtype="int32"), "num_int16": tm.makeNumericIndex(100, dtype="int16"), diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 10c2349f05dfd..8e0fa5960135f 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -89,6 +89,7 @@ ensure_platform_int, is_bool_dtype, is_categorical_dtype, + is_complex_dtype, is_dtype_equal, is_ea_or_datetimelike_dtype, is_extension_array_dtype, @@ -1044,7 +1045,11 @@ def astype(self, dtype, copy: bool = True): # this block is needed so e.g. NumericIndex[int8].astype("int32") returns # NumericIndex[int32] and not Int64Index with dtype int64. # When Int64Index etc. are removed from the code base, removed this also. - if isinstance(dtype, np.dtype) and is_numeric_dtype(dtype): + if ( + isinstance(dtype, np.dtype) + and is_numeric_dtype(dtype) + and not is_complex_dtype(dtype) + ): return self._constructor( new_values, name=self.name, dtype=dtype, copy=False ) diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index f2141b0b74ac6..97b640b252329 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -896,3 +896,9 @@ def test_invalid_dtype(self, invalid_dtype): msg = rf"Incorrect `dtype` passed: expected \w+(?: \w+)?, received {dtype}" with pytest.raises(ValueError, match=msg): self._index_cls([1, 2, 3], dtype=dtype) + + @pytest.mark.parametrize("complex_dtype", [np.complex64, np.complex128]) + def test_astype_to_complex(self, complex_dtype, simple_index): + result = simple_index.astype(complex_dtype) + + assert type(result) is Index and result.dtype == complex_dtype