Pandas DataFrame melt() Method

Rate this post

Preparation

Before any data manipulation can occur, two (2) new libraries will require installation.

  • The Pandas library enables access to/from a DataFrame.
  • The Xarray library works with labeled multi-dimensional arrays and advanced analytics.

To install these libraries, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.

$ pip install pandas

Hit the <Enter> key on the keyboard to start the installation process.

$ pip install xarray

Hit the <Enter> key on the keyboard to start the installation process.

If the installations were successful, a message displays in the terminal indicating the same.


Feel free to view the PyCharm installation guide for the required library.


Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

import pandas as pd
import xarray

DataFrame melt()

The melt() method unpivots a DataFrame/Series from the standard wide (horizontal) format to long (vertical).

httpv://www.youtube.com/watch?v=embed/DCqWZ0DGVqw

The syntax for this method is as follows:

DataFrame.melt(id_vars=None, value_vars=None, var_name=None, 
               value_name='value', col_level=None, ignore_index=True)
ParameterDescription
id_varsThis parameter is the column(s) to use for the identifier vars. Allowed dtypes are: tuple, list, or ndarray.
value_varsThe column(s) name(s) to unpivot. If empty, use all columns. Allowed dtypes are: tuple, list, or ndarray.
var_nameThe name(s) for the variable column(s).
value_nameThe name(s) for the value column(s).
col_levelIf MultiIndex, use this parameter to melt.
ignore_indexIf True, ignore the original index. If False, use the original index.

For this example, four (4) students enroll in coding classes. The output will display in various formats using the melt() method.

Code – Example 1

df = pd.DataFrame({'Enrolled': {0: '01/01/2021', 1: '01/02/2021',  2: '01/29/2021', 3: '01/13/2021'},
                   'Student':  {0: 'Micah',      1: 'Philip',   2: 'Jonas',         3: 'Sarah'},
                   'Class':    {0: 'Python',     1: 'PHP',     2: 'JavaScript', 3: 'Java'},
                   'Grade':    {0: 65, 1: 76, 2: 55, 3: 81}})
print(df)

result = pd.melt(df, id_vars =['Student'], value_vars =['Class', 'Grade'])
print(result)
  • Line [1] creates a DataFrame from a dictionary containing student details and saves it to df.
  • Line [2] outputs the DataFrame to the terminal.
  • Line [3] sets the id_vars to Student and the value_vars to Class and Grade. The output saves to result.
  • Line [4] outputs the result to the terminal.

Output

df

 EnrolledStudentClassGrade
001/01/2021Micah     Python    65
101/02/2021 Philip        PHP    76
201/29/2021  Jonas JavaScript    55
301/13/2021  Sarah       Java    81

result

 Studentvariablevalue
0Micah     Class    Python
1Philip        Class    PHP
2Jonas Class    JavaScript
3Sarah       Class    Java
4Micah     Grade    65
5Philip        Grade    76
6Jonas Grade    55
7Sarah       Grade    81

💡 Note: From the code on line [3] and the result, the melt() method unpivots the DataFrame around the Student column (id_vars =['Student']).

For this example, the column labels (shown above) will update. Previously the default column labels were named variable and value (see example 1).

Below the column labels change.

Code – Example 2

df = pd.DataFrame({'Enrolled': {0: '01/01/2021', 1: '01/02/2021',  2: '01/29/2021', 3: '01/13/2021'},
                   'Student':  {0: 'Micah',      1: 'Philip',   2: 'Jonas',         3: 'Sarah'},
                   'Class':    {0: 'Python',     1: 'PHP',     2: 'JavaScript', 3: 'Java'},
                   'Grade':    {0: 65, 1: 76, 2: 55, 3: 81}})

result = pd.melt(df, id_vars =['Student'], value_vars =['Class', 'Grade'],
                 var_name ='All-Students', value_name ='All-Grades')
print(result)
  • Line [1] creates a DataFrame from a dictionary containing student details and saves it to df.
  • Line [2] sets the id_vars to Student and the value_vars to Class and Grade. This line also changes the default names variable and value to All-Students and All-Grades. The output saves to result.
  • Line [3] outputs the result to the terminal.

result

 StudentAll StudentsAll Grades
0Micah     Class    Python
1Philip        Class    PHP
2Jonas Class    JavaScript
3Sarah       Class    Java
 Micah     Grade    65
5Philip        Grade    76
6Jonas Grade    55
7Sarah       Grade    81

More Pandas DataFrame Methods

Feel free to learn more about the previous and next pandas DataFrame methods (alphabetically) here:

Also, check out the full cheat sheet overview of all Pandas DataFrame methods.