Reshape Data: Pivot - Problem

You have a DataFrame weather with the following structure:

Column NameType
cityobject
monthobject
temperatureint

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 should transform data from a long format (multiple rows per month) to a wide format (one row per month with cities as columns).

Input & Output

Example 1 — Basic Weather Data
$ Input: weather_data = [["New York", "January", 25], ["Los Angeles", "January", 75], ["New York", "February", 30], ["Los Angeles", "February", 80]]
Output: [["month", "Los Angeles", "New York"], ["February", 80, 30], ["January", 75, 25]]
💡 Note: Transform from long format (city-month-temp rows) to wide format where months become rows and cities become columns. Cities are sorted alphabetically.
Example 2 — Missing Data
$ Input: weather_data = [["Miami", "March", 85], ["Seattle", "April", 55], ["Miami", "April", 88]]
Output: [["month", "Miami", "Seattle"], ["April", 88, 55], ["March", 85, null]]
💡 Note: When a city has no temperature data for a specific month, the pivot table shows null for that cell (Seattle has no March data).
Example 3 — Single Record
$ Input: weather_data = [["Chicago", "December", 15]]
Output: [["month", "Chicago"], ["December", 15]]
💡 Note: Even with minimal data, the pivot structure is maintained with proper headers and single data row.

Constraints

  • 1 ≤ weather_data.length ≤ 1000
  • weather_data[i].length = 3
  • weather_data[i] = [city, month, temperature]
  • All city and month names are non-empty strings
  • All temperatures are integers

Visualization

Tap to expand
Weather Data Pivot: Long Format → Wide FormatInput: Long FormatCity Month TempNYC Jan 25LA Jan 75NYC Feb 30LA Feb 804 rows × 3 columnsPIVOTOutput: Wide FormatmonthLANYCFeb8030Jan75253 rows × 3 columnsKey Benefits:• Easy comparison across cities• Better for analysis and visualization• Structured table format• Months become row indices• Cities become column headers• Handles missing data gracefully
Understanding the Visualization
1
Input Data
Weather records in long format: [city, month, temperature]
2
Pivot Transform
Reshape data with months as rows and cities as columns
3
Output Table
Structured table format with proper headers
Key Takeaway
🎯 Key Insight: Pivoting transforms analytical perspective by making cities comparable across months in a structured table format
Asked in
Meta 15 Google 12 Microsoft 10 Amazon 8
23.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen