
- Python Pandas - Home
- Python Pandas - Introduction
- Python Pandas - Environment Setup
- Python Pandas - Basics
- Python Pandas - Introduction to Data Structures
- Python Pandas - Index Objects
- Python Pandas - Panel
- Python Pandas - Basic Functionality
- Python Pandas - Indexing & Selecting Data
- Python Pandas - Series
- Python Pandas - Series
- Python Pandas - Slicing a Series Object
- Python Pandas - Attributes of a Series Object
- Python Pandas - Arithmetic Operations on Series Object
- Python Pandas - Converting Series to Other Objects
- Python Pandas - DataFrame
- Python Pandas - DataFrame
- Python Pandas - Accessing DataFrame
- Python Pandas - Slicing a DataFrame Object
- Python Pandas - Modifying DataFrame
- Python Pandas - Removing Rows from a DataFrame
- Python Pandas - Arithmetic Operations on DataFrame
- Python Pandas - IO Tools
- Python Pandas - IO Tools
- Python Pandas - Working with CSV Format
- Python Pandas - Reading & Writing JSON Files
- Python Pandas - Reading Data from an Excel File
- Python Pandas - Writing Data to Excel Files
- Python Pandas - Working with HTML Data
- Python Pandas - Clipboard
- Python Pandas - Working with HDF5 Format
- Python Pandas - Comparison with SQL
- Python Pandas - Data Handling
- Python Pandas - Sorting
- Python Pandas - Reindexing
- Python Pandas - Iteration
- Python Pandas - Concatenation
- Python Pandas - Statistical Functions
- Python Pandas - Descriptive Statistics
- Python Pandas - Working with Text Data
- Python Pandas - Function Application
- Python Pandas - Options & Customization
- Python Pandas - Window Functions
- Python Pandas - Aggregations
- Python Pandas - Merging/Joining
- Python Pandas - MultiIndex
- Python Pandas - Basics of MultiIndex
- Python Pandas - Indexing with MultiIndex
- Python Pandas - Advanced Reindexing with MultiIndex
- Python Pandas - Renaming MultiIndex Labels
- Python Pandas - Sorting a MultiIndex
- Python Pandas - Binary Operations
- Python Pandas - Binary Comparison Operations
- Python Pandas - Boolean Indexing
- Python Pandas - Boolean Masking
- Python Pandas - Data Reshaping & Pivoting
- Python Pandas - Pivoting
- Python Pandas - Stacking & Unstacking
- Python Pandas - Melting
- Python Pandas - Computing Dummy Variables
- Python Pandas - Categorical Data
- Python Pandas - Categorical Data
- Python Pandas - Ordering & Sorting Categorical Data
- Python Pandas - Comparing Categorical Data
- Python Pandas - Handling Missing Data
- Python Pandas - Missing Data
- Python Pandas - Filling Missing Data
- Python Pandas - Interpolation of Missing Values
- Python Pandas - Dropping Missing Data
- Python Pandas - Calculations with Missing Data
- Python Pandas - Handling Duplicates
- Python Pandas - Duplicated Data
- Python Pandas - Counting & Retrieving Unique Elements
- Python Pandas - Duplicated Labels
- Python Pandas - Grouping & Aggregation
- Python Pandas - GroupBy
- Python Pandas - Time-series Data
- Python Pandas - Date Functionality
- Python Pandas - Timedelta
- Python Pandas - Sparse Data Structures
- Python Pandas - Sparse Data
- Python Pandas - Visualization
- Python Pandas - Visualization
- Python Pandas - Additional Concepts
- Python Pandas - Caveats & Gotchas
Python Pandas - Melting
Melting in Pandas is the process of converting a DataFrame from a wide format to a long format. In the wide format, data is spread across multiple columns. In simpler terms, it "unpivots" the DataFrame columns into rows, and it is useful for visualizing and performing statistical analysis on datasets.
Pandas provides two primary methods for melting DataFrames −
melt(): This function "unpivots" DataFrame from wide to long format, making it easier to reshape the data.
wide_to_long(): This function offers more options for melting, especially when working with column matching.
In this tutorial, we will learn about the melt() and wide_to_long() functions in Pandas and how these two methods can be used to transform a DataFrame from a wide format to a long format.
Melting in Pandas
The melt() function in Pandas converts a wide DataFrame into a long format. Which is nothing but "unpivots" the DataFrame.
Example
The following example demonstrates melting a simple DataFrame using the pandas.melt() function.
import pandas as pd # Create a DataFrame df = pd.DataFrame({'A': {0: 'a', 1: 'b', 2: 'c'},'B': {0: 1, 1: 3, 2: 5},'C': {0: 2, 1: 4, 2: 6}}) # Display the input DataFrame print('Input DataFrame:\n', df) # Melt the DataFrame melted_df = pd.melt(df, id_vars=['A'], value_vars=['B']) print('Output melted DataFrame:\n', melted_df)
Following is the output of the above code −
Input DataFrame:
A | B | C | |
---|---|---|---|
0 | a | 1 | 2 |
1 | b | 3 | 4 |
2 | c | 5 | 6 |
A | variable | value | |
---|---|---|---|
0 | a | B | 1 |
1 | b | B | 3 |
2 | c | B | 5 |
Example: Handling Index Values While Melting
This example demonstrates how to handle the missing values while melting the DataFrame using the pandas.melt() function.
import pandas as pd # Create a DataFrame index = pd.MultiIndex.from_tuples([("person", "A"), ("person", "B")]) df= pd.DataFrame({ "first": ["John", "Mary"],"last": ["Doe", "Bo"], "height": [5.5, 6.0],"weight": [130, 150]}, index=index) # Display the input DataFrame print('Input DataFrame:\n', df) # Melt the DataFrame melted_df = pd.melt(df, id_vars=["first", "last"], ignore_index=False) print('Output melted DataFrame:\n', melted_df)
Following is the output of the above code −
Input DataFrame:
first | last | height | weight | ||
---|---|---|---|---|---|
person | A | John | Doe | 5.5 | 130 |
B | Mary | Bo | 6.0 | 150 |
first | last | variable | value | ||
---|---|---|---|---|---|
person | A | John | Doe | height | 5.5 |
B | Mary | Bo | height | 6.0 | |
A | John | Doe | weight | 130.0 | |
B | Mary | Bo | weight | 150.0 |
Melting with wide_to_long()
The pandas wide_to_long() function provides more control over the transformation. It's useful when your columns have a structured naming pattern that includes a suffix.
Example
This example uses the wide_to_long() function for performing the advanced melting transformations.
import pandas as pd # Create a DataFrame df = pd.DataFrame({'famid': [1, 1, 1, 2, 2, 2, 3, 3, 3], 'birth': [1, 2, 3, 1, 2, 3, 1, 2, 3], 'ht1': [2.8, 2.9, 2.2, 2, 1.8, 1.9, 2.2, 2.3, 2.1], 'ht2': [3.4, 3.8, 2.9, 3.2, 2.8, 2.4, 3.3, 3.4, 2.9]}) # Display the input DataFrame print('Input DataFrame:\n', df) # Melt the DataFrame using wide_to_long() long_df = pd.wide_to_long(df, stubnames='ht', i=['famid', 'birth'], j='age') print('Output Long Melted DataFrame:\n', long_df)
Following is the output of the above code −
Input DataFrame:
famid | birth | ht1 | ht2 | |
---|---|---|---|---|
0 | 1 | 1 | 2.8 | 3.4 |
1 | 1 | 2 | 2.9 | 3.8 |
2 | 1 | 3 | 2.2 | 2.9 |
3 | 2 | 1 | 2.0 | 3.2 |
4 | 2 | 2 | 1.8 | 2.8 |
5 | 2 | 3 | 1.9 | 2.4 |
6 | 3 | 1 | 2.2 | 3.3 |
7 | 3 | 2 | 2.3 | 3.4 |
8 | 3 | 3 | 2.1 | 2.9 |
ht | |||
---|---|---|---|
famid | birth | age | |
1 | 1 | 1 | 2.8 |
2 | 3.4 | ||
2 | 1 | 2.9 | |
2 | 3.8 | ||
3 | 1 | 2.2 | |
2 | 2.9 | ||
2 | 1 | 1 | 2.0 |
2 | 3.2 | ||
2 | 1 | 1.8 | |
2 | 2.8 | ||
3 | 1 | 1.9 | |
2 | 2.4 | ||
3 | 1 | 1 | 2.2 |
2 | 3.3 | ||
2 | 1 | 2.3 | |
2 | 3.4 | ||
3 | 1 | 2.1 | |
2 | 2.9 |