From f66cd05e94946b5f4aa6926fa6439b000b900e01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Sok=C3=B3=C5=82?= Date: Wed, 31 Jan 2024 14:48:47 +0100 Subject: [PATCH 1/3] MAINT: Adjust the codebase to the new np.array copy keyword meaning --- pandas/core/frame.py | 2 +- pandas/tests/arrays/test_datetimelike.py | 23 +++++++++++-------- .../tests/extension/array_with_attr/array.py | 4 ++++ 3 files changed, 19 insertions(+), 10 deletions(-) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index f530466c0fc30..5cc01e655e0d9 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1919,7 +1919,7 @@ def to_numpy( dtype = np.dtype(dtype) result = self._mgr.as_array(dtype=dtype, copy=copy, na_value=na_value) if result.dtype is not dtype: - result = np.array(result, dtype=dtype, copy=False) + result = np.asarray(result, dtype=dtype) return result diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py index ed915a8878c9a..b6ae1a9df0e65 100644 --- a/pandas/tests/arrays/test_datetimelike.py +++ b/pandas/tests/arrays/test_datetimelike.py @@ -12,6 +12,7 @@ Timestamp, ) from pandas._libs.tslibs import to_offset +from pandas.compat.numpy import np_version_gt2 from pandas.core.dtypes.dtypes import PeriodDtype @@ -640,13 +641,14 @@ def test_round(self, arr1d): def test_array_interface(self, datetime_index): arr = datetime_index._data + copy_false = None if np_version_gt2 else False # default asarray gives the same underlying data (for tz naive) result = np.asarray(arr) expected = arr._ndarray assert result is expected tm.assert_numpy_array_equal(result, expected) - result = np.array(arr, copy=False) + result = np.array(arr, copy=copy_false) assert result is expected tm.assert_numpy_array_equal(result, expected) @@ -655,7 +657,7 @@ def test_array_interface(self, datetime_index): expected = arr._ndarray assert result is expected tm.assert_numpy_array_equal(result, expected) - result = np.array(arr, dtype="datetime64[ns]", copy=False) + result = np.array(arr, dtype="datetime64[ns]", copy=copy_false) assert result is expected tm.assert_numpy_array_equal(result, expected) result = np.array(arr, dtype="datetime64[ns]") @@ -698,6 +700,7 @@ def test_array_tz(self, arr1d): # GH#23524 arr = arr1d dti = self.index_cls(arr1d) + copy_false = None if np_version_gt2 else False expected = dti.asi8.view("M8[ns]") result = np.array(arr, dtype="M8[ns]") @@ -706,17 +709,18 @@ def test_array_tz(self, arr1d): result = np.array(arr, dtype="datetime64[ns]") tm.assert_numpy_array_equal(result, expected) - # check that we are not making copies when setting copy=False - result = np.array(arr, dtype="M8[ns]", copy=False) + # check that we are not making copies when setting copy=copy_false + result = np.array(arr, dtype="M8[ns]", copy=copy_false) assert result.base is expected.base assert result.base is not None - result = np.array(arr, dtype="datetime64[ns]", copy=False) + result = np.array(arr, dtype="datetime64[ns]", copy=copy_false) assert result.base is expected.base assert result.base is not None def test_array_i8_dtype(self, arr1d): arr = arr1d dti = self.index_cls(arr1d) + copy_false = None if np_version_gt2 else False expected = dti.asi8 result = np.array(arr, dtype="i8") @@ -725,8 +729,8 @@ def test_array_i8_dtype(self, arr1d): result = np.array(arr, dtype=np.int64) tm.assert_numpy_array_equal(result, expected) - # check that we are still making copies when setting copy=False - result = np.array(arr, dtype="i8", copy=False) + # check that we are still making copies when setting copy=copy_false + result = np.array(arr, dtype="i8", copy=copy_false) assert result.base is not expected.base assert result.base is None @@ -952,13 +956,14 @@ def test_int_properties(self, timedelta_index, propname): def test_array_interface(self, timedelta_index): arr = timedelta_index._data + copy_false = None if np_version_gt2 else False # default asarray gives the same underlying data result = np.asarray(arr) expected = arr._ndarray assert result is expected tm.assert_numpy_array_equal(result, expected) - result = np.array(arr, copy=False) + result = np.array(arr, copy=copy_false) assert result is expected tm.assert_numpy_array_equal(result, expected) @@ -967,7 +972,7 @@ def test_array_interface(self, timedelta_index): expected = arr._ndarray assert result is expected tm.assert_numpy_array_equal(result, expected) - result = np.array(arr, dtype="timedelta64[ns]", copy=False) + result = np.array(arr, dtype="timedelta64[ns]", copy=copy_false) assert result is expected tm.assert_numpy_array_equal(result, expected) result = np.array(arr, dtype="timedelta64[ns]") diff --git a/pandas/tests/extension/array_with_attr/array.py b/pandas/tests/extension/array_with_attr/array.py index d0249d9af8098..1acf70beff6b6 100644 --- a/pandas/tests/extension/array_with_attr/array.py +++ b/pandas/tests/extension/array_with_attr/array.py @@ -9,6 +9,8 @@ import numpy as np +from pandas.compat.numpy import np_version_gt2 + from pandas.core.dtypes.base import ExtensionDtype import pandas as pd @@ -49,6 +51,8 @@ def __init__(self, values, attr=None) -> None: @classmethod def _from_sequence(cls, scalars, *, dtype=None, copy=False): + if np_version_gt2 and not copy: + copy = None data = np.array(scalars, dtype="float64", copy=copy) return cls(data) From fc949a219e36734c4ee8d6cc922a70c94362dd28 Mon Sep 17 00:00:00 2001 From: Matthew Roeschke <10647082+mroeschke@users.noreply.github.com> Date: Mon, 4 Mar 2024 13:46:10 -0800 Subject: [PATCH 2/3] Add copy is docstring --- pandas/core/arrays/categorical.py | 3 +++ pandas/core/series.py | 3 +++ 2 files changed, 6 insertions(+) diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index d360b141fac4f..f37513b2bc8fd 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -1670,6 +1670,9 @@ def __array__( dtype : np.dtype or None Specifies the the dtype for the array. + copy : bool or None, optional + Unused. + Returns ------- numpy.array diff --git a/pandas/core/series.py b/pandas/core/series.py index 5151d42106b09..d7aed54da9014 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -804,6 +804,9 @@ def __array__( The dtype to use for the resulting NumPy array. By default, the dtype is inferred from the data. + copy : bool or None, optional + Unused. + Returns ------- numpy.ndarray From 2f6fd603e42012101c23b149b39954deb58a821f Mon Sep 17 00:00:00 2001 From: Matthew Roeschke <10647082+mroeschke@users.noreply.github.com> Date: Tue, 5 Mar 2024 12:05:55 -0800 Subject: [PATCH 3/3] Use asarray where possible --- pandas/core/array_algos/quantile.py | 10 +++------ pandas/core/arrays/base.py | 12 +++++----- pandas/core/arrays/datetimes.py | 4 +--- pandas/core/arrays/numeric.py | 21 +++++++++--------- pandas/core/arrays/period.py | 9 ++++---- pandas/core/arrays/timedeltas.py | 14 +++++------- pandas/core/construction.py | 22 +++++++++---------- pandas/core/dtypes/cast.py | 11 +++++----- pandas/core/dtypes/missing.py | 4 +--- pandas/core/indexes/multi.py | 11 +++------- pandas/core/internals/managers.py | 6 ++--- pandas/io/pytables.py | 4 +--- .../tests/extension/array_with_attr/array.py | 9 ++++---- pandas/tests/extension/json/array.py | 10 ++++----- pandas/tests/extension/list/array.py | 9 ++++---- pandas/tests/extension/test_common.py | 9 ++++---- 16 files changed, 67 insertions(+), 98 deletions(-) diff --git a/pandas/core/array_algos/quantile.py b/pandas/core/array_algos/quantile.py index 6be27a14cb9fa..5c933294fb944 100644 --- a/pandas/core/array_algos/quantile.py +++ b/pandas/core/array_algos/quantile.py @@ -4,8 +4,6 @@ import numpy as np -from pandas.compat.numpy import np_version_gt2 - from pandas.core.dtypes.missing import ( isna, na_value_for_dtype, @@ -104,8 +102,7 @@ def quantile_with_mask( interpolation=interpolation, ) - copy_false = None if np_version_gt2 else False - result = np.array(result, copy=copy_false) + result = np.asarray(result) result = result.T return result @@ -202,12 +199,11 @@ def _nanpercentile( _nanpercentile_1d(val, m, qs, na_value, interpolation=interpolation) for (val, m) in zip(list(values), list(mask)) ] - copy_false = None if np_version_gt2 else False if values.dtype.kind == "f": # preserve itemsize - result = np.array(result, dtype=values.dtype, copy=copy_false).T + result = np.asarray(result, dtype=values.dtype).T else: - result = np.array(result, copy=copy_false).T + result = np.asarray(result).T if ( result.dtype != values.dtype and not mask.all() diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index a8ede6ba1aa72..a0da3518f8e5e 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -27,10 +27,7 @@ lib, ) from pandas.compat import set_function_name -from pandas.compat.numpy import ( - function as nv, - np_version_gt2, -) +from pandas.compat.numpy import function as nv from pandas.errors import AbstractMethodError from pandas.util._decorators import ( Appender, @@ -713,8 +710,6 @@ def astype(self, dtype: AstypeArg, copy: bool = True) -> ArrayLike: return self else: return self.copy() - if np_version_gt2 and not copy: - copy = None if isinstance(dtype, ExtensionDtype): cls = dtype.construct_array_type() @@ -730,7 +725,10 @@ def astype(self, dtype: AstypeArg, copy: bool = True) -> ArrayLike: return TimedeltaArray._from_sequence(self, dtype=dtype, copy=copy) - return np.array(self, dtype=dtype, copy=copy) + if not copy: + return np.asarray(self, dtype=dtype) + else: + return np.array(self, dtype=dtype, copy=copy) def isna(self) -> np.ndarray | ExtensionArraySupportsAnyAll: """ diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 50eccb8e0e498..11516692801a1 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -43,7 +43,6 @@ tzconversion, ) from pandas._libs.tslibs.dtypes import abbrev_to_npy_unit -from pandas.compat.numpy import np_version_gt2 from pandas.errors import PerformanceWarning from pandas.util._exceptions import find_stack_level from pandas.util._validators import validate_inclusive @@ -2422,8 +2421,7 @@ def objects_to_datetime64( assert errors in ["raise", "coerce"] # if str-dtype, convert - copy_false = None if np_version_gt2 else False - data = np.array(data, dtype=np.object_, copy=copy_false) + data = np.asarray(data, dtype=np.object_) result, tz_parsed = tslib.array_to_datetime( data, diff --git a/pandas/core/arrays/numeric.py b/pandas/core/arrays/numeric.py index df485bfde0514..fe7b32ec9652e 100644 --- a/pandas/core/arrays/numeric.py +++ b/pandas/core/arrays/numeric.py @@ -13,7 +13,6 @@ lib, missing as libmissing, ) -from pandas.compat.numpy import np_version_gt2 from pandas.errors import AbstractMethodError from pandas.util._decorators import cache_readonly @@ -138,12 +137,6 @@ def _coerce_to_data_and_mask( values, dtype, copy: bool, dtype_cls: type[NumericDtype], default_dtype: np.dtype ): checker = dtype_cls._checker - if np_version_gt2: - copy_false = None - if not copy: - copy = None - else: - copy_false = False mask = None inferred_type = None @@ -167,7 +160,10 @@ def _coerce_to_data_and_mask( return values, mask, dtype, inferred_type original = values - values = np.array(values, copy=copy) + if not copy: + values = np.asarray(values) + else: + values = np.array(values, copy=copy) inferred_type = None if values.dtype == object or is_string_dtype(values.dtype): inferred_type = lib.infer_dtype(values, skipna=True) @@ -176,7 +172,10 @@ def _coerce_to_data_and_mask( raise TypeError(f"{values.dtype} cannot be converted to {name}") elif values.dtype.kind == "b" and checker(dtype): - values = np.array(values, dtype=default_dtype, copy=copy) + if not copy: + values = np.asarray(values, dtype=default_dtype) + else: + values = np.array(values, dtype=default_dtype, copy=copy) elif values.dtype.kind not in "iuf": name = dtype_cls.__name__.strip("_") @@ -215,9 +214,9 @@ def _coerce_to_data_and_mask( inferred_type not in ["floating", "mixed-integer-float"] and not mask.any() ): - values = np.array(original, dtype=dtype, copy=copy_false) + values = np.asarray(original, dtype=dtype) else: - values = np.array(original, dtype="object", copy=copy_false) + values = np.asarray(original, dtype="object") # we copy as need to coerce here if mask.any(): diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 36769ca948728..73cc8e4345d3c 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -50,7 +50,6 @@ get_period_field_arr, period_asfreq_arr, ) -from pandas.compat.numpy import np_version_gt2 from pandas.util._decorators import ( cache_readonly, doc, @@ -244,9 +243,6 @@ def __init__( if not isinstance(dtype, PeriodDtype): raise ValueError(f"Invalid dtype {dtype} for PeriodArray") - if np_version_gt2 and not copy: - copy = None - if isinstance(values, ABCSeries): values = values._values if not isinstance(values, type(self)): @@ -260,7 +256,10 @@ def __init__( raise raise_on_incompatible(values, dtype.freq) values, dtype = values._ndarray, values.dtype - values = np.array(values, dtype="int64", copy=copy) + if not copy: + values = np.asarray(values, dtype="int64") + else: + values = np.array(values, dtype="int64", copy=copy) if dtype is None: raise ValueError("dtype is not specified and cannot be inferred") dtype = cast(PeriodDtype, dtype) diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index 8e0b43e401314..c41e078095feb 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -36,10 +36,7 @@ parse_timedelta_unit, truediv_object_array, ) -from pandas.compat.numpy import ( - function as nv, - np_version_gt2, -) +from pandas.compat.numpy import function as nv from pandas.util._validators import validate_endpoints from pandas.core.dtypes.common import ( @@ -1075,10 +1072,10 @@ def sequence_to_td64ns( # This includes datetime64-dtype, see GH#23539, GH#29794 raise TypeError(f"dtype {data.dtype} cannot be converted to timedelta64[ns]") - copy_false = None if np_version_gt2 else False if not copy: - copy = copy_false - data = np.array(data, copy=copy) + data = np.asarray(data) + else: + data = np.array(data, copy=copy) assert data.dtype.kind == "m" assert data.dtype != "m8" # i.e. not unit-less @@ -1158,8 +1155,7 @@ def _objects_to_td64ns( higher level. """ # coerce Index to np.ndarray, converting string-dtype if necessary - copy_false = None if np_version_gt2 else False - values = np.array(data, dtype=np.object_, copy=copy_false) + values = np.asarray(data, dtype=np.object_) result = array_to_timedelta64(values, unit=unit, errors=errors) return result.view("timedelta64[ns]") diff --git a/pandas/core/construction.py b/pandas/core/construction.py index 0243049b22e1d..af2aea11dcf6d 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -34,7 +34,6 @@ DtypeObj, T, ) -from pandas.compat.numpy import np_version_gt2 from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.base import ExtensionDtype @@ -627,9 +626,10 @@ def sanitize_array( elif hasattr(data, "__array__"): # e.g. dask array GH#38645 - if np_version_gt2 and not copy: - copy = None - data = np.array(data, copy=copy) + if not copy: + data = np.asarray(data) + else: + data = np.array(data, copy=copy) return sanitize_array( data, index=index, @@ -738,9 +738,6 @@ def _sanitize_str_dtypes( """ Ensure we have a dtype that is supported by pandas. """ - copy_false = None if np_version_gt2 else False - if not copy: - copy = copy_false # This is to prevent mixed-type Series getting all casted to # NumPy string type, e.g. NaN --> '-1#IND'. @@ -750,8 +747,11 @@ def _sanitize_str_dtypes( # GH#19853: If data is a scalar, result has already the result if not lib.is_scalar(data): if not np.all(isna(data)): - data = np.array(data, dtype=dtype, copy=copy_false) - result = np.array(data, dtype=object, copy=copy) + data = np.asarray(data, dtype=dtype) + if not copy: + result = np.asarray(data, dtype=object) + else: + result = np.array(data, dtype=object, copy=copy) return result @@ -787,8 +787,6 @@ def _try_cast( np.ndarray or ExtensionArray """ is_ndarray = isinstance(arr, np.ndarray) - if np_version_gt2 and not copy: - copy = None if dtype == object: if not is_ndarray: @@ -818,6 +816,8 @@ def _try_cast( # this will raise if we have e.g. floats subarr = maybe_cast_to_integer_array(arr, dtype) + elif not copy: + subarr = np.asarray(arr, dtype=dtype) else: subarr = np.array(arr, dtype=dtype, copy=copy) diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 0d604d6fc0967..01b7d500179bf 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1491,9 +1491,6 @@ def construct_2d_arraylike_from_scalar( value: Scalar, length: int, width: int, dtype: np.dtype, copy: bool ) -> np.ndarray: shape = (length, width) - copy_false = None if np_version_gt2 else False - if not copy: - copy = copy_false if dtype.kind in "mM": value = _maybe_box_and_unbox_datetimelike(value, dtype) @@ -1506,7 +1503,10 @@ def construct_2d_arraylike_from_scalar( # Attempt to coerce to a numpy array try: - arr = np.array(value, dtype=dtype, copy=copy) + if not copy: + arr = np.asarray(value, dtype=dtype) + else: + arr = np.array(value, dtype=dtype, copy=copy) except (ValueError, TypeError) as err: raise TypeError( f"DataFrame constructor called with incompatible data and dtype: {err}" @@ -1655,8 +1655,7 @@ def maybe_cast_to_integer_array(arr: list | np.ndarray, dtype: np.dtype) -> np.n "out-of-bound Python int", DeprecationWarning, ) - copy_false = None if np_version_gt2 else False - casted = np.array(arr, dtype=dtype, copy=copy_false) + casted = np.asarray(arr, dtype=dtype) else: with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=RuntimeWarning) diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py index 3c02f2ab002fb..97efb5db9baa9 100644 --- a/pandas/core/dtypes/missing.py +++ b/pandas/core/dtypes/missing.py @@ -18,7 +18,6 @@ NaT, iNaT, ) -from pandas.compat.numpy import np_version_gt2 from pandas.core.dtypes.common import ( DT64NS_DTYPE, @@ -565,8 +564,7 @@ def infer_fill_value(val): """ if not is_list_like(val): val = [val] - copy_false = None if np_version_gt2 else False - val = np.array(val, copy=copy_false) + val = np.asarray(val) if val.dtype.kind in "mM": return np.array("NaT", dtype=val.dtype) elif val.dtype == object: diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index ac90a6db6231a..a1ca9727c1dbf 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -44,10 +44,7 @@ Shape, npt, ) -from pandas.compat.numpy import ( - function as nv, - np_version_gt2, -) +from pandas.compat.numpy import function as nv from pandas.errors import ( InvalidIndexError, PerformanceWarning, @@ -773,8 +770,7 @@ def _values(self) -> np.ndarray: ): vals = vals.astype(object) - copy_false = None if np_version_gt2 else False - array_vals = np.array(vals, copy=copy_false) + array_vals = np.asarray(vals) array_vals = algos.take_nd(array_vals, codes, fill_value=index._na_value) values.append(array_vals) @@ -3361,8 +3357,7 @@ def convert_indexer(start, stop, step, indexer=indexer, codes=level_codes): locs = (level_codes >= idx.start) & (level_codes < idx.stop) return locs - copy_false = None if np_version_gt2 else False - locs = np.array(level_codes == idx, dtype=bool, copy=copy_false) + locs = np.asarray(level_codes == idx, dtype=bool) if not locs.any(): # The label is present in self.levels[level] but unused: diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 75bd7b9a68ea8..f1cbfb39b0c10 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -30,7 +30,6 @@ BlockValuesRefs, ) from pandas._libs.tslibs import Timestamp -from pandas.compat.numpy import np_version_gt2 from pandas.errors import ( AbstractMethodError, PerformanceWarning, @@ -1798,9 +1797,6 @@ def as_array( arr : ndarray """ passed_nan = lib.is_float(na_value) and isna(na_value) - copy_false = None if np_version_gt2 else False - if not copy: - copy = copy_false if len(self.blocks) == 0: arr = np.empty(self.shape, dtype=float) @@ -1828,6 +1824,8 @@ def as_array( na_value=na_value, copy=copy, ).reshape(blk.shape) + elif not copy: + arr = np.asarray(blk.values, dtype=dtype) else: arr = np.array(blk.values, dtype=dtype, copy=copy) diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 21be48aec9423..60ef953059d18 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -40,7 +40,6 @@ from pandas._libs.lib import is_string_array from pandas._libs.tslibs import timezones from pandas.compat._optional import import_optional_dependency -from pandas.compat.numpy import np_version_gt2 from pandas.compat.pickle_compat import patch_pickle from pandas.errors import ( AttributeConflictWarning, @@ -4044,8 +4043,7 @@ def _create_axes( if isinstance(data_converted.dtype, CategoricalDtype): ordered = data_converted.ordered meta = "category" - copy_false = None if np_version_gt2 else False - metadata = np.array(data_converted.categories, copy=copy_false).ravel() + metadata = np.asarray(data_converted.categories).ravel() data, dtype_name = _get_data_and_dtype_name(data_converted) diff --git a/pandas/tests/extension/array_with_attr/array.py b/pandas/tests/extension/array_with_attr/array.py index 1acf70beff6b6..2789d51ec2ce3 100644 --- a/pandas/tests/extension/array_with_attr/array.py +++ b/pandas/tests/extension/array_with_attr/array.py @@ -9,8 +9,6 @@ import numpy as np -from pandas.compat.numpy import np_version_gt2 - from pandas.core.dtypes.base import ExtensionDtype import pandas as pd @@ -51,9 +49,10 @@ def __init__(self, values, attr=None) -> None: @classmethod def _from_sequence(cls, scalars, *, dtype=None, copy=False): - if np_version_gt2 and not copy: - copy = None - data = np.array(scalars, dtype="float64", copy=copy) + if not copy: + data = np.asarray(scalars, dtype="float64") + else: + data = np.array(scalars, dtype="float64", copy=copy) return cls(data) def __getitem__(self, item): diff --git a/pandas/tests/extension/json/array.py b/pandas/tests/extension/json/array.py index b294aef162b52..e43b50322bb92 100644 --- a/pandas/tests/extension/json/array.py +++ b/pandas/tests/extension/json/array.py @@ -28,8 +28,6 @@ import numpy as np -from pandas.compat.numpy import np_version_gt2 - from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike from pandas.core.dtypes.common import ( is_bool_dtype, @@ -212,10 +210,10 @@ def astype(self, dtype, copy=True): value = self.astype(str) # numpy doesn't like nested dicts arr_cls = dtype.construct_array_type() return arr_cls._from_sequence(value, dtype=dtype, copy=False) - - if np_version_gt2 and not copy: - copy = None - return np.array([dict(x) for x in self], dtype=dtype, copy=copy) + elif not copy: + return np.asarray([dict(x) for x in self], dtype=dtype) + else: + return np.array([dict(x) for x in self], dtype=dtype, copy=copy) def unique(self): # Parent method doesn't work since np.array will try to infer diff --git a/pandas/tests/extension/list/array.py b/pandas/tests/extension/list/array.py index e2915cd94de5d..b3bb35c9396f4 100644 --- a/pandas/tests/extension/list/array.py +++ b/pandas/tests/extension/list/array.py @@ -11,8 +11,6 @@ import numpy as np -from pandas.compat.numpy import np_version_gt2 - from pandas.core.dtypes.base import ExtensionDtype import pandas as pd @@ -117,9 +115,10 @@ def astype(self, dtype, copy=True): elif is_string_dtype(dtype) and not is_object_dtype(dtype): # numpy has problems with astype(str) for nested elements return np.array([str(x) for x in self.data], dtype=dtype) - if np_version_gt2 and not copy: - copy = None - return np.array(self.data, dtype=dtype, copy=copy) + elif not copy: + return np.asarray(self.data, dtype=dtype) + else: + return np.array(self.data, dtype=dtype, copy=copy) @classmethod def _concat_same_type(cls, to_concat): diff --git a/pandas/tests/extension/test_common.py b/pandas/tests/extension/test_common.py index 2c5eb72bf65c9..5eda0f00f54ca 100644 --- a/pandas/tests/extension/test_common.py +++ b/pandas/tests/extension/test_common.py @@ -1,8 +1,6 @@ import numpy as np import pytest -from pandas.compat.numpy import np_version_gt2 - from pandas.core.dtypes import dtypes from pandas.core.dtypes.common import is_extension_array_dtype @@ -32,9 +30,10 @@ def astype(self, dtype, copy=True): if copy: return type(self)(self.data) return self - if np_version_gt2 and not copy: - copy = None - return np.array(self, dtype=dtype, copy=copy) + elif not copy: + return np.asarray(self, dtype=dtype) + else: + return np.array(self, dtype=dtype, copy=copy) class TestExtensionArrayDtype: