Skip to content

BUG: Set dtypes of new columns when stacking (#36991) #40127

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 17 commits into from
Mar 10, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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
4 changes: 4 additions & 0 deletions pandas/core/reshape/reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -645,6 +645,10 @@ def _convert_level_number(level_num, columns):
unique_groups = [key for key, _ in itertools.groupby(tuples)]
new_names = this.columns.names[:-1]
new_columns = MultiIndex.from_tuples(unique_groups, names=new_names)
new_columns = new_columns.set_levels([
new_columns.levels[i].astype(this.columns.levels[i].dtype)
for i in range(0, len(new_columns.levels))
])
else:
new_columns = this.columns.levels[0]._rename(name=this.columns.names[0])
unique_groups = new_columns
Expand Down
20 changes: 20 additions & 0 deletions pandas/tests/frame/test_stack_unstack.py
Original file line number Diff line number Diff line change
Expand Up @@ -1052,6 +1052,26 @@ def test_stack_preserve_categorical_dtype(self, ordered, labels):

tm.assert_series_equal(result, expected)

@pytest.mark.parametrize("ordered", [False, True])
@pytest.mark.parametrize("labels", [list("yxz"), list("yzx")])
@pytest.mark.parametrize("labels2", [list("uv"), list("vu")])
def test_multi_stack_preserve_categorical_dtype(self, ordered, labels, labels2):
cidx = pd.CategoricalIndex(labels, categories=list("xyz"), ordered=ordered)
cidx2 = pd.CategoricalIndex(labels2, categories=list("uv"), ordered=ordered)
sorted_cidx = pd.CategoricalIndex(
list("xyz"), categories=list("xyz"), ordered=ordered)
sorted_cidx2 = pd.CategoricalIndex(
list("uv"), categories=list("uv"), ordered=ordered)

midx = MultiIndex.from_product([cidx, cidx2, [1, 2, 3]], names=['a', 'b', 'c'])
df = pd.DataFrame(np.random.randn(5, midx.size), columns=midx)
result = df.stack(['a', 'b'])

expected = MultiIndex.from_product(
[df.index, sorted_cidx, sorted_cidx2], names=[None, 'a', 'b'])

tm.assert_equal(result.index, expected)

def test_stack_preserve_categorical_dtype_values(self):
# GH-23077
cat = pd.Categorical(["a", "a", "b", "c"])
Expand Down