Skill - Reshaping Pandas Dataframe using pivot and melt functions
Skills Required
- Setup python development environment
- Basic Printing in Python
- Commenting in Python
- Managing Variables in python
- Pandas DataFrame Basics
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
- Excel files used in this post can be found at
- 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
- pivot - https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.html
- melt - https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.melt.html#pandas.DataFrame.melt
- pivot_table - https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html
Comments
Post a Comment