Skip to content

DOC: mention that stack/unstack implicicly sort #7937

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
Aug 5, 2014
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
14 changes: 14 additions & 0 deletions doc/source/reshaping.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
----------
Expand Down Expand Up @@ -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
----------
Expand Down
3 changes: 2 additions & 1 deletion pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
----------
Expand Down