River Gauge Clean-Up

Data with PythonHard+10 XP+10

River Gauge Clean-Up

Volunteers read river-level gauges and upload their readings as a CSV file with two columns, station and level_cm. The uploads are messy:

  • station names are typed with odd capitals and stray spaces, so " north" and "NORTH" are the same station
  • the same reading is sometimes uploaded twice, and the copies only match once the names are tidied
  • a few levels are typed as words, like err or dry

Task: write gauge_report(path). The starter code includes write_text(path, text), which saves CSV text to a file and returns its path. Each test passes that path straight to gauge_report. Load the file at path with pandas, then clean it in this order:

  1. Tidy the names. Strip spaces from both ends of every station, then put it in title case.
  2. Drop repeats. Remove rows that are exact copies of an earlier row (after tidying), keeping the first.
  3. Fix the levels. Convert level_cm to numbers. Anything that can't be read becomes missing.
  4. Drop the gaps. Remove rows whose level is missing.
  5. Flag outliers. Using the levels that are left, find the 1.5 × IQR fences with pandas quantile(0.25) and quantile(0.75). A level is an outlier if it's strictly outside a fence.

Return a dictionary:

  • "rows": how many rows are left after step 4, as a whole number
  • "stations": the different stations left after step 4, in the order they first appear
  • "outliers": a list of [station, level] pairs for every outlier, in row order, with each level as a number. [] if there are none.

At least one level in every file can be read, and every file has at least one level that is not a whole number, so the column always reads as text or decimals.

Examples

path = write_text("gauge_a.csv", "station,level_cm\nNorth,41.5\n north,41.5\nSouth,38.0\nSOUTH,err\nEast,40.2\nNorth,39.8\nEast,96.0\nSouth,42.1\n")
returns {'rows': 6, 'stations': ['North', 'South', 'East'], 'outliers': [['East', 96.0]]}
path = write_text("gauge_b.csv", "station,level_cm\nWeir,20.5\nweir ,21.0\nMill,19.5\nMill,dry\n")
returns {'rows': 3, 'stations': ['Weir', 'Mill'], 'outliers': []}

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run