From abaaf8818867c3d24ebe4a6a0dffb46849a74fd6 Mon Sep 17 00:00:00 2001 From: Patrick Hoefler <61934744+phofl@users.noreply.github.com> Date: Wed, 15 Mar 2023 11:25:14 +0100 Subject: [PATCH] Backport PR #51974: BUG: astype_view check raising on minimum versions build --- pandas/core/dtypes/astype.py | 5 ++++- pandas/tests/copy_view/test_astype.py | 10 ++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/pandas/core/dtypes/astype.py b/pandas/core/dtypes/astype.py index 7ae5993c857e2..87a36aed418f9 100644 --- a/pandas/core/dtypes/astype.py +++ b/pandas/core/dtypes/astype.py @@ -263,6 +263,9 @@ def astype_is_view(dtype: DtypeObj, new_dtype: DtypeObj) -> bool: ------- True if new data is a view or not guaranteed to be a copy, False otherwise """ + if isinstance(dtype, np.dtype) and not isinstance(new_dtype, np.dtype): + new_dtype, dtype = dtype, new_dtype + if dtype == new_dtype: return True @@ -290,7 +293,7 @@ def astype_is_view(dtype: DtypeObj, new_dtype: DtypeObj) -> bool: numpy_dtype = dtype if new_numpy_dtype is None and isinstance(new_dtype, np.dtype): - numpy_dtype = new_dtype + new_numpy_dtype = new_dtype if numpy_dtype is not None and new_numpy_dtype is not None: # if both have NumPy dtype or one of them is a numpy dtype diff --git a/pandas/tests/copy_view/test_astype.py b/pandas/tests/copy_view/test_astype.py index 73343976e92fb..15351967c8d83 100644 --- a/pandas/tests/copy_view/test_astype.py +++ b/pandas/tests/copy_view/test_astype.py @@ -2,7 +2,9 @@ import pytest from pandas.compat import pa_version_under7p0 +import pandas.util._test_decorators as td +import pandas as pd from pandas import ( DataFrame, Series, @@ -84,6 +86,14 @@ def test_astype_different_target_dtype(using_copy_on_write, dtype): tm.assert_frame_equal(df2, df_orig.astype(dtype)) +@td.skip_array_manager_invalid_test +def test_astype_numpy_to_ea(): + ser = Series([1, 2, 3]) + with pd.option_context("mode.copy_on_write", True): + result = ser.astype("Int64") + assert np.shares_memory(get_array(ser), get_array(result)) + + @pytest.mark.parametrize( "dtype, new_dtype", [("object", "string"), ("string", "object")] )