Towards AI

The leading AI community and content platform focused on making AI accessible to all. Check out our new course platform: https://academy.towardsai.net/courses/beginner-to-advanced-llm-dev

Follow publication

Pandas.melt() function examples | Image by the Author | All images are from the author(s) unless stated otherwise.
Pandas.melt() function examples | Image by the Author | All images are from the author(s) unless stated otherwise.

Member-only story

Data Science, Editorial, Programming

Understanding Pandas Melt — pd.melt()

Towards AI Editorial Team
Towards AI
Published in
8 min readApr 23, 2021

--

Author(s): Pratik Shukla, Roberto Iriondo

This tutorial will dive deeper into Pandas’ pd.melt() function to understand its core functionalities with graphics and its implementation in Python. We will first see the syntax and parameters for this method. Then we will take a few examples to understand all the pd.melt() function parameters. The companion resources to this tutorial can be found either on Google Colab or Github.

What is PD Melt?

The Pandas melt() function is within many other methods used to reshape the pandas DataFrames from wide to a long format which is particularly useful in data science. However, the pd.melt() function is the most efficient and flexible among them. The pd.melt() function unpivots/melts the pandas DataFrame from a wide to a long format.

Figure 1: Syntax of pd.melt( ) Function.
Figure 1: Syntax of pd.melt( ) function.

Wide versus Long DataFrame:

Before converting our wide DataFrame to a long DataFrame, let us first visually see the difference between them. The following is an example of a DataFrame in wide form.

Figure 2: DataFrame in Wide Form.
Figure 2: DataFrame in Wide Form.

Now, the following image represents a DataFrame that contains the same data but in a long-form.

Figure 3: DataFrame in Long Form.
Figure 3: DataFrame in Long Form.

Before diving deeper into it, let us first create a wide DataFrame using pd.DataFrame().

--

--

Published in Towards AI

The leading AI community and content platform focused on making AI accessible to all. Check out our new course platform: https://academy.towardsai.net/courses/beginner-to-advanced-llm-dev

Written by Towards AI Editorial Team

The leading AI community & content platform making AI accessible to all. | 2.5k writers, 60k Discord, 500 k followers

Responses (1)

Write a response