Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas df.stack() Function

Pandas df.stack() Function

Pandas Common Functions Common Pandas functions


df.stack() is a member method of DataFrame, used toConvert column indices to row indices. It "stacks" the columns of wide-format data into rows, producing a Series or DataFrame with a hierarchical index.

This is an important data reshaping operation, often used together with unstack() to achieve mutual conversion of data.

Word meaning: stack It means "stack/pile up"; here it refers to stacking column data into rows, converting a wide table into a long table.


Basic syntax and parameters

df.stack() is an instance method of DataFrame, called via the dot operator.

Syntax format



DataFrame.stack(level=-1, dropna=True)

Parameter Description

- Type: int, str, a list of int, or a list of str. - Description: Specify the level(s) to stack. For a MultiIndex, you can specify a concrete level number (starting from 0) or a level name. The default is -1, meaning the innermost level. - Type: boolean. - Description: Whether to drop rows in the result that are all NaN. The default is True, meaning rows containing all NaN values are removed.

Function description


Example

Let us thoroughly master df.stack() through a series of examples from simple to complex.

Example 1: Basic Usage - Converting Columns to Rows

Example

import

pandas

as

pd

import

numpy

as

np

1. Create wide-format data (one column per quarter)

df

=

pd.

DataFrame

(

{

   

'name'

:

[

'Alice'

,

'Bob'

,

'Charlie'

]

,

   

'Q1'

:

[

100

,

150

,

200

]

,

   

'Q2'

:

[

120

,

160

,

210

]

,

   

'Q3'

:

[

130

,

170

,

220

]

}

)

print

(

"=== Original wide-format data ==="

)

print

(

df

)

print

(

f

"Column names: {df.columns.tolist()}"

)

2. Use df.stack() to convert columns to rows

stacked

=

df.

stack

(

)

print

(

"n=== df.stack() Result ==="

)

print

(

stacked

)

print

(

f

"nType: {type(stacked)}"

)

3. Convert the result to a DataFrame for viewing

print

(

"n=== Converted to DataFrame ==="

)

stacked_df

=

stacked.

reset_index

(

)

stacked_df.

columns

=

[

'name'

,

'quarter'

,

'sales'

]

print

(

stacked_df

)

Expected output:



=== 原始宽格式数据 ===

      name  Q1   Q2   Q3

0    Alice  100  120  130

1      Bob  150  160  170

2  Charlie  'Q2', 'Q3'], columns=['name', 'quarter', 'sales']

...

Code analysis:

  1. The original data is in wide format, with Q1, Q2, Q3 as three columns of quarterly data.
  2. stack() "Stack" the three columns Q1, Q2, Q3 into rows.
  3. The result is a Series with two index levels: the outer level is the original row index and the inner level is the original column names (quarters).
  4. After stacking, the data becomes "long format", with only one quarter value per row.

Example 2: Stacking Multi-Level Column Indices

When a DataFrame has multi-level column indices, you can specify which level to stack.

Example

import

pandas

as

pd

import

numpy

as

np

1. Create data with a multi-level column index

Outer level: product type (Electronics, Furniture)

Inner level: quarter (Q1, Q2)

df

=

pd.

DataFrame

(

   

[

[

100

,

110

,

200

,

210

]

,

[

150

,

160

,

180

,

190

]

]

,

    index

=

[

'Store_A'

,

'Store_B'

]

,

    columns

=

pd.

MultiIndex

.

from_tuples

(

[

       

(

'Electronics'

,

'Q1'

)

,

(

'Electronics'

,

'Q2'

)

,

       

(

'Furniture'

,

'Q1'

)

,

(

'Furniture'

,

'Q2'

)

   

]

,

names

=

[

'Product'

,

'Quarter'

]

)

)

print

(

"=== Original data (multi-level column index) ==="

)

print

(

df

)

print

(

f

"Column index levels: {df.columns.names}"

)

2. Stack the inner columns (default, level=-1)

print

(

"n=== Stack inner columns (level=-1) ==="

)

stacked_inner

=

df.

stack

(

)

print

(

stacked_inner

)

3. Stack the outer columns

print

(

"n=== Stack outer columns (level=0) ==="

)

stacked_outer

=

df.

stack

(

level

=

0

)

print

(

stacked_outer

)

4. Stack all columns (producing a longer format)

print

(

"n=== Stack all columns ==="

)

stacked_all

=

df.

stack

(

level

=

[

0

,

1

]

)

print

(

stacked_all

)

Expected output:



=== 原始数据(多层列索引)===

Product      Electronics   Furniture

Quarter              Q1   Q2      Q1   Q

...

Code analysis:

Example 3: Handling Missing Values

Use dropna This parameter controls how missing values are handled.

Example

import

pandas

as

pd

import

numpy

as

np

1. Create data containing missing values

df

=

pd.

DataFrame

(

{

   

'name'

:

[

'Alice'

,

'Bob'

]

,

   

'Math'

:

[

100

,

np.

nan

]

,

   

'English'

:

[

90

,

85

]

,

   

'Science'

:

[

np.

nan

,

95

]

}

)

print

(

"=== Original data (with missing values) ==="

)

print

(

df

)

2. dropna=True (default), drop rows that are all NaN

print

(

"n=== dropna=True (default) ==="

)

stacked_drop

=

df.

stack

(

dropna

=

True

)

print

(

stacked_drop

)

3. dropna=False, keep NaN values

print

(

"n=== dropna=False ==="

)

stacked_keep

=

df.

stack

(

dropna

=

False

)

print

(

stacked_keep

)

4. Practical application: organize the stacked result into an analyzable long format

print

(

"n=== Organized into long-format DataFrame ==="

)

result

=

df.

set_index

(

'name'

)

.

stack

(

)

.

reset_index

(

)

result.

columns

=

[

'name'

,

'subject'

,

'score'

]

print

(

result

)

5. Drop missing values

result_clean

=

result.

dropna

(

)

print

(

"n=== After dropping missing values ==="

)

print

(

result_clean

)

Expected output:



=== 原始数据(包含缺失值)===

   name  Math  English  Science

0  Alice  100.0     90.0      NaN

1    Bob    NaN    85.0     95.0

2=== 堆叠内层列 (level=-1) ===

Store_A  Electronics  Q1    100

                  Q2    110

         Furniture   Q1    200

                  Q2    210

Store_B  Electronics  Q1    150

 ...

Code analysis:

Example 4: Using stack and unstack Together

stack() and unstack() They are inverse operations; used together they enable flexible data reshaping.

Example

import

pandas

as

pd

1. Create initial data

df

=

pd.

DataFrame

(

{

   

'product'

:

[

'A'

,

'B'

,

'C'

]

,

   

'North'

:

[

100

,

150

,

200

]

,

   

'South'

:

[

180

,

170

,

160

]

,

   

'East'

:

[

190

,

200

,

210

]

}

)

print

(

"=== Original data ==="

)

print

(

df

)

2. Use unstack to turn regions into columns (first convert to a multi-level index)

df_indexed

=

df.

set_index

(

'product'

)

print

(

"n=== After setting the index ==="

)

print

(

df_indexed

)

3. Use stack to turn columns into rows (stack is the inverse of unstack)

print

(

"n=== unstack + stack round trip ==="

)

First unstack

unstacked

=

df_indexed.

unstack

(

)

print

(

"unstack Result:"

)

print

(

unstacked

)

Then stack back

restacked

=

unstacked.

stack

(

)

print

(

"nStacked back:"

)

print

(

restacked

)

4. Complete example: create a multi-level index and then convert

print

(

"n=== Multi-level index conversion ==="

)

Create a multi-level index DataFrame

multi_df

=

pd.

DataFrame

(

   

[

[

100

,

110

]

,

[

150

,

160

]

]

,

    index

=

pd.

MultiIndex

.

from_tuples

(

[

(

'A'

,

'2023'

)

,

(

'B'

,

'2023'

)

]

,

names

=

[

'product'

,

'year'

]

)

,

    columns

=

[

'North'

,

'South'

]

)

print

(

"Original multi-level index data:"

)

print

(

multi_df

)

unstack year

print

(

"nunstack year:"

)

print

(

multi_df.

unstack

(

level

=

'year'

)

)

unstack columns

print

(

"nunstack columns (to columns):"

)

print

(

multi_df.

unstack

(

level

=

'columns'

)

)

Expected output:



=== unstack + stack 往返 ===

unstack 结果:

       product

North  A          100

       B          150

       C          200

South  A          180

       B          170

...

Code analysis:

Tip: stack() and unstack() It is a core tool for data reshaping.stack() It "piles" columns into rows (wide to long),unstack() and "unpiles" rows into columns (long to wide).

Pandas Common Functions Common Pandas functions