Skip to content

BUG: Multiple unstack using row index level labels and multi level columns DataFrame #32990

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 7 commits into from
Mar 26, 2020
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,7 @@ Reshaping
- Bug in :meth:`DataFrame.apply` where callback was called with :class:`Series` parameter even though ``raw=True`` requested. (:issue:`32423`)
- Bug in :meth:`DataFrame.pivot_table` losing timezone information when creating a :class:`MultiIndex` level from a column with timezone-aware dtype (:issue:`32558`)
- :meth:`DataFrame.agg` now provides more descriptive ``SpecificationError`` message when attempting to aggregating non-existant column (:issue:`32755`)
- Bug in :meth:`DataFrame.unstack` when MultiIndexed columns and MultiIndexed rows were used (:issue:`32624`, :issue:`24729` and :issue:`28306`)

Sparse
^^^^^^
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/reshape/reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@ def _unstack_multiple(data, clocs, fill_value=None):
comp_ids, obs_ids = compress_group_index(group_index, sort=False)
recons_codes = decons_obs_group_ids(comp_ids, obs_ids, shape, ccodes, xnull=False)

if rlocs == []:
if not rlocs:
# Everything is in clocs, so the dummy df has a regular index
dummy_index = Index(obs_ids, name="__placeholder__")
else:
Expand All @@ -363,7 +363,7 @@ def _unstack_multiple(data, clocs, fill_value=None):
for i in range(len(clocs)):
val = clocs[i]
result = result.unstack(val, fill_value=fill_value)
clocs = [v if i > v else v - 1 for v in clocs]
clocs = [v if v < val else v - 1 for v in clocs]

return result

Expand Down
54 changes: 54 additions & 0 deletions pandas/tests/frame/test_reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -765,6 +765,60 @@ def test_unstack_unused_level(self, cols):
expected.index = expected.index.droplevel("C")
tm.assert_frame_equal(result, expected)

def test_unstack_long_index(self):
# PH 32624: Error when using a lot of indices to unstack.
# The error occurred only, if a lot of indices are used.
df = pd.DataFrame(
[[1]],
columns=pd.MultiIndex.from_tuples([[0]], names=["c1"]),
index=pd.MultiIndex.from_tuples(
[[0, 0, 1, 0, 0, 0, 1]],
names=["i1", "i2", "i3", "i4", "i5", "i6", "i7"],
),
)
result = df.unstack(["i2", "i3", "i4", "i5", "i6", "i7"])
expected = pd.DataFrame(
[[1]],
columns=pd.MultiIndex.from_tuples(
[[0, 0, 1, 0, 0, 0, 1]],
names=["c1", "i2", "i3", "i4", "i5", "i6", "i7"],
),
index=pd.Index([0], name="i1"),
)
tm.assert_frame_equal(result, expected)

def test_unstack_multi_level_cols(self):
# PH 24729: Unstack a df with multi level columns
df = pd.DataFrame(
[[0.0, 0.0], [0.0, 0.0]],
columns=pd.MultiIndex.from_tuples(
[["B", "C"], ["B", "D"]], names=["c1", "c2"]
),
index=pd.MultiIndex.from_tuples(
[[10, 20, 30], [10, 20, 40]], names=["i1", "i2", "i3"],
),
)
assert df.unstack(["i2", "i1"]).columns.names[-2:] == ["i2", "i1"]

def test_unstack_multi_level_rows_and_cols(self):
# PH 28306: Unstack df with multi level cols and rows
df = pd.DataFrame(
[[1, 2], [3, 4], [-1, -2], [-3, -4]],
columns=pd.MultiIndex.from_tuples([["a", "b", "c"], ["d", "e", "f"]]),
index=pd.MultiIndex.from_tuples(
[
["m1", "P3", 222],
["m1", "A5", 111],
["m2", "P3", 222],
["m2", "A5", 111],
],
names=["i1", "i2", "i3"],
),
)
result = df.unstack(["i3", "i2"])
expected = df.unstack(["i3"]).unstack(["i2"])
tm.assert_frame_equal(result, expected)

def test_unstack_nan_index(self): # GH7466
def cast(val):
val_str = "" if val != val else val
Expand Down