Functions in Python
Write reusable functions to clean, transform, and process data consistently
Functions let you package a block of code with a name and call it whenever needed. In data analysis, functions help you: apply the same cleaning logic to multiple columns, standardise transformations, and avoid copy-pasting the same code repeatedly.
A function takes inputs (parameters), does something, and returns an output. In pandas, you apply custom functions to columns with .apply() or .map().
Syntax
def function_name(parameter1, parameter2):
# code
return resultExamples
Key Points
- ✓def creates a function; return sends back the result
- ✓Parameters with defaults: def func(x, threshold=50) — threshold is optional
- ✓Lambda: lambda x: expression — for simple one-liners in apply() and sorted()
- ✓Docstrings: """description""" after def — document what the function does
- ✓In pandas: .apply(func) applies a function to every row/column element
Practice Question
What does this lambda return: (lambda x: x * 2 + 1)(5)?