Reshape Data: Melt — LeetCode 2890 Python Solution

EasyPandas
Problem
#2890
Reading time
2 min

Table schema

SQL
DataFrame report +-------------+--------+ | Column Name | Type | +-------------+--------+ | product | object | | quarter_1 | int | | quarter_2 | int | | quarter_3 | int | | quarter_4 | int | +-------------+--------+ Write a solution to reshape the data so that each row represents sales data for a product in a specific quarter. The result format is in the following example.

Example

SQL
DataFrame report
+-------------+--------+
| Column Name | Type   |
+-------------+--------+
| product     | object |
| quarter_1   | int    |
| quarter_2   | int    |
| quarter_3   | int    |
| quarter_4   | int    |
+-------------+--------+

Python solution

Python
import pandas as pd


def meltTable(report: pd.DataFrame) -> pd.DataFrame:
    return pd.melt(report, id_vars=['product'], var_name='quarter', value_name='sales')

Complexity

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

Related problems

Frequently asked questions

How hard is LeetCode 2890. Reshape Data: Melt?
LeetCode 2890. Reshape Data: Melt is rated Easy on LeetCode.
What topics does LeetCode 2890. Reshape Data: Melt cover?
LeetCode 2890. Reshape Data: Melt 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