From 7790aac139dc40e894e75c5e4a71ed1e55ff3dd9 Mon Sep 17 00:00:00 2001 From: Brock Date: Mon, 4 Oct 2021 21:07:05 -0700 Subject: [PATCH 1/2] BUG: pd.array preserve PandasArray --- pandas/core/arrays/datetimelike.py | 3 ++- pandas/core/construction.py | 3 ++- pandas/tests/arrays/test_array.py | 7 +++++++ 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 2c9796e826825..1c0ac739ea6c6 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")], From 974bb2d3a72b89016b72c5077ec41eaff648d7e5 Mon Sep 17 00:00:00 2001 From: Brock Date: Mon, 4 Oct 2021 21:08:28 -0700 Subject: [PATCH 2/2] whatsnew --- doc/source/whatsnew/v1.4.0.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index dcd31abaa8857..693828e7c4cfb 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -518,7 +518,7 @@ Sparse ExtensionArray ^^^^^^^^^^^^^^ -- +- Bug in :func:`array` failing to preserve :class:`PandasArray` (:issue:`43887`) - Styler