diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index 1c139f4692b52..b83f317814ad9 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -92,7 +92,7 @@ Other API changes Deprecations ~~~~~~~~~~~~ -- +- Deprecated accepting slices in :meth:`DataFrame.take`, call ``obj[slicer]`` or pass a sequence of integers instead (:issue:`51539`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 4a6b95f9a2e11..10e64f7fbd52c 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3749,6 +3749,9 @@ def __getitem__(self, key): if getattr(indexer, "dtype", None) == bool: indexer = np.where(indexer)[0] + if isinstance(indexer, slice): + return self._slice(indexer, axis=1) + data = self._take_with_is_copy(indexer, axis=1) if is_single_key: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 7c2e42ef71d46..33dc62564d34e 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -3910,6 +3910,14 @@ class max_speed "not slice." ) else: + warnings.warn( + # GH#51539 + f"Passing a slice to {type(self).__name__}.take is deprecated " + "and will raise in a future version. Use `obj[slicer]` or pass " + "a sequence of integers instead.", + FutureWarning, + stacklevel=find_stack_level(), + ) # We can get here with a slice via DataFrame.__getitem__ indices = np.arange( indices.start, indices.stop, indices.step, dtype=np.intp diff --git a/pandas/tests/frame/indexing/test_take.py b/pandas/tests/frame/indexing/test_take.py index a3d13ecd7b98e..8c17231440917 100644 --- a/pandas/tests/frame/indexing/test_take.py +++ b/pandas/tests/frame/indexing/test_take.py @@ -4,6 +4,16 @@ class TestDataFrameTake: + def test_take_slices_deprecated(self, float_frame): + # GH#51539 + df = float_frame + + slc = slice(0, 4, 1) + with tm.assert_produces_warning(FutureWarning): + df.take(slc, axis=0) + with tm.assert_produces_warning(FutureWarning): + df.take(slc, axis=1) + def test_take(self, float_frame): # homogeneous order = [3, 1, 2, 0]