Skip to content

Preserve Alignment Between Index and Values for Non-Monotonic Stack #20980

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

Closed
wants to merge 2 commits into from
Closed
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
8 changes: 7 additions & 1 deletion pandas/core/reshape/reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -653,7 +653,13 @@ def _convert_level_number(level_num, columns):
# time to ravel the values
new_data = {}
level_vals = this.columns.levels[-1]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we have a sort_monotonic function in a MI to do this

level_labels = sorted(set(this.columns.labels[-1]))
level_labels = list()
for label in this.columns.labels[-1]:
# GH 20945 if labels are not monotonic we were mangling
# alignment when moving to index; ensure we preserve order
if label not in level_labels:
level_labels.append(label)

level_vals_used = level_vals[level_labels]
levsize = len(level_labels)
drop_cols = []
Expand Down
19 changes: 19 additions & 0 deletions pandas/tests/frame/test_reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,25 @@ def test_stack_mixed_levels(self):
assert_frame_equal(df3.stack(level=['animal', 0]),
animal_hair_stacked, check_names=False)

def test_stack_retains_index_order_non_monotonic(self):
# GH 20945
df = pd.DataFrame([
['DIM', 'A', 1, 2, 3, 4],
['DIM', 'B', 11, 22, 33, 44],
])
df.columns = ["dim1", "dim2", 'c', 'b', 'a', 'd']
df.columns.name = 'foo'
df = df.set_index(["dim1", "dim2"])

expected_mi = pd.MultiIndex.from_product([['DIM'], ['c', 'b', 'a', 'd']])
expected_mi.names = ['dim1', 'foo']
expected = pd.DataFrame([[1, 11], [2, 22], [3, 33], [4, 44]],
index=expected_mi, columns=['A', 'B'])
expected.columns.name = 'dim2'

result = df.unstack('dim2').stack(level=0)
tm.assert_frame_equal(result, expected)

def test_stack_int_level_names(self):
columns = MultiIndex.from_tuples(
[('A', 'cat', 'long'), ('B', 'cat', 'long'),
Expand Down