EasyNo. 2889

Reshape Data: Pivot — LeetCode 2889 Python Solution

Topics
Pandas
Reading time
2 min

Table schema

SQLTable schema
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

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

Python solution

PythonSolution
import pandas as pd


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

Complexity

Time
O(n)
Space · auxiliary
O(1) to O(n)

Related problems

Related problems
No.ProblemDifficulty
2877Create a DataFrame from ListEasy
0057Insert IntervalMedium
0192Word FrequencyMedium
0193Valid Phone NumbersEasy
0194Transpose FileMedium
0195Tenth LineEasy

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.

Free to download. Check it runs on your machine, then pick a plan.