THINK FIRST·CODE LATER

← All labs

Wide to long and back: melt and pivot

Problem

Read a wide CSV from standard input: the first column identifies the unit (e.g., building), the other columns are periods (e.g., Jan,Feb,Mar) holding energy values (some may be empty).

  1. Convert it to long format with columns <first column>, month, kwh, dropping missing values. Print wide: 3 rows x 4 columns -> long: 8 rows x 3 columns and the first 3 rows (to_string(index=False)).
  2. Print the total per unit, largest first: total per building: Lab 1205, Library 900, Gym 320 (numbers in :g format).
  3. Print the largest single value: largest value: Lab in Feb (410).
  4. Pivot back to wide and print round trip cells: 8 (non-missing cells).

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

v2-2-data-1.csv

building,Jan,Feb,Mar
Library,320,300,280
Gym,150,170,
Lab,400,410,395
What your program must print for v2-2-data-1.csv
wide: 3 rows x 4 columns -> long: 8 rows x 3 columns
building month   kwh
 Library   Jan 320.0
     Gym   Jan 150.0
     Lab   Jan 400.0
total per building: Lab 1205, Library 900, Gym 320
largest value: Lab in Feb (410)
round trip cells: 8

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), in the folder that holds both files:

python my_lab.py < v2-2-data-1.csv

Windows PowerShell (the default terminal of VS Code on Windows) does not understand <:

Get-Content v2-2-data-1.csv | python my_lab.py

PyCharm: Run → Edit Configurations → tick Redirect input from and choose the file.

Jupyter: put this at the top of the cell that holds your program:

import sys
sys.stdin = open("v2-2-data-1.csv", encoding="utf-8")

Write it here, in Jupyter or in your IDE, then paste it. Run it on the sample input yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.