2889 Reshape Data: Pivot
Last updated
Last updated
DataFrame weather
Column Name | Type |
---|---|
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.
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.
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 argument weather
, which is a DataFrame containing weather data.
Pivoting the Data
We use the pivot
method on the DataFrame weather
to pivot the data based on the month
column.
The index='month'
argument specifies that the month
column should be used as the index of the resulting DataFrame.
The columns='city'
argument specifies that the city
column should be used to create separate columns for each city.
The values='temperature'
argument specifies that the temperature
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.
city
object
month
object
temperature
int