diff --git a/pandas/core/dtypes/astype.py b/pandas/core/dtypes/astype.py index cd91f06d7ff04..09e338d205bbc 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 310e811c0c6d8..16c060d004bc7 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")] )