diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 4914d213accac..822c6372ea2a4 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -526,6 +526,7 @@ Sparse ExtensionArray ^^^^^^^^^^^^^^ +- Bug in :func:`array` failing to preserve :class:`PandasArray` (:issue:`43887`) - NumPy ufuncs ``np.abs``, ``np.positive``, ``np.negative`` now correctly preserve dtype when called on ExtensionArrays that implement ``__abs__, __pos__, __neg__``, respectively. In particular this is fixed for :class:`TimedeltaArray` (:issue:`43899`) - diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 420a409529a10..d1b926bd25055 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -718,8 +718,9 @@ def _validate_listlike(self, value, allow_object: bool = False): msg = self._validation_error_message(value, True) raise TypeError(msg) - # Do type inference if necessary up front + # Do type inference if necessary up front (after unpacking PandasArray) # e.g. we passed PeriodIndex.values and got an ndarray of Periods + value = extract_array(value, extract_numpy=True) value = pd_array(value) value = extract_array(value, extract_numpy=True) diff --git a/pandas/core/construction.py b/pandas/core/construction.py index 8d3fd0c520a6d..c6f131a9daba6 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -297,6 +297,7 @@ def array( from pandas.core.arrays import ( BooleanArray, DatetimeArray, + ExtensionArray, FloatingArray, IntegerArray, IntervalArray, @@ -310,7 +311,7 @@ def array( msg = f"Cannot pass scalar '{data}' to 'pandas.array'." raise ValueError(msg) - if dtype is None and isinstance(data, (ABCSeries, ABCIndex, ABCExtensionArray)): + if dtype is None and isinstance(data, (ABCSeries, ABCIndex, ExtensionArray)): # Note: we exclude np.ndarray here, will do type inference on it dtype = data.dtype diff --git a/pandas/tests/arrays/test_array.py b/pandas/tests/arrays/test_array.py index cc8a47f545d92..e953e7dc6dcba 100644 --- a/pandas/tests/arrays/test_array.py +++ b/pandas/tests/arrays/test_array.py @@ -50,6 +50,13 @@ ), # String alias passes through to NumPy ([1, 2], "float32", PandasArray(np.array([1, 2], dtype="float32"))), + ([1, 2], "int64", PandasArray(np.array([1, 2], dtype=np.int64))), + # idempotency with e.g. pd.array(pd.array([1, 2], dtype="int64")) + ( + PandasArray(np.array([1, 2], dtype=np.int32)), + None, + PandasArray(np.array([1, 2], dtype=np.int32)), + ), # Period alias ( [pd.Period("2000", "D"), pd.Period("2001", "D")],