#2889

Reshape Data: Pivot

Easy
Hash MapDataFrame Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using the built-in pivot functionality in pandas allows us to efficiently transform the DataFrame without manual iteration. This is faster and cleaner.

⚙️

Algorithm

4 steps
  1. 1Step 1: Use the pivot_table function from pandas.
  2. 2Step 2: Set 'month' as the index, 'city' as the columns, and 'temperature' as the values.
  3. 3Step 3: Fill any missing values with NaN or a specified value.
  4. 4Step 4: Reset the index to get a clean DataFrame.
solution.py4 lines
1import pandas as pd
2
3def pivot_weather(df):
4    return df.pivot_table(index='month', columns='city', values='temperature', aggfunc='first').reset_index()

Complexity note: The time complexity is O(n) because we are processing each entry in the DataFrame only once, making it efficient. The space complexity is O(n) due to the storage of the pivoted DataFrame.

  • 1Using built-in functions can significantly reduce complexity and improve readability.
  • 2Understanding how to manipulate DataFrames is crucial for data analysis tasks.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.