Skip to content

BUG: NumericIndex.astype(complex) should return Index[complex] #49540

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
Nov 8, 2022
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
4 changes: 2 additions & 2 deletions pandas/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down
7 changes: 6 additions & 1 deletion pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
)
Expand Down
6 changes: 6 additions & 0 deletions pandas/tests/indexes/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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