Skip to content

CLN: Remove Series.view/ravel, fastpath #57319

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions doc/redirects.csv
Original file line number Diff line number Diff line change
Expand Up @@ -1114,7 +1114,6 @@ generated/pandas.Series.ptp,../reference/api/pandas.Series.ptp
generated/pandas.Series.quantile,../reference/api/pandas.Series.quantile
generated/pandas.Series.radd,../reference/api/pandas.Series.radd
generated/pandas.Series.rank,../reference/api/pandas.Series.rank
generated/pandas.Series.ravel,../reference/api/pandas.Series.ravel
generated/pandas.Series.rdiv,../reference/api/pandas.Series.rdiv
generated/pandas.Series.rdivmod,../reference/api/pandas.Series.rdivmod
generated/pandas.Series.real,../reference/api/pandas.Series.real
Expand Down Expand Up @@ -1249,7 +1248,6 @@ generated/pandas.Series.valid,../reference/api/pandas.Series.valid
generated/pandas.Series.value_counts,../reference/api/pandas.Series.value_counts
generated/pandas.Series.values,../reference/api/pandas.Series.values
generated/pandas.Series.var,../reference/api/pandas.Series.var
generated/pandas.Series.view,../reference/api/pandas.Series.view
generated/pandas.Series.where,../reference/api/pandas.Series.where
generated/pandas.Series.xs,../reference/api/pandas.Series.xs
generated/pandas.set_option,../reference/api/pandas.set_option
Expand Down
2 changes: 0 additions & 2 deletions doc/source/reference/series.rst
Original file line number Diff line number Diff line change
Expand Up @@ -236,10 +236,8 @@ Reshaping, sorting
Series.unstack
Series.explode
Series.searchsorted
Series.ravel
Series.repeat
Series.squeeze
Series.view

Combining / comparing / joining / merging
-----------------------------------------
Expand Down
4 changes: 4 additions & 0 deletions doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -104,14 +104,18 @@ Deprecations
Removal of prior version deprecations/changes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- All arguments except the first ``path``-like argument in IO writers are now keyword only (:issue:`54229`)
- Removed ``DataFrame.first`` and ``DataFrame.last`` (:issue:`53710`)
- Removed ``DataFrameGroupBy.grouper`` and ``SeriesGroupBy.grouper`` (:issue:`56521`)
- Removed ``DataFrameGroupby.fillna`` and ``SeriesGroupBy.fillna``` (:issue:`55719`)
- Removed ``Series.ravel`` (:issue:`56053`)
- Removed ``Series.view`` (:issue:`56054`)
- Removed ``axis`` argument from :meth:`DataFrame.groupby`, :meth:`Series.groupby`, :meth:`DataFrame.rolling`, :meth:`Series.rolling`, :meth:`DataFrame.resample`, and :meth:`Series.resample` (:issue:`51203`)
- Removed ``axis`` argument from all groupby operations (:issue:`50405`)
- Removed ``pandas.io.sql.execute`` (:issue:`50185`)
- Removed ``read_gbq`` and ``DataFrame.to_gbq``. Use ``pandas_gbq.read_gbq`` and ``pandas_gbq.to_gbq`` instead https://pandas-gbq.readthedocs.io/en/latest/api.html (:issue:`55525`)
- Removed deprecated argument ``obj`` in :meth:`.DataFrameGroupBy.get_group` and :meth:`.SeriesGroupBy.get_group` (:issue:`53545`)
- Removed the ``ArrayManager`` (:issue:`55043`)
- Removed the ``fastpath`` argument from the :class:`Series` constructor (:issue:`55466`)
- Removed the ``is_boolean``, ``is_integer``, ``is_floating``, ``holds_integer``, ``is_numeric``, ``is_categorical``, ``is_object``, and ``is_interval`` attributes of :class:`Index` (:issue:`50042`)
- Removed unused arguments ``*args`` and ``**kwargs`` in :class:`Resampler` methods (:issue:`50977`)
- Unrecognized timezones when parsing strings to datetimes now raises a ``ValueError`` (:issue:`51477`)
Expand Down
134 changes: 1 addition & 133 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -385,18 +385,7 @@ def __init__(
dtype: Dtype | None = None,
name=None,
copy: bool | None = None,
fastpath: bool | lib.NoDefault = lib.no_default,
) -> None:
if fastpath is not lib.no_default:
warnings.warn(
"The 'fastpath' keyword in pd.Series is deprecated and will "
"be removed in a future version.",
DeprecationWarning,
stacklevel=find_stack_level(),
)
else:
fastpath = False

allow_mgr = False
if (
isinstance(data, SingleBlockManager)
Expand All @@ -417,11 +406,7 @@ def __init__(
data = data.copy(deep=False)
# GH#33357 called with just the SingleBlockManager
NDFrame.__init__(self, data)
if fastpath:
# e.g. from _box_col_values, skip validation of name
object.__setattr__(self, "_name", name)
else:
self.name = name
self.name = name
return

is_pandas_object = isinstance(data, (Series, Index, ExtensionArray))
Expand All @@ -435,31 +420,6 @@ def __init__(
if copy is None:
copy = False

# we are called internally, so short-circuit
if fastpath:
# data is a ndarray, index is defined
if not isinstance(data, SingleBlockManager):
data = SingleBlockManager.from_array(data, index)
allow_mgr = True
elif using_copy_on_write() and not copy:
data = data.copy(deep=False)

if not allow_mgr:
warnings.warn(
f"Passing a {type(data).__name__} to {type(self).__name__} "
"is deprecated and will raise in a future version. "
"Use public APIs instead.",
DeprecationWarning,
stacklevel=2,
)

if copy:
data = data.copy()
# skips validation of the name
object.__setattr__(self, "_name", name)
NDFrame.__init__(self, data)
return

if isinstance(data, SingleBlockManager) and using_copy_on_write() and not copy:
data = data.copy(deep=False)

Expand Down Expand Up @@ -851,104 +811,12 @@ def _references(self) -> BlockValuesRefs:
def array(self) -> ExtensionArray:
return self._mgr.array_values()

# ops
def ravel(self, order: str = "C") -> ArrayLike:
"""
Return the flattened underlying data as an ndarray or ExtensionArray.

.. deprecated:: 2.2.0
Series.ravel is deprecated. The underlying array is already 1D, so
ravel is not necessary. Use :meth:`to_numpy` for conversion to a numpy
array instead.

Returns
-------
numpy.ndarray or ExtensionArray
Flattened data of the Series.

See Also
--------
numpy.ndarray.ravel : Return a flattened array.

Examples
--------
>>> s = pd.Series([1, 2, 3])
>>> s.ravel() # doctest: +SKIP
array([1, 2, 3])
"""
warnings.warn(
"Series.ravel is deprecated. The underlying array is already 1D, so "
"ravel is not necessary. Use `to_numpy()` for conversion to a numpy "
"array instead.",
FutureWarning,
stacklevel=2,
)
arr = self._values.ravel(order=order)
if isinstance(arr, np.ndarray) and using_copy_on_write():
arr.flags.writeable = False
return arr

def __len__(self) -> int:
"""
Return the length of the Series.
"""
return len(self._mgr)

def view(self, dtype: Dtype | None = None) -> Series:
"""
Create a new view of the Series.

.. deprecated:: 2.2.0
``Series.view`` is deprecated and will be removed in a future version.
Use :meth:`Series.astype` as an alternative to change the dtype.

This function will return a new Series with a view of the same
underlying values in memory, optionally reinterpreted with a new data
type. The new data type must preserve the same size in bytes as to not
cause index misalignment.

Parameters
----------
dtype : data type
Data type object or one of their string representations.

Returns
-------
Series
A new Series object as a view of the same data in memory.

See Also
--------
numpy.ndarray.view : Equivalent numpy function to create a new view of
the same data in memory.

Notes
-----
Series are instantiated with ``dtype=float64`` by default. While
``numpy.ndarray.view()`` will return a view with the same data type as
the original array, ``Series.view()`` (without specified dtype)
will try using ``float64`` and may fail if the original data type size
in bytes is not the same.

Examples
--------
Use ``astype`` to change the dtype instead.
"""
warnings.warn(
"Series.view is deprecated and will be removed in a future version. "
"Use ``astype`` as an alternative to change the dtype.",
FutureWarning,
stacklevel=2,
)
# self.array instead of self._values so we piggyback on NumpyExtensionArray
# implementation
res_values = self.array.view(dtype)
res_ser = self._constructor(res_values, index=self.index, copy=False)
if isinstance(res_ser._mgr, SingleBlockManager):
blk = res_ser._mgr._block
blk.refs.add_reference(blk)
return res_ser.__finalize__(self, method="view")

# ----------------------------------------------------------------------
# NDArray Compat
def __array__(self, dtype: npt.DTypeLike | None = None) -> np.ndarray:
Expand Down
10 changes: 0 additions & 10 deletions pandas/tests/copy_view/test_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,16 +110,6 @@ def test_series_to_numpy(using_copy_on_write):
assert arr.flags.writeable is True


@pytest.mark.parametrize("order", ["F", "C"])
def test_ravel_read_only(using_copy_on_write, order):
ser = Series([1, 2, 3])
with tm.assert_produces_warning(FutureWarning, match="is deprecated"):
arr = ser.ravel(order=order)
if using_copy_on_write:
assert arr.flags.writeable is False
assert np.shares_memory(get_array(ser), arr)


def test_series_array_ea_dtypes(using_copy_on_write):
ser = Series([1, 2, 3], dtype="Int64")
arr = np.asarray(ser, dtype="int64")
Expand Down
31 changes: 2 additions & 29 deletions pandas/tests/copy_view/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,18 +90,13 @@ def test_series_from_series_with_reindex(using_copy_on_write):
assert not result._mgr.blocks[0].refs.has_reference()


@pytest.mark.parametrize("fastpath", [False, True])
@pytest.mark.parametrize("dtype", [None, "int64"])
@pytest.mark.parametrize("idx", [None, pd.RangeIndex(start=0, stop=3, step=1)])
@pytest.mark.parametrize(
"arr", [np.array([1, 2, 3], dtype="int64"), pd.array([1, 2, 3], dtype="Int64")]
)
def test_series_from_array(using_copy_on_write, idx, dtype, fastpath, arr):
if idx is None or dtype is not None:
fastpath = False
msg = "The 'fastpath' keyword in pd.Series is deprecated"
with tm.assert_produces_warning(DeprecationWarning, match=msg):
ser = Series(arr, dtype=dtype, index=idx, fastpath=fastpath)
def test_series_from_array(using_copy_on_write, idx, dtype, arr):
ser = Series(arr, dtype=dtype, index=idx)
ser_orig = ser.copy()
data = getattr(arr, "_data", arr)
if using_copy_on_write:
Expand Down Expand Up @@ -153,28 +148,6 @@ def test_series_from_index_different_dtypes(using_copy_on_write):
assert ser._mgr._has_no_reference(0)


@pytest.mark.filterwarnings("ignore:Setting a value on a view:FutureWarning")
@pytest.mark.parametrize("fastpath", [False, True])
@pytest.mark.parametrize("dtype", [None, "int64"])
@pytest.mark.parametrize("idx", [None, pd.RangeIndex(start=0, stop=3, step=1)])
def test_series_from_block_manager(using_copy_on_write, idx, dtype, fastpath):
ser = Series([1, 2, 3], dtype="int64")
ser_orig = ser.copy()
msg = "The 'fastpath' keyword in pd.Series is deprecated"
with tm.assert_produces_warning(DeprecationWarning, match=msg):
ser2 = Series(ser._mgr, dtype=dtype, fastpath=fastpath, index=idx)
assert np.shares_memory(get_array(ser), get_array(ser2))
if using_copy_on_write:
assert not ser2._mgr._has_no_reference(0)

ser2.iloc[0] = 100
if using_copy_on_write:
tm.assert_series_equal(ser, ser_orig)
else:
expected = Series([100, 2, 3])
tm.assert_series_equal(ser, expected)


def test_series_from_block_manager_different_dtype(using_copy_on_write):
ser = Series([1, 2, 3], dtype="int64")
msg = "Passing a SingleBlockManager to Series"
Expand Down
19 changes: 0 additions & 19 deletions pandas/tests/copy_view/test_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -1859,25 +1859,6 @@ def test_count_read_only_array():
tm.assert_series_equal(result, expected)


def test_series_view(using_copy_on_write):
ser = Series([1, 2, 3])
ser_orig = ser.copy()

with tm.assert_produces_warning(FutureWarning, match="is deprecated"):
ser2 = ser.view()
assert np.shares_memory(get_array(ser), get_array(ser2))
if using_copy_on_write:
assert not ser2._mgr._has_no_reference(0)

ser2.iloc[0] = 100

if using_copy_on_write:
tm.assert_series_equal(ser_orig, ser)
else:
expected = Series([100, 2, 3])
tm.assert_series_equal(ser, expected)


def test_insert_series(using_copy_on_write):
df = DataFrame({"a": [1, 2, 3]})
ser = Series([1, 2, 3])
Expand Down
4 changes: 1 addition & 3 deletions pandas/tests/frame/indexing/test_where.py
Original file line number Diff line number Diff line change
Expand Up @@ -761,15 +761,13 @@ def test_where_interval_fullop_downcast(self, frame_or_series):
"timedelta64[ns]",
"datetime64[ns]",
"datetime64[ns, Asia/Tokyo]",
"Period[D]",
],
)
def test_where_datetimelike_noop(self, dtype):
# GH#45135, analogue to GH#44181 for Period don't raise on no-op
# For td64/dt64/dt64tz we already don't raise, but also are
# checking that we don't unnecessarily upcast to object.
with tm.assert_produces_warning(FutureWarning, match="is deprecated"):
ser = Series(np.arange(3) * 10**9, dtype=np.int64).view(dtype)
ser = Series(np.arange(3) * 10**9, dtype=np.int64).astype(dtype)
df = ser.to_frame()
mask = np.array([False, False, False])

Expand Down
58 changes: 0 additions & 58 deletions pandas/tests/series/methods/test_view.py

This file was deleted.

7 changes: 0 additions & 7 deletions pandas/tests/series/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,13 +138,6 @@ def test_ndarray_compat_like_func(self):
expected = Series(1, index=range(10), dtype="float64")
tm.assert_series_equal(result, expected)

def test_ndarray_compat_ravel(self):
# ravel
s = Series(np.random.default_rng(2).standard_normal(10))
with tm.assert_produces_warning(FutureWarning, match="ravel is deprecated"):
result = s.ravel(order="F")
tm.assert_almost_equal(result, s.values.ravel(order="F"))

def test_empty_method(self):
s_empty = Series(dtype=object)
assert s_empty.empty
Expand Down