THINK FIRST·CODE LATER

← All labs

Verify what the chart computes

Problem

Input: a line valid_max M, then a CSV district,pm25.

Build an Altair bar chart with transforms: filter 0 ≤ pm25 ≤ M, aggregate mean_pm25 = mean(pm25) and readings = count() grouped by district, calculate over_guideline = datum.mean_pm25 > 15; encode x = district sorted by -y, y = mean_pm25, colour = over_guideline. Print each transform of the specification (transform: {...}).

Then recompute the same result independently with pandas and print one line per district, highest mean first: Lucheng: mean 42.0 from 2 readings, over guideline: True, and finally filtered out: 2 of 8 rows.

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.

v7-2-data-1.txt

valid_max 500
district,pm25
Lucheng,40
Lucheng,44
Lucheng,900
Ouhai,12
Ouhai,14
Longwan,20
Longwan,-3
Longwan,26
What your program must print for v7-2-data-1.txt
transform: {'filter': '((datum.pm25 >= 0) && (datum.pm25 <= 500.0))'}
transform: {'aggregate': [{'op': 'mean', 'field': 'pm25', 'as': 'mean_pm25'}, {'op': 'count', 'as': 'readings'}], 'groupby': ['district']}
transform: {'calculate': 'datum.mean_pm25 > 15', 'as': 'over_guideline'}
Lucheng: mean 42.0 from 2 readings, over guideline: True
Longwan: mean 23.0 from 2 readings, over guideline: True
Ouhai: mean 13.0 from 2 readings, over guideline: False
filtered out: 2 of 8 rows

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 < v7-2-data-1.txt

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

Get-Content v7-2-data-1.txt | 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("v7-2-data-1.txt", 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.