diff --git a/doc/source/reshaping.rst b/doc/source/reshaping.rst index 768190975db2d..92a35d0276e22 100644 --- a/doc/source/reshaping.rst +++ b/doc/source/reshaping.rst @@ -151,6 +151,20 @@ unstacks the **last level**: stacked.unstack(1) stacked.unstack(0) +Notice that the ``stack`` and ``unstack`` methods implicitly sort the index +levels involved. Hence a call to ``stack`` and then ``unstack``, or viceversa, +will result in a **sorted** copy of the original DataFrame or Series: + +.. ipython:: python + + index = MultiIndex.from_product([[2,1], ['a', 'b']]) + df = DataFrame(randn(4), index=index, columns=['A']) + df + all(df.unstack().stack() == df.sort()) + +while the above code will raise a ``TypeError`` if the call to ``sort`` is +removed. + .. _reshaping.unstack_by_name: If the indexes have names, you can use the level names instead of specifying diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 4b8d13ce30355..81e43fb039554 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3278,6 +3278,7 @@ def stack(self, level=-1, dropna=True): DataFrame (or Series in the case of an object with a single level of column labels) having a hierarchical index with a new inner-most level of row labels. + The level involved will automatically get sorted. Parameters ---------- @@ -3317,7 +3318,8 @@ def unstack(self, level=-1): a DataFrame having a new level of column labels whose inner-most level consists of the pivoted index labels. If the index is not a MultiIndex, the output will be a Series (the analogue of stack when the columns are - not a MultiIndex) + not a MultiIndex). + The level involved will automatically get sorted. Parameters ---------- diff --git a/pandas/core/series.py b/pandas/core/series.py index c0e1e8a13eea3..d1f861b7f7fd7 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1884,7 +1884,8 @@ def reorder_levels(self, order): def unstack(self, level=-1): """ - Unstack, a.k.a. pivot, Series with MultiIndex to produce DataFrame + Unstack, a.k.a. pivot, Series with MultiIndex to produce DataFrame. + The level involved will automatically get sorted. Parameters ----------