Getting and cleaning data · lesson 10 of 11
Parts in this lesson
Afrom src.cleaning import clean_salesyour own module, from src/
Braw.pipe(fix_stores, log).pipe(fix_dates, log)4.10: a chain of your own steps
Cif __name__ == "__main__":code that runs when the file is run

A cleaning pipeline

Last updated

Project 3.P cleaned one file with cells in a notebook. Next month there's another file, and the month after another. In this lesson you'll move the cleaning into functions in src/, chain them into a pipeline that reads raw files and writes clean ones with a log, and run the whole thing with one command.

By the end of this lesson you can

  • Turn notebook cells into small functions in a .py file
  • Chain the functions with pipe, counting what each one changes
  • Run the pipeline from the command line, from raw files to clean ones

From cells to functions

In project 3.P, each fix was a cell. That's right for working out the fixes, and wrong for running them every month: cells can be run out of order, skipped, or changed by accident, and a second notebook that needs the same cleaning would copy them.

So each fix becomes a function in src/cleaning.py, an ordinary Python file (Simple Python covers modules):

def fix_stores(sales, log):
    fixed = sales["store"].replace({"Lipa City": "Lipa"})
    log.append(("store names fixed", int((fixed != sales["store"]).sum())))
    return sales.assign(store=fixed)

Every function has the same shape:

  • it takes the table and the log, a list;
  • it counts how many rows it changes, and adds a line to the log;
  • it returns a new table, and never changes the one it was given (assign, lesson 4.10).

Small functions with one job each are easy to read, test and fix. When a new problem turns up, it gets a new function.

Raw in, clean out

Step through the pipeline, then run it on January's raw file from project 1.P. The page's project folder already has src/cleaning.py, with the six fixes and this function to chain them:

def clean_sales(raw):
    log = []
    sales = (
        raw.pipe(fix_stores, log)
           .pipe(fix_dates, log)
           .pipe(fix_prices, log)
           .pipe(fix_kilos, log)
           .pipe(drop_repeats, log)
           .pipe(drop_missing, log)
           .reset_index(drop=True)
    )
    return sales, log

It also has clean.py, which runs clean_sales on every raw sales file.

A cleaning pipeline. The raw file goes in at one end. It’s only ever read, never changed.data/raw/sales_2024-01.csvfix_stores()fix_dates()fix_prices()fix_kilos()drop_repeats()drop_missing()
1 of 3 The raw file goes in at one end. It’s only ever read, never changed.
pipeline.ipynb
  • clean_sales chains the six fixes with pipe, passing the log to each. 13 raw rows in, 11 clean rows out.
  • The log says what each step did: one store name, one date, 12 prices, one kilos value, one repeat and one missing row. That's the "What I changed" note from 3.P, written by the code itself, and always true.
  • clean.main() does it for every file matching data/raw/sales_*.csv, writing each clean file to data/clean/ under the same name. When February's file arrives, nothing changes but the folder.
  • The last cell checks the promise: the clean file has 11 rows, and the raw file is untouched.

Run clean.main() twice, and you get the same clean file twice. A pipeline you can rerun any time, with the same result, is what lets you delete everything in data/clean/ without worrying: it can always be made again.

Running it with one command

clean.py ends with:

if __name__ == "__main__":
    main()

__name__ is "__main__" only when the file is run, not when it's imported. So the notebook can import clean without it doing anything, and the terminal can run it. On your computer, from the project folder, with the environment active:

Terminal, in the tindahan folder
python clean.py
sales_2024-01.csv: 11 rows
  store names fixed: 1
  dates read as day/month/year: 1
  peso signs removed: 12
  kilos over 500 divided by 100: 1
  repeated rows dropped: 1
  rows with no kilos dropped: 1

Now cleaning is one command that anyone can run. Notebooks then only read from data/clean/, and never clean anything themselves. Write the command in the project's README.md, so a colleague (or you, next year) knows where clean data comes from.

The script runs from the project folder, so its paths start there. A notebook in notebooks/ that wants to import from src/ needs Python to look in the folder above first:

import sys
sys.path.insert(0, "..")
from src.cleaning import clean_sales

Wrong way: by hand in Excel, just this once

March's file arrives with three dates in a new format. The report is due today, so you open the raw file in Excel, retype the three dates, save it, and run the report.

What that costs:

  • The raw file is changed. Nobody can tell what it said, or check your three fixes.
  • The fix isn't in the pipeline, so April's file breaks the same way, and whoever cleans it doesn't know what you did.
  • Excel may have changed more than the dates. Saving a CSV in Excel can turn codes like 0012 into 12, long numbers into rounded ones, and other dates into its own format.
  • The report can't be rerun: deleting data/clean/ and running the pipeline now gives a different answer.

The fix takes ten minutes longer: a new format in fix_dates, a line in the log, a rule in validate() (lesson 5.9). "Just this once" is how nearly every unrepeatable analysis starts.

Check what you learned

Why does each cleaning function return a new table instead of changing the one it’s given?
What does if __name__ == "__main__": do in clean.py?
A raw file has a typo. Where should the fix go?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Data Analysis