Skip to content

Commit ce648b6

Browse files
Backport PR #45214: REGR: Index(pd.array(foo), dtype=object) (#45265)
Co-authored-by: jbrockmendel <[email protected]>
1 parent dbaea53 commit ce648b6

File tree

3 files changed

+15
-2
lines changed

3 files changed

+15
-2
lines changed

pandas/core/indexes/base.py

+3
Original file line numberDiff line numberDiff line change
@@ -453,6 +453,9 @@ def __new__(
453453
if dtype is not None:
454454
return result.astype(dtype, copy=False)
455455
return result
456+
elif dtype is not None:
457+
# GH#45206
458+
data = data.astype(dtype, copy=False)
456459

457460
disallow_kwargs(kwargs)
458461
data = extract_array(data, extract_numpy=True)

pandas/tests/indexes/common.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -422,17 +422,19 @@ def test_equals(self, index):
422422
# fails for IntervalIndex
423423
return
424424

425+
is_ea_idx = type(index) is Index and not isinstance(index.dtype, np.dtype)
426+
425427
assert index.equals(index)
426428
assert index.equals(index.copy())
427-
if not (type(index) is Index and not isinstance(index.dtype, np.dtype)):
429+
if not is_ea_idx:
428430
# doesn't hold for e.g. IntegerDtype
429431
assert index.equals(index.astype(object))
430432

431433
assert not index.equals(list(index))
432434
assert not index.equals(np.array(index))
433435

434436
# Cannot pass in non-int64 dtype to RangeIndex
435-
if not isinstance(index, RangeIndex):
437+
if not isinstance(index, RangeIndex) and not is_ea_idx:
436438
same_values = Index(index, dtype=object)
437439
assert index.equals(same_values)
438440
assert same_values.equals(index)

pandas/tests/indexes/test_index_new.py

+8
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
Series,
2626
TimedeltaIndex,
2727
Timestamp,
28+
array,
2829
date_range,
2930
period_range,
3031
timedelta_range,
@@ -159,6 +160,13 @@ def test_constructor_datetime_and_datetime64(self, swap_objs):
159160
class TestDtypeEnforced:
160161
# check we don't silently ignore the dtype keyword
161162

163+
def test_constructor_object_dtype_with_ea_data(self, any_numeric_ea_dtype):
164+
# GH#45206
165+
arr = array([0], dtype=any_numeric_ea_dtype)
166+
167+
idx = Index(arr, dtype=object)
168+
assert idx.dtype == object
169+
162170
@pytest.mark.parametrize("dtype", [object, "float64", "uint64", "category"])
163171
def test_constructor_range_values_mismatched_dtype(self, dtype):
164172
rng = Index(range(5))

0 commit comments

Comments
 (0)