Skip to content

Backport PR #45214 on branch 1.4.x (REGR: Index(pd.array(foo), dtype=object)) #45265

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
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
3 changes: 3 additions & 0 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,9 @@ def __new__(
if dtype is not None:
return result.astype(dtype, copy=False)
return result
elif dtype is not None:
# GH#45206
data = data.astype(dtype, copy=False)

disallow_kwargs(kwargs)
data = extract_array(data, extract_numpy=True)
Expand Down
6 changes: 4 additions & 2 deletions pandas/tests/indexes/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -422,17 +422,19 @@ def test_equals(self, index):
# fails for IntervalIndex
return

is_ea_idx = type(index) is Index and not isinstance(index.dtype, np.dtype)

assert index.equals(index)
assert index.equals(index.copy())
if not (type(index) is Index and not isinstance(index.dtype, np.dtype)):
if not is_ea_idx:
# doesn't hold for e.g. IntegerDtype
assert index.equals(index.astype(object))

assert not index.equals(list(index))
assert not index.equals(np.array(index))

# Cannot pass in non-int64 dtype to RangeIndex
if not isinstance(index, RangeIndex):
if not isinstance(index, RangeIndex) and not is_ea_idx:
same_values = Index(index, dtype=object)
assert index.equals(same_values)
assert same_values.equals(index)
Expand Down
8 changes: 8 additions & 0 deletions pandas/tests/indexes/test_index_new.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
Series,
TimedeltaIndex,
Timestamp,
array,
date_range,
period_range,
timedelta_range,
Expand Down Expand Up @@ -159,6 +160,13 @@ def test_constructor_datetime_and_datetime64(self, swap_objs):
class TestDtypeEnforced:
# check we don't silently ignore the dtype keyword

def test_constructor_object_dtype_with_ea_data(self, any_numeric_ea_dtype):
# GH#45206
arr = array([0], dtype=any_numeric_ea_dtype)

idx = Index(arr, dtype=object)
assert idx.dtype == object

@pytest.mark.parametrize("dtype", [object, "float64", "uint64", "category"])
def test_constructor_range_values_mismatched_dtype(self, dtype):
rng = Index(range(5))
Expand Down