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

Backport PR #54962 on branch 2.1.x (BUG: DataFrame.stack with future_stack=True failing when columns are tuples) #54971

Merged
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: 1 addition & 1 deletion doc/source/whatsnew/v2.1.1.rst
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ Fixed regressions

Bug fixes
~~~~~~~~~
-
- Fixed bug in :meth:`DataFrame.stack` with ``future_stack=True`` and columns a non-:class:`MultiIndex` consisting of tuples (:issue:`54948`)

.. ---------------------------------------------------------------------------
.. _whatsnew_211.other:
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/reshape/reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -908,7 +908,7 @@ def stack_v3(frame: DataFrame, level: list[int]) -> Series | DataFrame:
data = frame.copy()
else:
# Take the data from frame corresponding to this idx value
if not isinstance(idx, tuple):
if len(level) == 1:
idx = (idx,)
gen = iter(idx)
column_indexer = tuple(
Expand Down
16 changes: 16 additions & 0 deletions pandas/tests/frame/test_stack_unstack.py
Original file line number Diff line number Diff line change
Expand Up @@ -2508,3 +2508,19 @@ def test_unstack_mixed_level_names(self):
index=MultiIndex.from_tuples([(1, "red"), (2, "blue")], names=[0, "y"]),
)
tm.assert_frame_equal(result, expected)


def test_stack_tuple_columns(future_stack):
# GH#54948 - test stack when the input has a non-MultiIndex with tuples
df = DataFrame(
[[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=[("a", 1), ("a", 2), ("b", 1)]
)
result = df.stack(future_stack=future_stack)
expected = Series(
[1, 2, 3, 4, 5, 6, 7, 8, 9],
index=MultiIndex(
levels=[[0, 1, 2], [("a", 1), ("a", 2), ("b", 1)]],
codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2], [0, 1, 2, 0, 1, 2, 0, 1, 2]],
),
)
tm.assert_series_equal(result, expected)