Popular Searches

Build Comparable Hourly Observations

PythonBeginner
Practice Now

Introduction

A community exhibition needs a useful comparison of its opening slots. More visitors in total can simply mean more opportunities to record visitors. You will first compare two equally observed slots, then build a reusable analysis that preserves what was open, what was recorded, and what remains unknown.

This lab assumes Python basics, pandas reading, filtering and grouping, and Matplotlib bar charts. Python and the libraries are prepared for the Terminal and Results environment. All counts are synthetic; a row represents one hour, not a visitor identity. The time is an author estimate including reading and ordinary errors. You will create real CSV and PNG files, with every original input preserved.

Compare Two Equally Observed Slots

In this step, you will run a working total comparison, then change its calculation and chart to visitors per recorded hour. Open the Terminal Tab. Use Results for saved files: All files / Refresh reads current files, View opens an available file, and Download returns its original bytes. Missing files stay missing; the reader never runs analysis or redraws charts. Return to Terminal for commands. Opening or reconnecting Terminal does not recreate your workspace.

cd changes this terminal's working directory; pwd prints it. If a command later reports a missing file, return here and check spelling with ls.

cd /home/labex/project/opening-hours
pwd
/home/labex/project/opening-hours

cat prints a text file without changing it. Each row below is one recorded hour.

cat data/equal.csv
slot,visitors
morning,6
morning,10
evening,8
evening,12

Run the supplied small program. Setup has prepared its file, but has not run it or made your results.

python3 equal.py
         visitors
slot
evening        20
morning        16

In Results, refresh and view results/equal.png: the bars show 20 and 16, with the honest unit Total visitors. Return to Terminal. Morning has 16 visitors across two recorded hours: 16 / 2 = 8 visitors per hour. Evening has 20 / 2 = 10. Equal denominators make the two comparisons agree, but a rate needs its own calculation and unit.

Read the current source before editing:

cat equal.py

Follow main: it reads the CSV, calls compare, saves equal-summary.csv, asks chart_settings which column and unit to draw, then saves the PNG. The prepared imports and Agg backend save a figure without a separate window; the I/O and layout are already present. You will change only the comparison and its chart binding.

Make a backup first. cp SOURCE DESTINATION copies a file; the .bak suffix is just a backup filename. Do not copy over this backup after making a mistake.

cp equal.py equal.py.bak

nano edits an existing file in Terminal. The command-local LC_ALL=C.UTF-8 selects UTF-8 text handling for this editor only, without changing your shell or other programs. In nano, ^ in the shortcut strip means hold Ctrl. Arrow keys move the cursor; typing inserts text. Ctrl+W, a search phrase, then Enter finds a function. Home moves to the start of its current line. Ctrl+K cuts that entire line. Python function bodies use four spaces of indentation, not an unindented line.

LC_ALL=C.UTF-8 nano equal.py

First practice leaving an unwanted edit unsaved: press Ctrl+W, type def chart_settings, press Enter, and add a temporary character on that line. Press Ctrl+X, then N at the save question. You return to the shell without changing the file. Open it again with the same command:

LC_ALL=C.UTF-8 nano equal.py

Find def compare with Ctrl+W and Enter, then press Home. The supplied function has three lines: its def, the grouped total, and return summary. Cut those three lines with Ctrl+K three times. Insert the following function at that position, leaving the next function intact. agg names the result columns; size counts recorded rows, which here are hours. The division creates a rate for every slot rather than hardcoding 8 and 10.

def compare(data):
    summary = data.groupby('slot').agg(visitors=('visitors', 'sum'), hours=('visitors', 'size'))
    summary['rate'] = summary['visitors'] / summary['hours']
    return summary

Now find def chart_settings. Its two lines return the total column and its unit. Cut just those two lines and replace them with:

def chart_settings():
    return 'rate', 'Visitors per recorded hour'

The returned pair is unpacked by column, label in main: changing both makes the actual plotted data agree with the axis unit. Save with Ctrl+O, press Enter to confirm the unchanged filename, then Ctrl+X to exit. Saving is separate from running the program.

python3 equal.py
         visitors  hours  rate
slot
evening        20      2  10.0
morning        16      2   8.0

Leading whitespace and numeric formatting can vary. In Results, refresh and view both results/equal-summary.csv and results/equal.png. The bars now show 10 and 8, with slot ticks and the vertical label Visitors per recorded hour. Keep these units and actual values; colors, fonts, dimensions and ordering may differ. The chart must be deterministic: rerunning the current script with unchanged input reproduces its image pixels. Avoid random styles or timestamps; PNG metadata may differ.

Return to Terminal. This next filename error is intentional:

python3 missing.py

Python reports can't open file and No such file or directory; your work has not reset. Recover by finding the actual name and running it:

ls
python3 equal.py

For an editing error, read the filename and line number in Python's message. Reopen that file with nano, locate the named function with Ctrl+W, correct it, save, exit and rerun. A SyntaxError often means a missing colon or quote; an IndentationError points to inconsistent leading spaces. To abandon unsaved changes, use Ctrl+X, N. If necessary, cp equal.py.bak equal.py restores only this script, after which you must reapply the two edits above; it does not alter data or reset the environment.

Self-check: both slots use two recorded hours. Your calculation derives the denominators, and the plotted column and label describe the same rate. The initial totals-only program was useful, but did not satisfy this rate comparison.

Preserve Every Planned Hour

In this step, you will implement the function that matches counts to their planned hours. Continue in Terminal at /home/labex/project/opening-hours. Each plan row is one hour on one date in one slot. open=1 means planned open; open=0 means closed. The pair date and slot is a composite key: neither column alone identifies a row. Dates use YYYY-MM-DD; all dates here are valid calendar dates.

cat data/plan.csv
cat data/counts.csv

The count file is in a different order. A count of 0 is an observation of no visitors. An absent count for an open planned hour means missing recording, not zero visitors. Closed hours have no count row. Predict the outputs before editing: should quiet be observed or missing? Should unlogged have a numeric zero? Should closed contribute an observed hour?

Read the prepared program:

cat observe.py

read_inputs reads the two CSVs and validates complete, unique keys, open values and nonnegative counts. Every count must match an open planned key. .duplicated(keys) detects repeated pairs. validate='one_to_one' rejects duplicate relationships. Check key completeness before merging because pandas can match missing keys to each other. These validation checks reject invalid input rather than deduplicating or inventing counts.

main reads the two path arguments through sys.argv[1] and [2]. A Path joined with / builds a file path. mkdir(parents=True, exist_ok=True) prepares the output directory. The program calls build_hours, writes its returned table, then calls summarize. The latter currently returns None, meaning not implemented yet; main skips summary.csv until the next step. Neither function has a completed analysis hidden elsewhere.

A left merge keeps every row of its left table, the plan, and finds counts using both key columns regardless of row position. Missing matches get pandas' missing value, displayed as NaN. .loc[condition, column] assigns only matching rows; .eq(0) and .eq(1) compare each value. & combines elementwise conditions, and notna() distinguishes a recorded zero from missing. .astype(int) converts the observed condition to 1 or 0.

cp observe.py observe.py.bak
LC_ALL=C.UTF-8 nano observe.py

Use Ctrl+W to find def build_hours, press Enter, then Home. Cut its two lines (the header and raise NotImplementedError) with Ctrl+K twice. Insert this complete function, preserving read_inputs, summarize and main:

def build_hours(plan, counts):
    keys = ['date', 'slot']
    hours = plan.merge(counts, on=keys, how='left', validate='one_to_one')
    hours['status'] = 'missing'
    hours.loc[hours['open'].eq(0), 'status'] = 'closed'
    hours.loc[hours['open'].eq(1) & hours['visitors'].notna(), 'status'] = 'observed'
    hours['valid_hour'] = hours['status'].eq('observed').astype(int)
    return hours

The default is missing, the first mask marks closed hours, and the second marks open recorded hours, including real zero. return hours gives the table back to main; a function's local variable does not automatically become another function's variable. Save with Ctrl+O, Enter, then exit with Ctrl+X.

python3 observe.py data results
head -n 10 results/hours.csv

head -n 10 prints the header and first nine data rows. The CSV includes date,slot,open,visitors,status,valid_hour, sorted by the composite key. No slot summary is generated yet. In Results, refresh and view results/hours.csv. Compare with your prediction: quiet has numeric zeros, observed and valid_hour=1; unlogged has blank visitors, missing and 0; closed has blank visitors and closed. Blank means unknown or inapplicable according to status, never a guessed zero. Return to Terminal.

Self-check: every planned key appears once and every count stays attached to its date and slot. For a ValueError, read the invalid relationship and check your function against the untouched tables. Correct the function with nano and rerun; do not change inputs or rerun setup. The saved backup can restore this script only, but then you must reapply your function.

Calculate Rates and Recording Coverage

In this step, you will implement the remaining summary function without changing unknown counts into zeros. Continue in the same Terminal and workspace.

For evening, four hours were planned open and three recorded 12 visitors each. Total visitors are 36, observed hours are 3, rate is 36 / 3 = 12, and coverage is 3 / 4 = 0.75, or 75% of planned open hours recorded. Missing hours do not enter the rate denominator, but reduce coverage. morning has 40 visitors in four observed hours: its higher total has a lower rate, 10.

For quiet, four recorded zeros give total 0 and rate 0 with full coverage. For unlogged, no hour is observed: coverage is 0, but total and rate remain blank. For closed, planned open hours are 0, so both coverage and rate remain blank. Undefined values must not become zero-height rate bars later.

groupby('slot') groups complete hourly rows by stable slot identity. Named agg sums planned open hours and observed hours separately. sum(min_count=1) returns a missing total when all counts are missing, rather than the default empty sum of zero. replace(0, float('nan')) makes zero denominators missing before division, while preserving a real observed zero numerator. return summary supplies the result to the existing CSV-writing code.

Back up your working hourly program under a new name so the original backup remains available:

cp observe.py observe-hours.py.bak
LC_ALL=C.UTF-8 nano observe.py

Find def summarize, press Home, and cut only its two lines (def and return None). Insert the following function. You are replacing a function in the same file, not appending another program. Leave build_hours and main intact.

def summarize(hours):
    grouped = hours.groupby('slot')
    summary = grouped.agg(planned_hours=('open', 'sum'), observed_hours=('valid_hour', 'sum'))
    summary['visitors'] = grouped['visitors'].sum(min_count=1)
    summary['coverage'] = summary['observed_hours'] / summary['planned_hours'].replace(0, float('nan'))
    summary['rate'] = summary['visitors'] / summary['observed_hours'].replace(0, float('nan'))
    return summary

Save with Ctrl+O, Enter, and exit with Ctrl+X. The existing main now writes both tables; its index=False omits the hourly row number, while the summary saves its named slot index as the first CSV column.

python3 observe.py data results
cat results/summary.csv
slot,planned_hours,observed_hours,visitors,coverage,rate
afternoon,3,3,36.0,1.0,12.0
closed,0,0,,,
evening,4,3,36.0,0.75,12.0
morning,4,4,40.0,1.0,10.0
quiet,4,4,0.0,1.0,0.0
short,4,1,20.0,0.25,20.0
sparse,5,3,27.0,0.6,9.0
unlogged,4,0,,0.0,

Numeric formatting such as 36 versus 36.0 may vary. short has the highest observed rate but only one observed hour; sparse has three observations but coverage only 60%. Those are reasons to consider evidence before recommending a slot; this lab has not declared either a winner.

In Results, refresh and view results/summary.csv. Keep the original data/plan.csv, data/counts.csv, data/equal.csv, and your scripts. The reusable contract is python3 observe.py INPUT_DIRECTORY OUTPUT_DIRECTORY: it reads both source CSVs and writes both tables. Equivalent calculations and row ordering are allowed when every key and numeric relationship is retained. Return to Terminal.

If this edit breaks the hourly stage, cp observe-hours.py.bak observe.py restores that working stage only. Reopen observe.py, replace summarize correctly, save, exit and rerun. Do not repair a denominator by editing counts or adding zeros to missing hours.

Self-check: an unobserved slot and an observed empty slot have different totals, denominators and rates. The next independent lab supplies a complete observation program and adds the evidence rule.

Summary

You created an equal-opportunity chart, matched counts to complete composite keys, and produced hourly and slot-level CSV files. Closed hours, missing recordings and real zeros remain distinct. Rates use recorded open hours; coverage reveals how much of the planned opportunity was actually recorded.

Keep the reusable analysis and original data. These descriptive historical rates do not prove what would happen after extending opening hours. In the next independent environment, you will apply an explicit evidence rule before making a recommendation.