EasyNo. 2890

Reshape Data: Melt — LeetCode 2890 Python Solution

Topics
Pandas
Reading time
2 min

Table schema

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

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

Python solution

PythonSolution
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

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 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.

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