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 5 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
11 changes: 9 additions & 2 deletions pandas/core/reshape/reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -643,8 +643,15 @@ def _convert_level_number(level_num, columns):
levs.append(np.take(lev, level_codes))
tuples = list(zip(*levs))
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 = MultiIndex.from_arrays(
[
Index(new_level, dtype=level.dtype)
if None not in new_level
Copy link
Contributor

Choose a reason for hiding this comment

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

do we have any tests that hit the None case?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes, specifically test_stack_nan_in_multiindex_columns.

None is a tricky case---it is allowed for some Index types (like CategoricalIndex) but not others (like Int64Index). I am just avoiding levels with None entirely.

I've also looked at the way None is handled elsewhere, and it's not totally consistent:

>>> MultiIndex.from_arrays([[1, 2, None]]).levels[0]
Int64Index([1, 2], dtype='int64')

But:

>>> Index([1, 2, None])
Index([1, 2, None], dtype='object')

Perhaps in the future it would be better if Index accepted None values, even when a dtype is specified. Then Index([1, 2, None], dtype='int64') would return Int64Index([1, 2], dtype='int64'). Then we wouldn't need such a condition here. Thoughts?

Copy link
Contributor

Choose a reason for hiding this comment

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

hmm interesting, ok can you open an issue specifically showing the MI vs Index cases. I agree we should do something about this. ok for here on this PR.

else new_level
for new_level, level in zip(zip(*unique_groups), this.columns.levels)
],
names=this.columns.names[:-1],
)
else:
new_columns = this.columns.levels[0]._rename(name=this.columns.names[0])
unique_groups = new_columns
Expand Down
24 changes: 24 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,30 @@ 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):
# GH-36991
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=list("abc"))
df = 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