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

Pandas Data Reshaping (pivot / melt / stack / unstack)

Pandas Data Reshaping (pivot / melt / stack / unstack)

Data reshaping is a common operation in data analysis used to change the layout of data. Pandas provides functions such as pivot, melt, stack, and unstack to convert between long and wide formats.


pivot (pivot table)

pivot Converts long-format data to wide format, similar to the pivot table feature in Excel.

Basic Usage

Example

import

pandas

as

pd

Create long-format data

df

=

pd.

DataFrame

(

{

   

"date"

:

[

"2024-01-01"

,

"2024-01-01"

,

"2024-01-02"

,

"2024-01-02"

]

,

   

"Product"

:

[

"A"

,

"B"

,

"A"

,

"B"

]

,

   

"Sales"

:

[

100

,

150

,

120

,

90

]

}

)

print

(

"Long-format data:"

)

print

(

df

)

print

(

)

Convert to wide format

pivot_df

=

df.

pivot

(

index

=

"date"

,

columns

=

"Product"

,

values

=

"Sales"

)

print

(

"Wide-format data:"

)

print

(

pivot_df

)

MultiIndex

Example

import

pandas

as

pd

df

=

pd.

DataFrame

(

{

   

"Year"

:

[

"2024"

,

"2024"

,

"2024"

,

"2024"

]

,

   

"Quarter"

:

[

"Q1"

,

"Q1"

,

"Q2"

,

"Q2"

]

,

   

"Product"

:

[

"A"

,

"B"

,

"A"

,

"B"

]

,

   

"Sales"

:

[

100

,

150

,

120

,

90

]

}

)

print

(

"Data:"

)

print

(

df

)

print

(

)

Pivot with a MultiIndex

pivot_df

=

df.

pivot

(

index

=

[

"Year"

,

"Quarter"

]

,

columns

=

"Product"

,

values

=

"Sales"

)

print

(

"Pivot with MultiIndex:"

)

print

(

pivot_df

)

Aggregation function

Example

import

pandas

as

pd

When duplicate values exist

df

=

pd.

DataFrame

(

{

   

"date"

:

[

"2024-01-01"

,

"2024-01-01"

,

"2024-01-01"

,

"2024-01-02"

]

,

   

"Product"

:

[

"A"

,

"A"

,

"B"

,

"B"

]

,

   

"Sales"

:

[

100

,

110

,

80

,

90

]

}

)

print

(

"Data with duplicate values:"

)

print

(

df

)

print

(

)

pivot does not support duplicate values by default; use pivot_table and specify an aggregation function

pivot_df

=

df.

pivot_table

(

index

=

"date"

,

columns

=

"Product"

,

values

=

"Sales"

,

aggfunc

=

"sum"

)

print

(

"Aggregate with sum:"

)

print

(

pivot_df

)

print

(

)

Using mean

print

(

"Aggregate with mean:"

)

print

(

df.

pivot_table

(

index

=

"date"

,

columns

=

"Product"

,

values

=

"Sales"

,

aggfunc

=

"mean"

)

)

pivot Duplicate values are not allowed; when they exist, use pivot_table and specify an aggregation function.


melt (unpivot)

melt Converts wide-format data to long format; it is the inverse of pivot.

Example

import

pandas

as

pd

Create wide-format data

df

=

pd.

DataFrame

(

{

   

"date"

:

[

"2024-01-01"

,

"2024-01-02"

]

,

   

"A"

:

[

100

,

120

]

,

   

"B"

:

[

150

,

90

]

}

)

print

(

"Wide-format data:"

)

print

(

df

)

print

(

)

Convert to long format

melted

=

df.

melt

(

id_vars

=

"date"

,

var_name

=

"Product"

,

value_name

=

"Sales"

)

print

(

"Long-format data:"

)

print

(

melted

)

Keep multiple columns unchanged

Example

import

pandas

as

pd

df

=

pd.

DataFrame

(

{

   

"City"

:

[

"Beijing"

,

"Shanghai"

]

,

   

"2023 revenue"

:

[

1000

,

800

]

,

   

"2023 profit"

:

[

200

,

150

]

,

   

"2024 revenue"

:

[

1200

,

950

]

,

   

"2024 profit"

:

[

250

,

180

]

}

)

print

(

"Wide format:"

)

print

(

df

)

print

(

)

Keep "city" unchanged and convert the other columns to long format

melted

=

df.

melt

(

    id_vars

=

"City"

,

    var_name

=

"Metric"

,

    value_name

=

"Value"

)

print

(

"Long format:"

)

print

(

melted

)


stack and unstack

stack and unstack are reshaping functions designed for MultiIndex.

unstack

Example

import

pandas

as

pd

Create data with a multi-level index

df

=

pd.

DataFrame

(

{

   

"A"

:

[

1

,

2

,

3

,

4

]

,

   

"B"

:

[

5

,

6

,

7

,

8

]

}

,

index

=

pd.

MultiIndex

.

from_tuples

(

   

[

(

"X"

,

1

)

,

(

"X"

,

2

)

,

(

"Y"

,

1

)

,

(

"Y"

,

2

)

]

,

    names

=

[

"Category"

,

"Number"

]

)

)

print

(

"Multi-level index data:"

)

print

(

df

)

print

(

)

unstack turns the inner index into columns

print

(

"After unstack:"

)

print

(

df.

unstack

(

)

)

stack

Example

import

pandas

as

pd

Create wide format (with a column index)

df

=

pd.

DataFrame

(

{

   

(

"A"

,

"X"

)

:

[

1

,

2

]

,

   

(

"A"

,

"Y"

)

:

[

3

,

4

]

,

   

(

"B"

,

"X"

)

:

[

5

,

6

]

,

   

(

"B"

,

"Y"

)

:

[

7

,

8

]

}

)

print

(

"With a multi-level column index:"

)

print

(

df

)

print

(

)

stack turns the column index into an inner index

print

(

"After stack:"

)

print

(

df.

stack

(

)

)


Practical example: transforming a business report

Example

import

pandas

as

pd

Simulated business data - sales records

sales

=

pd.

DataFrame

(

{

   

"date"

:

[

"2024-01"

]

4

,

   

"Product"

:

[

"Phone"

,

"Computer"

,

"Tablet"

,

"Headphones"

]

,

   

"Channel"

:

[

"Online"

,

"Online"

,

"Offline"

,

"Online"

]

,

   

"Sales"

:

[

10000

,

20000

,

8000

,

5000

]

}

)

print

(

"Original sales data:"

)

print

(

sales

)

print

(

)

Transform using pivot

pivot

=

sales.

pivot_table

(

    index

=

"Product"

,

    columns

=

"Channel"

,

    values

=

"Sales"

,

    aggfunc

=

"sum"

,

    fill_value

=

0

)

print

(

"Pivoted sales by channel:"

)

print

(

pivot

)

print

(

)

Restore to long format

print

(

"Restored to long format:"

)

print

(

pivot.

reset_index

(

)

.

melt

(

id_vars

=

"Product"

,

var_name

=

"Channel"

,

value_name

=

"Sales"

)

)


Choosing a reshaping function

function Purpose Typical scenario
pivot Long -> wide Row/column conversion
pivot_table Long -> wide (with aggregation) When duplicate values exist
melt Wide -> long Data tidying
unstack Index -> column Multi-level index
stack Column -> index Multi-level index

The goal of data reshaping is to make data more suitable for analysis or presentation. Choose the appropriate transformation based on downstream needs.