/W05
实验Lab: Clean a real sensor log
- Dataset
- UCI Air Quality (9,357 hourly rows, CC BY 4.0)
- Time
- 3 hours
This week you'll be able to
- Load, reshape, and summarise a dataset with pandas, using vectorised operations.
- Find and handle missing values, sentinel codes, duplicates, and wrong types, and justify each choice.
- Build a cleaning step that can run again on new data without hand edits.
Goal
Clean a messy real dataset into a tidy, typed, validated table. Write the cleaning so it runs again on new data without hand edits.
Data
A year of hourly readings from a gas sensor array in an Italian city, 2004 to 2005. Missing readings are coded as -200.
import pandas as pd
raw = pd.read_csv("https://archive.ics.uci.edu/static/public/360/data.csv")
raw.info()Tasks
- Profile the raw table: shape, types, value ranges. What type are
DateandTime? What's wrong with the numeric minimums? - Replace the
-200sentinel with a proper missing value. Count missing values per column. One column is about 90% missing. Decide whether to keep it and say why. - Combine
DateandTimeinto one datetime column (Procedure 7.2). Check the format first: is3/10/2004the 3rd of October or the 10th of March? - Some rows are missing every sensor reading at once. Find them. Are they random, or blocks of time? Plot the missing pattern (Procedure 9.2).
- Check for duplicates (Procedure 7.1) and for impossible values, such as negative concentrations or relative humidity over 100%.
- Impute the remaining gaps (Procedure 7.5). Compare two methods: forward-fill and time-based interpolation. Which is safer for hourly sensor data, and why?
- Write a
clean(raw) -> DataFramefunction that does all of the above. Add checks at the end that fail loudly if a rule is broken (Procedure 7.6).
Deliverable
A notebook ending in a clean() function and its checks, and a short cleaning log: each decision, and why.
Done when
clean(raw)runs from the raw download with no manual steps.- The output has a datetime index, numeric columns, and no
-200values. - The checks pass on the clean output and fail if you put a
-200back.
Stretch
Wrap the numeric cleaning steps in a scikit-learn Pipeline with a ColumnTransformer (Procedure 7.7).