Skip to content

REGR: Performance of DataFrame.stack where columns are not a MultiIndex #58027

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 1 commit into from
Mar 27, 2024
Merged
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
20 changes: 12 additions & 8 deletions pandas/core/reshape/reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -932,14 +932,18 @@ def stack_v3(frame: DataFrame, level: list[int]) -> Series | DataFrame:
if len(frame.columns) == 1:
data = frame.copy()
else:
# Take the data from frame corresponding to this idx value
if len(level) == 1:
idx = (idx,)
gen = iter(idx)
column_indexer = tuple(
next(gen) if k in set_levels else slice(None)
for k in range(frame.columns.nlevels)
)
if not isinstance(frame.columns, MultiIndex) and not isinstance(idx, tuple):
# GH#57750 - if the frame is an Index with tuples, .loc below will fail
column_indexer = idx
else:
# Take the data from frame corresponding to this idx value
if len(level) == 1:
idx = (idx,)
gen = iter(idx)
column_indexer = tuple(
next(gen) if k in set_levels else slice(None)
for k in range(frame.columns.nlevels)
)
data = frame.loc[:, column_indexer]

if len(level) < frame.columns.nlevels:
Expand Down