Functions and Lambdas for Data Work
Every week the bookshop wants the same numbers: revenue per sale, with a discount on big orders. You could retype the arithmetic each time, or name it once and reuse it everywhere. In data work, that named recipe is a function, and short throwaway recipes are lambdas.
The rule
Name a recipe you repeat; use a lambda for a one-line recipe you pass along.
A function takes inputs, does work, and returns a result:
def revenue(copies, price, discount=0.0):
return copies * price * (1 - discount)
revenue(3, 250) # 750.0
revenue(5, 400, discount=0.1) # 1800.0discount=0.0 is a default: callers may leave it out. Passing it by name, discount=0.1, is a keyword argument, and it makes calls easier to read.
Sometimes you do not know how many inputs will arrive:
def total(*amounts, **options):
result = sum(amounts)
if options.get("round_to"):
result = round(result, options["round_to"])
return result
total(750, 2000, 800) # 3550*amounts gathers extra positional values into a tuple; **options gathers extra keyword values into a dict. The names args and kwargs are only a habit; the stars do the work.
A lambda is a function with no name and a single expression, written where it is used:
by_price = sorted(books, key=lambda b: b["price"])You will pass lambdas constantly in pandas, for example to sort or transform values.