Problem

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.

Examples

Example 1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
Input:
+--------------+----------+-------------+
| city         | month    | temperature |
+--------------+----------+-------------+
| Jacksonville | January  | 13          |
| Jacksonville | February | 23          |
| Jacksonville | March    | 38          |
| Jacksonville | April    | 5           |
| Jacksonville | May      | 34          |
| ElPaso       | January  | 20          |
| ElPaso       | February | 6           |
| ElPaso       | March    | 26          |
| ElPaso       | April    | 2           |
| ElPaso       | May      | 43          |
+--------------+----------+-------------+
Output:
+----------+--------+--------------+
| month    | ElPaso | Jacksonville |
+----------+--------+--------------+
| April    | 2      | 5            |
| February | 6      | 23           |
| January  | 20     | 13           |
| March    | 26     | 38           |
| May      | 43     | 34           |
+----------+--------+--------------+
Explanation: The table is pivoted, each column represents a city, and each row represents a specific month.

## Solution

### Method 1 - Pandas Pivot

#### Intuition
We want to pivot the DataFrame so that each city becomes a column and each month is a row, with temperature as the value.

#### Approach
Use pandas `pivot` to reshape the DataFrame, then reset the index and sort by month for a clean output.

#### Code

1
2
3
4
5
def pivot_weather(weather: pd.DataFrame) -> pd.DataFrame:
    result = weather.pivot(index='month', columns='city', values='temperature').reset_index()
    # Optional: sort by month for consistent output
    result = result.sort_values('month').reset_index(drop=True)
    return result
#### Complexity * โฐ Time complexity: `O(n)` โ€” where n is the number of rows in the DataFrame. * ๐Ÿงบ Space complexity: `O(n)` โ€” for the output DataFrame.