Skip to content

GH28301 check for non-unique index in stack_multi_columns #28336

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 3 commits into from
Sep 10, 2019
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/v1.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ Groupby/resample/rolling
Reshaping
^^^^^^^^^

-
- Bug in :meth:`DataFrame.stack` not handling non-unique indexes correctly when creating MultiIndex (:issue: `28301`)
-

Sparse
Expand Down
5 changes: 3 additions & 2 deletions pandas/core/reshape/reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -725,8 +725,9 @@ def _convert_level_number(level_num, columns):
new_names = list(this.index.names)
new_codes = [lab.repeat(levsize) for lab in this.index.codes]
else:
new_levels = [this.index]
new_codes = [np.arange(N).repeat(levsize)]
old_codes, old_levels = _factorize_from_iterable(this.index)
new_levels = [old_levels]
new_codes = [old_codes.repeat(levsize)]
new_names = [this.index.name] # something better?

new_levels.append(level_vals)
Expand Down
21 changes: 21 additions & 0 deletions pandas/tests/frame/test_reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -1002,6 +1002,27 @@ def test_stack_preserve_categorical_dtype_values(self):
)
tm.assert_series_equal(result, expected)

@pytest.mark.parametrize(
"index, columns",
[
([0, 0, 1, 1], pd.MultiIndex.from_product([[1, 2], ["a", "b"]])),
([0, 0, 2, 3], pd.MultiIndex.from_product([[1, 2], ["a", "b"]])),
([0, 1, 2, 3], pd.MultiIndex.from_product([[1, 2], ["a", "b"]])),
],
)
def test_stack_multi_columns_non_unique_index(self, index, columns):
# GH-28301
df = pd.DataFrame(index=index, columns=columns).fillna(1)
stacked = df.stack()
new_index = pd.MultiIndex.from_tuples(stacked.index.to_numpy())
expected = pd.DataFrame(
stacked.to_numpy(), index=new_index, columns=stacked.columns
)
tm.assert_frame_equal(stacked, expected)
stacked_codes = np.asarray(stacked.index.codes)
expected_codes = np.asarray(new_index.codes)
tm.assert_numpy_array_equal(stacked_codes, expected_codes)

@pytest.mark.parametrize("level", [0, 1])
def test_unstack_mixed_extension_types(self, level):
index = pd.MultiIndex.from_tuples(
Expand Down