Skip to content

Python Essentials for ML

Functions & Lambdas

8 min+70 XPStep 1/10

`def` is a reusable cleaning step

Every data pipeline is the same handful of transformations applied over and over. A function packages one:

  • def standardize(x, mean, std):
  • return (x - mean) / std

Call it like standardize(77, 50, 10) → 2.7. Parameters can carry defaults — def load(path, sep=',') — so load('a.csv') works while load('b.csv', sep=';') handles the weird file.

The rule of data work: the second time you copy-paste a cleaning step, make it a function. The third bug always hides in the copy you forgot to update.

insight

Well-named functions are self-documenting pipelines. `df['price'].apply(parse_price)` reads like intent; five lines of inline string surgery reads like a riddle.