Skip to content

BUG: DataFrame.unstack with non-consolidated #34709

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 2 commits into from
Jun 14, 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
7 changes: 3 additions & 4 deletions pandas/core/reshape/reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,7 @@ class _Unstacker:

Parameters
----------
index : object
Pandas ``Index``
index : MultiIndex
level : int or str, default last level
Level to "unstack". Accepts a name for the level.
fill_value : scalar, optional
Expand Down Expand Up @@ -83,7 +82,7 @@ class _Unstacker:
"""

def __init__(
self, index, level=-1, constructor=None,
self, index: MultiIndex, level=-1, constructor=None,
):

if constructor is None:
Expand Down Expand Up @@ -415,7 +414,7 @@ def unstack(obj, level, fill_value=None):
level = obj.index._get_level_number(level)

if isinstance(obj, DataFrame):
if isinstance(obj.index, MultiIndex) or not obj._can_fast_transpose:
if isinstance(obj.index, MultiIndex):
return _unstack_frame(obj, level, fill_value=fill_value)
else:
return obj.T.stack(dropna=False)
Expand Down
11 changes: 11 additions & 0 deletions pandas/tests/frame/test_reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,17 @@ def test_stack_mixed_level(self):
expected = expected[["a", "b"]]
tm.assert_frame_equal(result, expected)

def test_unstack_not_consolidated(self):
# Gh#34708
df = pd.DataFrame({"x": [1, 2, np.NaN], "y": [3.0, 4, np.NaN]})
df2 = df[["x"]]
df2["y"] = df["y"]
assert len(df2._mgr.blocks) == 2

res = df2.unstack()
expected = df.unstack()
tm.assert_series_equal(res, expected)

def test_unstack_fill(self):

# GH #9746: fill_value keyword argument for Series
Expand Down