Reshaping Pandas Dataframe using pivot and melt functions

dataframe_pivot_melt

Skill - Reshaping Pandas Dataframe using pivot and melt functions

Table of Contents

Skills Required

Please make sure to have all the skills mentioned above to understand and execute the code mentioned below. Go through the above skills if necessary for reference or revision


Pandas is a python library.
DataFrame is a data structure provided by the pandas library.

Please go through Pandas DataFrame Basics to learn the basics of pandas DataFrame.

In this post, we will learn how to reshape a pandas DataFrame using pivot and melt functions


Dataframe pivot function is similar to the pivot in Excel Tables

Excel files used in this post

pivot_melt_illustration

  • Using pivot function, we can convert column data into header.
  • Using melt function, we can convert header data into a column data.

pivot example

import  pandas  as  pd
import  datetime  as  dt

df = pd.read_excel('pivot_data_1.xlsx')
print(df)

df1 = df.pivot(index="name", columns="date", values="sales")
print(df1)
  • Pivot function will throw error if the combination of index and attribute columns have duplicate values. If the values column values are all numeric values, then pivot_table can pivot the dataframe along with aggregating the values with duplicate index-attribute values

melt example

import  pandas  as  pd
import  datetime  as  dt

df = pd.read_excel('melt_data_1.xlsx')
print(df)

df1 = df.melt(id_vars=["name"])
print(df1)

Video

Video for this post can be found here


Online Interpreter

Although we recommend to practice the above examples in Visual Studio Code, you can run these examples online at https://www.tutorialspoint.com/execute_python_online.php

References


Table of Contents

Comments