2889 Reshape Data: Pivot

Problem Statement

DataFrame weather

Column Name
Type

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

import pandas as pd

def pivotTable(weather: pd.DataFrame) -> pd.DataFrame:
    # Pivot the table to have the temperature of each city in each month
    return weather.pivot(index='month', columns='city', values='temperature')

Explanation

  1. Import Pandas

    • We start by importing the Pandas library, which provides data structures and operations for manipulating numerical tables and time series.

  2. Define the Function

    • We define a function pivotTable that takes a single argument weather, which is a DataFrame containing weather data.

  3. 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.

  4. Return the Result

    • We return the pivoted DataFrame with each city as a separate column and the month as the index.

Last updated