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:
ABC
0a12
1b34
2c56
Output melted DataFrame:
Avariablevalue
0aB1
1bB3
2cB5

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:
firstlastheightweight
personAJohnDoe5.5130
BMaryBo6.0150
Output melted DataFrame:
firstlastvariablevalue
personAJohnDoeheight5.5
BMaryBoheight6.0
AJohnDoeweight130.0
BMaryBoweight150.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:
famidbirthht1ht2
0112.83.4
1122.93.8
2132.22.9
3212.03.2
4221.82.8
5231.92.4
6312.23.3
7322.33.4
8332.12.9
Output Long Melted DataFrame:
ht
famidbirthage
1112.8
23.4
212.9
23.8
312.2
22.9
2112.0
23.2
211.8
22.8
311.9
22.4
3112.2
23.3
212.3
23.4
312.1
22.9
Advertisements