Skip to content
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

DEPR: inplace argument in set_axis #49459

Merged
merged 4 commits into from
Nov 2, 2022
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,7 @@ Removal of prior version deprecations/changes
- Removed ``keep_tz`` argument in :meth:`DatetimeIndex.to_series` (:issue:`29731`)
- Remove arguments ``names`` and ``dtype`` from :meth:`Index.copy` and ``levels`` and ``codes`` from :meth:`MultiIndex.copy` (:issue:`35853`, :issue:`36685`)
- Remove argument ``inplace`` from :meth:`MultiIndex.set_levels` and :meth:`MultiIndex.set_codes` (:issue:`35626`)
- Removed argument ``inplace`` from :meth:`DataFrame.set_axis` and :meth:`Series.set_axis`, use ``obj = obj.set_axis(..., copy=False)`` instead (:issue:`48130`)
- Disallow passing positional arguments to :meth:`MultiIndex.set_levels` and :meth:`MultiIndex.set_codes` (:issue:`41485`)
- Removed :meth:`MultiIndex.is_lexsorted` and :meth:`MultiIndex.lexsort_depth` (:issue:`38701`)
- Removed argument ``how`` from :meth:`PeriodIndex.astype`, use :meth:`PeriodIndex.to_timestamp` instead (:issue:`37982`)
Expand Down
40 changes: 3 additions & 37 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -5046,39 +5046,6 @@ def align(
broadcast_axis=broadcast_axis,
)

@overload
def set_axis(
self,
labels,
*,
axis: Axis = ...,
inplace: Literal[False] | lib.NoDefault = ...,
copy: bool | lib.NoDefault = ...,
) -> DataFrame:
...

@overload
def set_axis(
self,
labels,
*,
axis: Axis = ...,
inplace: Literal[True],
copy: bool | lib.NoDefault = ...,
) -> None:
...

@overload
def set_axis(
self,
labels,
*,
axis: Axis = ...,
inplace: bool | lib.NoDefault = ...,
copy: bool | lib.NoDefault = ...,
) -> DataFrame | None:
...

# error: Signature of "set_axis" incompatible with supertype "NDFrame"
@Appender(
"""
Expand Down Expand Up @@ -5123,10 +5090,9 @@ def set_axis(
labels,
*,
axis: Axis = 0,
inplace: bool | lib.NoDefault = lib.no_default,
copy: bool | lib.NoDefault = lib.no_default,
):
return super().set_axis(labels, axis=axis, inplace=inplace, copy=copy)
copy: bool = True,
) -> DataFrame:
return super().set_axis(labels, axis=axis, copy=copy)

@Substitution(**_shared_doc_kwargs)
@Appender(NDFrame.reindex.__doc__)
Expand Down
68 changes: 5 additions & 63 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -695,47 +695,13 @@ def size(self) -> int:
# expected "int") [return-value]
return np.prod(self.shape) # type: ignore[return-value]

@overload
def set_axis(
self: NDFrameT,
labels,
*,
axis: Axis = ...,
inplace: Literal[False] | lib.NoDefault = ...,
copy: bool_t | lib.NoDefault = ...,
) -> NDFrameT:
...

@overload
def set_axis(
self,
labels,
*,
axis: Axis = ...,
inplace: Literal[True],
copy: bool_t | lib.NoDefault = ...,
) -> None:
...

@overload
def set_axis(
self: NDFrameT,
labels,
*,
axis: Axis = ...,
inplace: bool_t | lib.NoDefault = ...,
copy: bool_t | lib.NoDefault = ...,
) -> NDFrameT | None:
...

def set_axis(
self: NDFrameT,
labels,
*,
axis: Axis = 0,
inplace: bool_t | lib.NoDefault = lib.no_default,
copy: bool_t | lib.NoDefault = lib.no_default,
) -> NDFrameT | None:
copy: bool_t = True,
) -> NDFrameT:
"""
Assign desired index to given axis.

Expand All @@ -751,45 +717,21 @@ def set_axis(
The axis to update. The value 0 identifies the rows. For `Series`
this parameter is unused and defaults to 0.

inplace : bool, default False
Whether to return a new %(klass)s instance.

.. deprecated:: 1.5.0

copy : bool, default True
Whether to make a copy of the underlying data.

.. versionadded:: 1.5.0

Returns
-------
renamed : %(klass)s or None
An object of type %(klass)s or None if ``inplace=True``.
renamed : %(klass)s
An object of type %(klass)s.

See Also
--------
%(klass)s.rename_axis : Alter the name of the index%(see_also_sub)s.
"""
if inplace is not lib.no_default:
warnings.warn(
f"{type(self).__name__}.set_axis 'inplace' keyword is deprecated "
"and will be removed in a future version. Use "
"`obj = obj.set_axis(..., copy=False)` instead",
FutureWarning,
stacklevel=find_stack_level(),
)
else:
inplace = False

if inplace:
if copy is True:
raise ValueError("Cannot specify both inplace=True and copy=True")
copy = False
elif copy is lib.no_default:
copy = True

self._check_inplace_and_allows_duplicate_labels(inplace)
return self._set_axis_nocheck(labels, axis, inplace, copy=copy)
return self._set_axis_nocheck(labels, axis, inplace=False, copy=copy)

@final
def _set_axis_nocheck(self, labels, axis: Axis, inplace: bool_t, copy: bool_t):
Expand Down
42 changes: 4 additions & 38 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -4925,39 +4925,6 @@ def rename(
else:
return self._set_name(index, inplace=inplace)

@overload
def set_axis(
self,
labels,
*,
axis: Axis = ...,
inplace: Literal[False] | lib.NoDefault = ...,
copy: bool | lib.NoDefault = ...,
) -> Series:
...

@overload
def set_axis(
self,
labels,
*,
axis: Axis = ...,
inplace: Literal[True],
copy: bool | lib.NoDefault = ...,
) -> None:
...

@overload
def set_axis(
self,
labels,
*,
axis: Axis = ...,
inplace: bool | lib.NoDefault = ...,
copy: bool | lib.NoDefault = ...,
) -> Series | None:
...

# error: Signature of "set_axis" incompatible with supertype "NDFrame"
@Appender(
"""
Expand All @@ -4984,15 +4951,14 @@ def set_axis(
see_also_sub="",
)
@Appender(NDFrame.set_axis.__doc__)
def set_axis( # type: ignore[override]
def set_axis(
self,
labels,
*,
axis: Axis = 0,
inplace: bool | lib.NoDefault = lib.no_default,
copy: bool | lib.NoDefault = lib.no_default,
) -> Series | None:
return super().set_axis(labels, axis=axis, inplace=inplace, copy=copy)
copy: bool = True,
) -> Series:
return super().set_axis(labels, axis=axis, copy=copy)

# error: Cannot determine type of 'reindex'
@doc(
Expand Down
53 changes: 8 additions & 45 deletions pandas/tests/frame/methods/test_set_axis.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,9 @@ def obj(self):
def test_set_axis(self, obj):
# GH14636; this tests setting index for both Series and DataFrame
new_index = list("abcd")[: len(obj)]

expected = obj.copy()
expected.index = new_index

# inplace=False
msg = "set_axis 'inplace' keyword is deprecated"
with tm.assert_produces_warning(FutureWarning, match=msg):
result = obj.set_axis(new_index, axis=0, inplace=False)
result = obj.set_axis(new_index, axis=0)
tm.assert_equal(expected, result)

def test_set_axis_copy(self, obj):
Expand All @@ -34,12 +29,6 @@ def test_set_axis_copy(self, obj):
expected = obj.copy()
expected.index = new_index

with pytest.raises(
ValueError, match="Cannot specify both inplace=True and copy=True"
):
with tm.assert_produces_warning(FutureWarning):
obj.set_axis(new_index, axis=0, inplace=True, copy=True)

result = obj.set_axis(new_index, axis=0, copy=True)
tm.assert_equal(expected, result)
assert result is not obj
Expand Down Expand Up @@ -77,51 +66,25 @@ def test_set_axis_copy(self, obj):
for i in range(obj.shape[1])
)

# Do this last since it alters obj inplace
with tm.assert_produces_warning(FutureWarning):
res = obj.set_axis(new_index, inplace=True, copy=False)
assert res is None
tm.assert_equal(expected, obj)
res = obj.set_axis(new_index, copy=False)
tm.assert_equal(expected, res)
# check we did NOT make a copy
if obj.ndim == 1:
assert tm.shares_memory(obj, orig)
if res.ndim == 1:
assert tm.shares_memory(res, orig)
else:
assert all(
tm.shares_memory(obj.iloc[:, i], orig.iloc[:, i])
for i in range(obj.shape[1])
tm.shares_memory(res.iloc[:, i], orig.iloc[:, i])
for i in range(res.shape[1])
)

@pytest.mark.parametrize("axis", [0, "index", 1, "columns"])
def test_set_axis_inplace_axis(self, axis, obj):
# GH#14636
if obj.ndim == 1 and axis in [1, "columns"]:
# Series only has [0, "index"]
return

new_index = list("abcd")[: len(obj)]

expected = obj.copy()
if axis in [0, "index"]:
expected.index = new_index
else:
expected.columns = new_index

result = obj.copy()
with tm.assert_produces_warning(FutureWarning):
result.set_axis(new_index, axis=axis, inplace=True)
tm.assert_equal(result, expected)

def test_set_axis_unnamed_kwarg_warns(self, obj):
# omitting the "axis" parameter
new_index = list("abcd")[: len(obj)]

expected = obj.copy()
expected.index = new_index

with tm.assert_produces_warning(
FutureWarning, match="set_axis 'inplace' keyword"
):
result = obj.set_axis(new_index, inplace=False)
result = obj.set_axis(new_index)
tm.assert_equal(result, expected)

@pytest.mark.parametrize("axis", [3, "foo"])
Expand Down
13 changes: 2 additions & 11 deletions pandas/tests/generic/test_duplicate_labels.py
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,6 @@ def test_dataframe_insert_raises():
"method, frame_only",
[
(operator.methodcaller("set_index", "A", inplace=True), True),
(operator.methodcaller("set_axis", ["A", "B"], inplace=True), False),
(operator.methodcaller("reset_index", inplace=True), True),
(operator.methodcaller("rename", lambda x: x, inplace=True), False),
],
Expand All @@ -427,19 +426,11 @@ def test_inplace_raises(method, frame_only):
s.flags.allows_duplicate_labels = False
msg = "Cannot specify"

warn_msg = "Series.set_axis 'inplace' keyword"
if "set_axis" in str(method):
warn = FutureWarning
else:
warn = None

with pytest.raises(ValueError, match=msg):
with tm.assert_produces_warning(warn, match=warn_msg):
method(df)
method(df)
if not frame_only:
with pytest.raises(ValueError, match=msg):
with tm.assert_produces_warning(warn, match=warn_msg):
method(s)
method(s)


def test_pickle():
Expand Down