Skip to content

Commit c3f97ef

Browse files
rhshadrachmroeschke
authored andcommitted
BUG: DataFrame.stack with future_stack=True failing when columns are tuples (pandas-dev#54962)
1 parent 911a0f1 commit c3f97ef

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

doc/source/whatsnew/v2.1.1.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ Fixed regressions
2828

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

3333
.. ---------------------------------------------------------------------------
3434
.. _whatsnew_211.other:

pandas/core/reshape/reshape.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -904,7 +904,7 @@ def stack_v3(frame: DataFrame, level: list[int]) -> Series | DataFrame:
904904
data = frame.copy()
905905
else:
906906
# Take the data from frame corresponding to this idx value
907-
if not isinstance(idx, tuple):
907+
if len(level) == 1:
908908
idx = (idx,)
909909
gen = iter(idx)
910910
column_indexer = tuple(

pandas/tests/frame/test_stack_unstack.py

+16
Original file line numberDiff line numberDiff line change
@@ -2508,3 +2508,19 @@ def test_unstack_mixed_level_names(self):
25082508
index=MultiIndex.from_tuples([(1, "red"), (2, "blue")], names=[0, "y"]),
25092509
)
25102510
tm.assert_frame_equal(result, expected)
2511+
2512+
2513+
def test_stack_tuple_columns(future_stack):
2514+
# GH#54948 - test stack when the input has a non-MultiIndex with tuples
2515+
df = DataFrame(
2516+
[[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=[("a", 1), ("a", 2), ("b", 1)]
2517+
)
2518+
result = df.stack(future_stack=future_stack)
2519+
expected = Series(
2520+
[1, 2, 3, 4, 5, 6, 7, 8, 9],
2521+
index=MultiIndex(
2522+
levels=[[0, 1, 2], [("a", 1), ("a", 2), ("b", 1)]],
2523+
codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2], [0, 1, 2, 0, 1, 2, 0, 1, 2]],
2524+
),
2525+
)
2526+
tm.assert_series_equal(result, expected)

0 commit comments

Comments
 (0)