2889 Reshape Data: Pivot
Problem Statement
DataFrame weather
city
object
month
object
temperature
int
Write a solution to pivot the data so that each row represents temperatures for a specific month, and each city is a separate column.
The result format is in the following example.
For the whole problem statement, please refer here.
Plans
Use pandas to handle the data.
Pivot the data based on the
month
column.Provide the pivoted DataFrame with each city as a separate column.
The resulting DataFrame should have the
month
as the index.
Solution
Explanation
Import Pandas
We start by importing the Pandas library, which provides data structures and operations for manipulating numerical tables and time series.
Define the Function
We define a function
pivotTable
that takes a single argumentweather
, which is a DataFrame containing weather data.
Pivoting the Data
We use the
pivot
method on the DataFrameweather
to pivot the data based on themonth
column.The
index='month'
argument specifies that themonth
column should be used as the index of the resulting DataFrame.The
columns='city'
argument specifies that thecity
column should be used to create separate columns for each city.The
values='temperature'
argument specifies that thetemperature
column should be used to fill the values in the pivoted DataFrame.
Return the Result
We return the pivoted DataFrame with each city as a separate column and the
month
as the index.
Last updated