Skip to content

Commit 71cedd9

Browse files
topper-123Terji Petersen
authored andcommitted
BUG: NumericIndex.astype(complex) should return Index[complex] (pandas-dev#49540)
Co-authored-by: Terji Petersen <[email protected]>
1 parent 3df9a81 commit 71cedd9

File tree

3 files changed

+14
-3
lines changed

3 files changed

+14
-3
lines changed

pandas/conftest.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -597,8 +597,8 @@ def _create_mi_with_dt64tz_level():
597597
"uint": tm.makeUIntIndex(100),
598598
"range": tm.makeRangeIndex(100),
599599
"float": tm.makeFloatIndex(100),
600-
"complex64": tm.makeFloatIndex(100).astype("complex64"),
601-
"complex128": tm.makeFloatIndex(100).astype("complex128"),
600+
"complex64": tm.makeNumericIndex(100, dtype="float64").astype("complex64"),
601+
"complex128": tm.makeNumericIndex(100, dtype="float64").astype("complex128"),
602602
"num_int64": tm.makeNumericIndex(100, dtype="int64"),
603603
"num_int32": tm.makeNumericIndex(100, dtype="int32"),
604604
"num_int16": tm.makeNumericIndex(100, dtype="int16"),

pandas/core/indexes/base.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@
8989
ensure_platform_int,
9090
is_bool_dtype,
9191
is_categorical_dtype,
92+
is_complex_dtype,
9293
is_dtype_equal,
9394
is_ea_or_datetimelike_dtype,
9495
is_extension_array_dtype,
@@ -1044,7 +1045,11 @@ def astype(self, dtype, copy: bool = True):
10441045
# this block is needed so e.g. NumericIndex[int8].astype("int32") returns
10451046
# NumericIndex[int32] and not Int64Index with dtype int64.
10461047
# When Int64Index etc. are removed from the code base, removed this also.
1047-
if isinstance(dtype, np.dtype) and is_numeric_dtype(dtype):
1048+
if (
1049+
isinstance(dtype, np.dtype)
1050+
and is_numeric_dtype(dtype)
1051+
and not is_complex_dtype(dtype)
1052+
):
10481053
return self._constructor(
10491054
new_values, name=self.name, dtype=dtype, copy=False
10501055
)

pandas/tests/indexes/common.py

+6
Original file line numberDiff line numberDiff line change
@@ -896,3 +896,9 @@ def test_invalid_dtype(self, invalid_dtype):
896896
msg = rf"Incorrect `dtype` passed: expected \w+(?: \w+)?, received {dtype}"
897897
with pytest.raises(ValueError, match=msg):
898898
self._index_cls([1, 2, 3], dtype=dtype)
899+
900+
@pytest.mark.parametrize("complex_dtype", [np.complex64, np.complex128])
901+
def test_astype_to_complex(self, complex_dtype, simple_index):
902+
result = simple_index.astype(complex_dtype)
903+
904+
assert type(result) is Index and result.dtype == complex_dtype

0 commit comments

Comments
 (0)