Skip to content

Commit 3e997af

Browse files
Terji PetersenTerji Petersen
Terji Petersen
authored and
Terji Petersen
committed
BUG: NumericIndex.astype(complex) should return Index[complex]
1 parent f6204a5 commit 3e997af

File tree

3 files changed

+14
-3
lines changed

3 files changed

+14
-3
lines changed

pandas/conftest.py

Lines changed: 2 additions & 2 deletions
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

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@
9191
ensure_platform_int,
9292
is_bool_dtype,
9393
is_categorical_dtype,
94+
is_complex_dtype,
9495
is_dtype_equal,
9596
is_ea_or_datetimelike_dtype,
9697
is_extension_array_dtype,
@@ -1061,7 +1062,11 @@ def astype(self, dtype, copy: bool = True):
10611062
# this block is needed so e.g. NumericIndex[int8].astype("int32") returns
10621063
# NumericIndex[int32] and not Int64Index with dtype int64.
10631064
# When Int64Index etc. are removed from the code base, removed this also.
1064-
if isinstance(dtype, np.dtype) and is_numeric_dtype(dtype):
1065+
if (
1066+
isinstance(dtype, np.dtype)
1067+
and is_numeric_dtype(dtype)
1068+
and not is_complex_dtype(dtype)
1069+
):
10651070
return self._constructor(
10661071
new_values, name=self.name, dtype=dtype, copy=False
10671072
)

pandas/tests/indexes/common.py

Lines changed: 6 additions & 0 deletions
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)