The Wayback Machine - https://web.archive.org/web/20240717024249/https://www.geeksforgeeks.org/reshape-a-pandas-dataframe-using-stackunstack-and-melt-method/
Open In App

Reshape a Pandas DataFrame using stack,unstack and melt method

Last Updated : 11 Jul, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Pandas use various methods to reshape the dataframe and series. Reshaping a Pandas DataFrame is a common operation to transform data structures for better analysis and visualization. The stack method pivots columns into rows, creating a multi-level index Series. Conversely, the unstack method reverses this process by pivoting inner index levels into columns. On the other hand, the melt method is used to transform wide-format data into a long-format, making it suitable for various analytical tasks. Let’s see about some of that reshaping method.

Importing the Dataset

To download the dataset used in this article click here.

Python
# import pandas module
import pandas as pd

# making dataframe
df = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")

# it was print the first 5-rows
print(df.head())

Output:

            Name            Team  Number Position   Age Height  Weight            College     Salary
0 Avery Bradley Boston Celtics 0.0 PG 25.0 6-2 180.0 Texas 7730337.0
1 Jae Crowder Boston Celtics 99.0 SF 25.0 6-6 235.0 Marquette 6796117.0
2 John Holland Boston Celtics 30.0 SG 27.0 6-5 205.0 Boston University NaN
3 R.J. Hunter Boston Celtics 28.0 SG 22.0 6-5 185.0 Georgia State 1148640.0
4 Jonas Jerebko Boston Celtics 8.0 PF 29.0 6-10 231.0 NaN 5000000.0

Reshape DataFrame in Pandas

Below are the three methods that we will use to reshape the layout of tables in Pandas:

  • Using Pandas stack() method
  • Using unstack() method
  • Using melt() method

Reshape the Layout of Tables in Pandas Using stack() method

The stack() method works with the MultiIndex objects in DataFrame, it returns a DataFrame with an index with a new inner-most level of row labels. It changes the wide table to a long table.

Python
# import pandas module
import pandas as pd

# making dataframe
df = pd.read_csv("nba.csv")

# reshape the dataframe using stack() method
df_stacked = df.stack()

print(df_stacked.head(26))

Output:

0  Name            Avery Bradley
Team Boston Celtics
Number 0.0
Position PG
Age 25.0
Height 6-2
Weight 180.0
College Texas
Salary 7730337.0
1 Name Jae Crowder
Team Boston Celtics
Number 99.0
Position SF
Age 25.0
Height 6-6
Weight 235.0
College Marquette
Salary 6796117.0
2 Name John Holland
Team Boston Celtics
Number 30.0
Position SG
Age 27.0
Height 6-5
Weight 205.0
College Boston University
dtype: object

Reshape a Pandas DataFrame Using unstack() method

The unstack() is similar to stack method, It also works with multi-index objects in dataframe, producing a reshaped DataFrame with a new inner-most level of column labels.

Python
# import pandas module
import pandas as pd

# making dataframe
df = pd.read_csv("nba.csv")

# unstack() method
df_unstacked = df_stacked.unstack()
print(df_unstacked.head(10))

Output:

            Name            Team Number Position   Age Height Weight           College      Salary  
0 Avery Bradley Boston Celtics 0.0 PG 25.0 6-2 180.0 Texas 7730337.0
1 Jae Crowder Boston Celtics 99.0 SF 25.0 6-6 235.0 Marquette 6796117.0
2 John Holland Boston Celtics 30.0 SG 27.0 6-5 205.0 Boston University NaN
3 R.J. Hunter Boston Celtics 28.0 SG 22.0 6-5 185.0 Georgia State 1148640.0
4 Jonas Jerebko Boston Celtics 8.0 PF 29.0 6-10 231.0 NaN 5000000.0
5 Amir Johnson Boston Celtics 90.0 PF 29.0 6-9 240.0 NaN 12000000.0
6 Jordan Mickey Boston Celtics 55.0 PF 21.0 6-8 235.0 LSU 1170960.0
7 Kelly Olynyk Boston Celtics 41.0 C 25.0 7-0 238.0 Gonzaga 2165160.0
8 Terry Rozier Boston Celtics 12.0 PG 22.0 6-2 190.0 Louisville 1824360.0
9 Marcus Smart Boston Celtics 36.0 PG 22.0 6-4 220.0 Oklahoma State 3431040.0

Reshape the Layout of Tables in Pandas Using melt() method

The melt() in Pandas reshape dataframe from wide format to long format. It uses the “id_vars[‘col_names’]” to melt the dataframe by column names.

Python
# import pandas module
import pandas as pd

# making dataframe
df = pd.read_csv("nba.csv")

# it takes two columns "Name" and "Team"
df_melt = df.melt(id_vars=['Name', 'Team'])
print(df_melt.head(10))

Output:

            Name            Team variable value
0 Avery Bradley Boston Celtics Number 0.0
1 Jae Crowder Boston Celtics Number 99.0
2 John Holland Boston Celtics Number 30.0
3 R.J. Hunter Boston Celtics Number 28.0
4 Jonas Jerebko Boston Celtics Number 8.0
5 Amir Johnson Boston Celtics Number 90.0
6 Jordan Mickey Boston Celtics Number 55.0
7 Kelly Olynyk Boston Celtics Number 41.0
8 Terry Rozier Boston Celtics Number 12.0
9 Marcus Smart Boston Celtics Number 36.0

Reshape a Pandas DataFrame using stack,unstack and melt method – FAQs

What does the stack() and unstack() Function Do on a DataFrame?

Stack():

  • stack() is a function in pandas that “compresses” a level in the DataFrame’s columns to produce a longer, narrower DataFrame (or Series if the resulting structure is one-dimensional). It essentially pivots the column labels into the row index, creating a multi-level index.

Unstack():

  • unstack() performs the inverse operation of stack(). It pivots a level of the (possibly hierarchical) row index into the column axis, producing a wider and shorter DataFrame. This is useful for unstacking grouped or aggregated data.

How to Reshape a Pandas DataFrame

Reshaping a DataFrame can be achieved through several functions including pivot(), melt(), stack(), and unstack(), each serving different reshaping needs:

  • Pivot is used to create a new derived table out of a given one.
  • Melt is used to transform or reshape data from wide format to long format.
  • Stack/Unstack as described above for moving column index levels to row index levels and vice-versa.

Difference Between Melt and Unstack in Pandas

  • Melt: This function is used to transform a DataFrame from a wide format to a long format. It can be seen as ‘unpivoting’ a DataFrame, turning columns into rows.
  • Unstack: This function moves information from the index to the columns. It is typically used on DataFrames with multi-level indexes to reshape them into a more readable form.

What does melt() Do in Python?

The melt() function in pandas transforms a DataFrame from a wide format to a long format. The id_vars specify columns to use as identifier variables, while value_vars specify columns to unpivot. If value_vars is not specified, all non-id_vars will be unpivoted.

Difference Between Stacking and Unstacking

  • Stacking: Converts DataFrame columns into a new level of index, making the DataFrame taller and narrower (more rows, fewer columns).
  • Unstacking: Converts a level of index into DataFrame columns, making the DataFrame shorter and wider (fewer rows, more columns).


Previous Article
Next Article

Similar Reads

Reshape Wide DataFrame to Tidy with identifiers using Pandas Melt
Sometimes we need to reshape the Pandas data frame to perform analysis in a better way. Reshaping plays a crucial role in data analysis. Pandas provide functions like melt and unmelt for reshaping. In this article, we will see what is Pandas Melt and how to use it to reshape wide to Tidy with identifiers. Pandas Melt(): Pandas.melt() unpivots a Dat
3 min read
Python | Pandas dataframe.melt()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.melt() function unpivots a DataFrame from wide format to long format, optionally leaving identifier variables set. This
2 min read
Pandas GroupBy - Unstack
Pandas Unstack is a function that pivots the level of the indexed columns in a stacked dataframe. A stacked dataframe is usually a result of an aggregated groupby function in pandas. Stack() sets the columns to a new level of hierarchy whereas Unstack() pivots the indexed column. There are different ways to Unstack a pandas dataframe which would be
4 min read
Reshaping Pandas Dataframes using Melt And Unmelt
Pandas is an open-source, BSD-licensed library written in Python Language. Pandas provide high performance, fast, easy to use data structures and data analysis tools for manipulating numeric data and time series. Pandas is built on the Numpy library and written in languages like Python, Cython, and C. In 2008, Wes McKinney developed the Pandas libr
3 min read
Python | Pandas.melt()
To make the analysis of data in a table easier, we can reshape the data into a more computer-friendly form using Pandas in Python. Pandas.melt() is one of the functions to do so.. Pandas.melt() unpivots a DataFrame from wide format to long format. Pandas melt() function is useful to massage a DataFrame into a format where one or more columns are id
3 min read
How to reshape Pandas Series?
In this article, we will see how to reshaping Pandas Series. So, for reshaping the Pandas Series we are using reshape() method of Pandas Series object. Syntax: Pandas.Series.values.reshape((dimension)) Return: return an ndarray with the values shape if the specified shape matches exactly the current shape, then return self (for compat) Let's see so
1 min read
How to Convert Wide Dataframe to Tidy Dataframe with Pandas stack()?
We might sometimes need a tidy/long-form of data for data analysis. So, in python's library Pandas there are a few ways to reshape a dataframe which is in wide form into a dataframe in long/tidy form. Here, we will discuss converting data from a wide form into a long-form using the pandas function stack(). stack() mainly stacks the specified index
4 min read
Difference between reshape() and resize() method in Numpy
Both the numpy.reshape() and numpy.resize() methods are used to change the size of a NumPy array. The difference between them is that the reshape() does not changes the original array but only returns the changed array, whereas the resize() method returns nothing and directly changes the original array. Example 1: Using reshape() C/C++ Code # impor
1 min read
What's the Difference Between Reshape and View in PyTorch?
PyTorch, a popular deep learning framework, offers two methods for reshaping tensors: torch.reshape and torch.view. While both methods can be used to change the shape of tensors, they have distinct differences in their behavior, constraints, and implications for memory usage. This article delves into the technical details of these methods, highligh
5 min read
Pandas DataFrame iterrows() Method | Pandas Method
Pandas DataFrame iterrows() iterates over a Pandas DataFrame rows in the form of (index, series) pair. This function iterates over the data frame column, it will return a tuple with the column name and content in the form of a series. Example: Python Code import pandas as pd df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 32, 3
2 min read
three90RightbarBannerImg