Skip to content

Commit 472de31

Browse files
committed
Merge pull request #7937 from toobaz/stack_unstack_doc
DOC: mention that stack/unstack implicicly sort
2 parents 9b16d2e + e83ee58 commit 472de31

File tree

3 files changed

+19
-2
lines changed

3 files changed

+19
-2
lines changed

doc/source/reshaping.rst

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,20 @@ unstacks the **last level**:
151151
stacked.unstack(1)
152152
stacked.unstack(0)
153153
154+
Notice that the ``stack`` and ``unstack`` methods implicitly sort the index
155+
levels involved. Hence a call to ``stack`` and then ``unstack``, or viceversa,
156+
will result in a **sorted** copy of the original DataFrame or Series:
157+
158+
.. ipython:: python
159+
160+
index = MultiIndex.from_product([[2,1], ['a', 'b']])
161+
df = DataFrame(randn(4), index=index, columns=['A'])
162+
df
163+
all(df.unstack().stack() == df.sort())
164+
165+
while the above code will raise a ``TypeError`` if the call to ``sort`` is
166+
removed.
167+
154168
.. _reshaping.unstack_by_name:
155169

156170
If the indexes have names, you can use the level names instead of specifying

pandas/core/frame.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3278,6 +3278,7 @@ def stack(self, level=-1, dropna=True):
32783278
DataFrame (or Series in the case of an object with a single level of
32793279
column labels) having a hierarchical index with a new inner-most level
32803280
of row labels.
3281+
The level involved will automatically get sorted.
32813282
32823283
Parameters
32833284
----------
@@ -3317,7 +3318,8 @@ def unstack(self, level=-1):
33173318
a DataFrame having a new level of column labels whose inner-most level
33183319
consists of the pivoted index labels. If the index is not a MultiIndex,
33193320
the output will be a Series (the analogue of stack when the columns are
3320-
not a MultiIndex)
3321+
not a MultiIndex).
3322+
The level involved will automatically get sorted.
33213323
33223324
Parameters
33233325
----------

pandas/core/series.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1884,7 +1884,8 @@ def reorder_levels(self, order):
18841884

18851885
def unstack(self, level=-1):
18861886
"""
1887-
Unstack, a.k.a. pivot, Series with MultiIndex to produce DataFrame
1887+
Unstack, a.k.a. pivot, Series with MultiIndex to produce DataFrame.
1888+
The level involved will automatically get sorted.
18881889
18891890
Parameters
18901891
----------

0 commit comments

Comments
 (0)