Reshape Data: Pivot — LeetCode 2889 Python Solution

EasyPandas
Problem
#2889
Reading time
2 min

Table schema

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

Example

SQL
DataFrame weather
+-------------+--------+
| Column Name | Type   |
+-------------+--------+
| city        | object |
| month       | object |
| temperature | int    |
+-------------+--------+

Python solution

Python
import pandas as pd


def pivotTable(weather: pd.DataFrame) -> pd.DataFrame:
    return weather.pivot(index='month', columns='city', values='temperature')

Complexity

MeasureComplexity
TimeO(n)
SpaceO(1) to O(n) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 2889. Reshape Data: Pivot?
LeetCode 2889. Reshape Data: Pivot is rated Easy on LeetCode.
What topics does LeetCode 2889. Reshape Data: Pivot cover?
LeetCode 2889. Reshape Data: Pivot is tagged Pandas on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview