Skip to content

Commit 77c9fac

Browse files
Add an example where multiple levels are stacked at once.
1 parent 7e10273 commit 77c9fac

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed

pandas/core/frame.py

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5173,6 +5173,12 @@ def stack(self, level=-1, dropna=True):
51735173
that are missing from the original dataframe. See Examples
51745174
section.
51755175
5176+
Notes
5177+
-----
5178+
The function is named by analogy with a stack of books
5179+
(levels) being re-organised from a horizontal position (column
5180+
levels) to a vertical position (index levels).
5181+
51765182
Examples
51775183
--------
51785184
>>> df_single_level_cols = pd.DataFrame([[0, 1], [2, 3]],
@@ -5203,7 +5209,7 @@ def stack(self, level=-1, dropna=True):
52035209
b 3
52045210
dtype: int64
52055211
5206-
Stacking a dataframe with a multi-level column axis with no missing values:
5212+
Stacking a dataframe with a multi-level column axis:
52075213
52085214
>>> df_multi_level_cols1
52095215
X
@@ -5218,8 +5224,8 @@ def stack(self, level=-1, dropna=True):
52185224
b 3
52195225
52205226
It is common to have missing values when stacking a dataframe
5221-
with multi-level columns, since the stacked dataframe can have
5222-
more values than the original dataframe. By default the
5227+
with multi-level columns, as the stacked dataframe typically
5228+
has more values than the original dataframe. By default the
52235229
missing values are filled with NaNs:
52245230
52255231
>>> df_multi_level_cols2
@@ -5234,9 +5240,18 @@ def stack(self, level=-1, dropna=True):
52345240
two a 2.0 NaN
52355241
b NaN 3.0
52365242
5237-
Rows where all values are missing are dropped by default but
5238-
this behaviour can be controlled via the dropna keyword
5239-
parameter:
5243+
Multiple levels can be stacked at once
5244+
5245+
>>> df_multi_level_cols2.stack([1, 0])
5246+
one a X 0.0
5247+
b Y 1.0
5248+
two a X 2.0
5249+
b Y 3.0
5250+
dtype: float64
5251+
5252+
Note that rows where all values are missing are dropped by
5253+
default but this behaviour can be controlled via the dropna
5254+
keyword parameter:
52405255
52415256
>>> df_multi_level_cols3
52425257
X Y

0 commit comments

Comments
 (0)