Skip to content

API: Index(object_dtype_bool_ndarray) retain object dtype #49594

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 2 commits into from
Nov 9, 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
3 changes: 2 additions & 1 deletion doc/source/whatsnew/v2.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,8 @@ Other API changes
- Passing a sequence containing ``datetime`` objects and ``date`` objects to :class:`Series` constructor will return with ``object`` dtype instead of ``datetime64[ns]`` dtype, consistent with :class:`Index` behavior (:issue:`49341`)
- Passing strings that cannot be parsed as datetimes to :class:`Series` or :class:`DataFrame` with ``dtype="datetime64[ns]"`` will raise instead of silently ignoring the keyword and returning ``object`` dtype (:issue:`24435`)
- Passing a sequence containing a type that cannot be converted to :class:`Timedelta` to :func:`to_timedelta` or to the :class:`Series` or :class:`DataFrame` constructor with ``dtype="timedelta64[ns]"`` or to :class:`TimedeltaIndex` now raises ``TypeError`` instead of ``ValueError`` (:issue:`49525`)
- Changed behavior of :class:`Index` construct with sequence containing at least one ``NaT`` and everything else either ``None`` or ``NaN`` to infer ``datetime64[ns]`` dtype instead of ``object``, matching :class:`Series` behavior (:issue:`49340`)
- Changed behavior of :class:`Index` constructor with sequence containing at least one ``NaT`` and everything else either ``None`` or ``NaN`` to infer ``datetime64[ns]`` dtype instead of ``object``, matching :class:`Series` behavior (:issue:`49340`)
- Changed behavior of :class:`Index` constructor with an object-dtype ``numpy.ndarray`` containing all-``bool`` values or all-complex values, this will now retain object dtype, consistent with the :class:`Series` behavior (:issue:`49594`)
-

.. ---------------------------------------------------------------------------
Expand Down
22 changes: 5 additions & 17 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@
find_common_type,
infer_dtype_from,
maybe_cast_pointwise_result,
maybe_infer_to_datetimelike,
np_can_hold_element,
)
from pandas.core.dtypes.common import (
Expand Down Expand Up @@ -503,9 +504,8 @@ def __new__(
arr = com.asarray_tuplesafe(data, dtype=_dtype_obj)

if dtype is None:
arr = _maybe_cast_data_without_dtype(
arr, cast_numeric_deprecated=True
)
arr = maybe_infer_to_datetimelike(arr)
arr = ensure_wrapped_if_datetimelike(arr)
dtype = arr.dtype

klass = cls._dtype_to_subclass(arr.dtype)
Expand Down Expand Up @@ -534,9 +534,7 @@ def __new__(
subarr = com.asarray_tuplesafe(data, dtype=_dtype_obj)
if dtype is None:
# with e.g. a list [1, 2, 3] casting to numeric is _not_ deprecated
subarr = _maybe_cast_data_without_dtype(
subarr, cast_numeric_deprecated=False
)
subarr = _maybe_cast_data_without_dtype(subarr)
dtype = subarr.dtype
return Index(subarr, dtype=dtype, copy=copy, name=name)

Expand Down Expand Up @@ -7062,18 +7060,14 @@ def maybe_extract_name(name, obj, cls) -> Hashable:
return name


def _maybe_cast_data_without_dtype(
subarr: np.ndarray, cast_numeric_deprecated: bool = True
) -> ArrayLike:
def _maybe_cast_data_without_dtype(subarr: npt.NDArray[np.object_]) -> ArrayLike:
"""
If we have an arraylike input but no passed dtype, try to infer
a supported dtype.

Parameters
----------
subarr : np.ndarray[object]
cast_numeric_deprecated : bool, default True
Whether to issue a FutureWarning when inferring numeric dtypes.

Returns
-------
Expand All @@ -7088,12 +7082,6 @@ def _maybe_cast_data_without_dtype(
convert_interval=True,
dtype_if_all_nat=np.dtype("datetime64[ns]"),
)
if result.dtype.kind in ["i", "u", "f"]:
if not cast_numeric_deprecated:
# i.e. we started with a list, not an ndarray[object]
return result
return subarr

result = ensure_wrapped_if_datetimelike(result)
return result

Expand Down
18 changes: 18 additions & 0 deletions pandas/tests/indexes/test_index_new.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,24 @@


class TestIndexConstructorInference:
def test_object_all_bools(self):
# GH#49594 match Series behavior on ndarray[object] of all bools
arr = np.array([True, False], dtype=object)
res = Index(arr)
assert res.dtype == object

# since the point is matching Series behavior, let's double check
assert Series(arr).dtype == object

def test_object_all_complex(self):
# GH#49594 match Series behavior on ndarray[object] of all complex
arr = np.array([complex(1), complex(2)], dtype=object)
res = Index(arr)
assert res.dtype == object

# since the point is matching Series behavior, let's double check
assert Series(arr).dtype == object

@pytest.mark.parametrize("val", [NaT, None, np.nan, float("nan")])
def test_infer_nat(self, val):
# GH#49340 all NaT/None/nan and at least 1 NaT -> datetime64[ns],
Expand Down