pandas: Melt a wide table

Model DataFrame.melt, which turns one column per measurement into one row per measurement.

What to build

A program that melts a wide table into long rows.

Requirements

  • The first column is the id column; every other column is melted. Print id,variable,value (the header uses the id column's real name), then one row per id and melted column, column by column: all rows of the first melted column, then the second, and so on.
  • An empty cell gives the value NaN.

Input

Line 1: the header. Line 2: n. Then n rows.

Output

The header line, then n × (columns − 1) rows.

Constraints

1 ≤ n ≤ 50; 2 to 10 columns.

Example

Input:

name,maths,art
2
Ada,90,70
Mei,95,88

Output:

name,variable,value
Ada,maths,90
Mei,maths,95
Ada,art,70
Mei,art,88

Why it works

melt keeps the identifying column and turns each other column into rows that say which column the value came from, which is the long layout grouping and plotting expect.

Examples

Example 1 · Input
name,maths,art
2
Ada,90,70
Mei,95,88
Expected output
name,variable,value
Ada,maths,90
Mei,maths,95
Ada,art,70
Mei,art,88
Example 2 · Input
city,2023,2024
1
Dhaka,5,
Expected output
city,variable,value
Dhaka,2023,5
Dhaka,2024,NaN

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Loop over the value columns first, then over the rows, as melt does.

Hint 2

An empty cell stays a row, with the value NaN.

Solution

Show one correct solution (try it yourself first)
header = input().split(",")
n = int(input())
rows = [input().split(",") for _ in range(n)]
print(f"{header[0]},variable,value")
for j in range(1, len(header)):
    for row in rows:
        print(f"{row[0]},{header[j]},{row[j] if row[j] else 'NaN'}")

Lesson: Reshaping: pivot_table, melt and crosstab →