From 07defde83465aa9b5287fc85205e87577fc5b49b Mon Sep 17 00:00:00 2001 From: Brock Date: Wed, 10 Jun 2020 17:31:19 -0700 Subject: [PATCH] BUG: DataFrame.unstack with non-consolidated --- pandas/core/reshape/reshape.py | 7 +++---- pandas/tests/frame/test_reshape.py | 11 +++++++++++ 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index 133fba0246497..391313fbb5283 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -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 @@ -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: @@ -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) diff --git a/pandas/tests/frame/test_reshape.py b/pandas/tests/frame/test_reshape.py index 2e707342a0793..a6c4089dc71e6 100644 --- a/pandas/tests/frame/test_reshape.py +++ b/pandas/tests/frame/test_reshape.py @@ -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