Skip to content

Commit aa981dd

Browse files
author
patrick
committed
BUG: Fix bug for unstack with a lot of indices (pandas-dev#32624)
1 parent bed9103 commit aa981dd

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

pandas/core/reshape/reshape.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -363,7 +363,7 @@ def _unstack_multiple(data, clocs, fill_value=None):
363363
for i in range(len(clocs)):
364364
val = clocs[i]
365365
result = result.unstack(val, fill_value=fill_value)
366-
clocs = [v if i > v else v - 1 for v in clocs]
366+
clocs = [v if v < val else v - 1 for v in clocs]
367367

368368
return result
369369

pandas/tests/frame/test_reshape.py

+13
Original file line numberDiff line numberDiff line change
@@ -765,6 +765,19 @@ def test_unstack_unused_level(self, cols):
765765
expected.index = expected.index.droplevel("C")
766766
tm.assert_frame_equal(result, expected)
767767

768+
def test_unstack_long_index(self):
769+
# PH 32624: Error when using a lot of indices to unstack. The error occurred only, if a lot of indices are used.
770+
df = pd.DataFrame([[1]],
771+
columns=pd.MultiIndex.from_tuples([[0]], names=['c1']),
772+
index=pd.MultiIndex.from_tuples([[0, 0, 1, 0, 0, 0, 1]],
773+
names=['i1', 'i2', 'i3', 'i4', 'i5', 'i6', 'i7']))
774+
result = df.unstack(["i2", "i3", "i4", "i5", "i6", "i7"])
775+
expected = pd.DataFrame([[1]],
776+
columns=pd.MultiIndex.from_tuples([[0, 0, 1, 0, 0, 0, 1]],
777+
names=['c1', 'i2', 'i3', 'i4', 'i5', 'i6', 'i7']),
778+
index=pd.Index([0], name='i1'))
779+
tm.assert_frame_equal(result, expected)
780+
768781
def test_unstack_nan_index(self): # GH7466
769782
def cast(val):
770783
val_str = "" if val != val else val

0 commit comments

Comments
 (0)