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

ENH: droplevel copy keyword #48117

Closed
Closed
Show file tree
Hide file tree
Changes from 3 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/v1.5.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,7 @@ Other enhancements
- :meth:`DataFrame.quantile` gained a ``method`` argument that can accept ``table`` to evaluate multi-column quantiles (:issue:`43881`)
- :class:`Interval` now supports checking whether one interval is contained by another interval (:issue:`46613`)
- Added ``copy`` keyword to :meth:`Series.set_axis` and :meth:`DataFrame.set_axis` to allow user to set axis on a new object without necessarily copying the underlying data (:issue:`47932`)
- :meth:`DataFrame.droplevel` and :meth:`Series.droplevel` support a ``copy`` argument. if ``False``, the underlying data is not copied (:issue:`48117`)
- :meth:`Series.add_suffix`, :meth:`DataFrame.add_suffix`, :meth:`Series.add_prefix` and :meth:`DataFrame.add_prefix` support a ``copy`` argument. If ``False``, the underlying data is not copied in the returned object (:issue:`47934`)
- :meth:`DataFrame.set_index` now supports a ``copy`` keyword. If ``False``, the underlying data is not copied when a new :class:`DataFrame` is returned (:issue:`48043`)

Expand Down
11 changes: 9 additions & 2 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -843,7 +843,9 @@ def swapaxes(

@final
@doc(klass=_shared_doc_kwargs["klass"])
def droplevel(self: NDFrameT, level: IndexLabel, axis: Axis = 0) -> NDFrameT:
def droplevel(
self: NDFrameT, level: IndexLabel, axis: Axis = 0, copy: bool_t = True
) -> NDFrameT:
"""
Return {klass} with requested index / column level(s) removed.

Expand All @@ -862,6 +864,11 @@ def droplevel(self: NDFrameT, level: IndexLabel, axis: Axis = 0) -> NDFrameT:

For `Series` this parameter is unused and defaults to 0.

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

.. versionadded:: 1.5.0

Returns
-------
{klass}
Expand Down Expand Up @@ -904,7 +911,7 @@ def droplevel(self: NDFrameT, level: IndexLabel, axis: Axis = 0) -> NDFrameT:
"""
labels = self._get_axis(axis)
new_labels = labels.droplevel(level)
return self.set_axis(new_labels, axis=axis, inplace=False)
return self.set_axis(new_labels, axis=axis, copy=copy)

def pop(self, item: Hashable) -> Series | Any:
result = self[item]
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/reshape/pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ def __internal_pivot_table(

# discard the top level
if values_passed and not values_multi and table.columns.nlevels > 1:
table = table.droplevel(0, axis=1)
table = table.droplevel(0, axis=1, copy=False)
if len(index) == 0 and len(columns) > 0:
table = table.T

Expand Down
5 changes: 1 addition & 4 deletions pandas/core/reshape/reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -535,10 +535,7 @@ def _unstack_extension_series(series: Series, level, fill_value) -> DataFrame:
df = series.to_frame()
result = df.unstack(level=level, fill_value=fill_value)

# equiv: result.droplevel(level=0, axis=1)
# but this avoids an extra copy
result.columns = result.columns.droplevel(0)
return result
return result.droplevel(level=0, axis=1, copy=False)


def stack(frame: DataFrame, level=-1, dropna: bool = True):
Expand Down
25 changes: 25 additions & 0 deletions pandas/tests/frame/methods/test_droplevel.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,28 @@ def test_droplevel(self, frame_or_series):
# test that droplevel raises ValueError on axis != 0
with pytest.raises(ValueError, match="No axis named columns"):
df.droplevel(1, axis="columns")

def test_droplevel_copy(self, frame_or_series):
cols = MultiIndex.from_tuples(
[("c", "e"), ("d", "f")], names=["level_1", "level_2"]
)
mi = MultiIndex.from_tuples([(1, 2), (5, 6), (9, 10)], names=["a", "b"])
df = DataFrame([[3, 4], [7, 8], [11, 12]], index=mi, columns=cols)
if frame_or_series is not DataFrame:
df = df.iloc[:, 0]

# Check that we DID make a copy
res = df.droplevel("a", axis="index", copy=True)
if frame_or_series is DataFrame:
for i in range(df.shape[1]):
assert not tm.shares_memory(df.iloc[:, i], res.iloc[:, i])
else:
assert not tm.shares_memory(res, df)

# Check that we did NOT make a copy
res = df.droplevel("a", axis="index", copy=False)
if frame_or_series is DataFrame:
for i in range(df.shape[1]):
assert tm.shares_memory(df.iloc[:, i], res.iloc[:, i])
else:
assert tm.shares_memory(res, df)