TutorialsPythonFunctions in Python

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 result

Examples

Writing and using functions in data work
# A simple cleaning function
def clean_salary(value):
    """Remove ₹ sign and commas, return as integer."""
    if isinstance(value, str):
        value = value.replace("₹", "").replace(",", "").strip()
        return int(value)
    return value

# Test it
clean_salary("₹75,000")   # 75000
clean_salary("₹1,20,000") # 120000

# Apply to a pandas column
# df["Salary"] = df["Salary"].apply(clean_salary)

# Function with default parameter
def classify_salary(amount, threshold=60000):
    return "Senior" if amount >= threshold else "Junior"

classify_salary(75000)          # "Senior"
classify_salary(45000)          # "Junior"
classify_salary(45000, 40000)   # "Senior" (custom threshold)
Lambda functions — for simple one-line operations
# Regular function
def double(x):
    return x * 2

# Same as lambda
double = lambda x: x * 2

# Lambda in pandas apply — common pattern
import pandas as pd
df = pd.DataFrame({"Score": [45, 78, 32, 91]})

df["Grade"] = df["Score"].apply(lambda x: "Pass" if x >= 50 else "Fail")
df["ScoreK"] = df["Score"].apply(lambda x: round(x / 100, 2))

# Sort a list of dicts by a key
employees = [{"name": "Rahul", "sal": 72000}, {"name": "Priya", "sal": 85000}]
sorted_emp = sorted(employees, key=lambda e: e["sal"], reverse=True)
💡 Lambda functions are for simple single-expression operations. For anything complex, use a regular def function.

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)?