0PricingLogin
Pandas & NumPy Academy · Lesson

apply() on Columns and Rows

Use DataFrame.apply() with axis=0 and axis=1 to run a custom function over each column or each row.

When to Use apply()

DataFrame.apply() runs a custom Python function over each column (axis=0) or each row (axis=1). It is the tool of last resort — slower than built-in vectorised operations — but essential when a computation cannot be expressed with NumPy arithmetic, boolean indexing, or built-in aggregation functions. Use it when you need complex conditional logic, custom string parsing, or multi-step calculations that operate on a single row or column at a time.

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'price': [10.5, 25.0, 8.3, 100.0],
    'quantity': [3, 1, 5, 2],
    'tax_rate': [0.05, 0.10, 0.05, 0.15]
})
print(df)

apply() Along Columns (axis=0)

With axis=0 (the default), apply() passes each column as a Series to the function. The function receives one column at a time and should return a scalar (for aggregation) or a Series (for transformation). This is useful for applying a custom normalisation or cleaning step uniformly to all numeric columns in one call.

# Custom range normalisation (0 to 1) for each column
def min_max_scale(col):
    return (col - col.min()) / (col.max() - col.min())

df_scaled = df[['price', 'quantity']].apply(min_max_scale, axis=0)
print(df_scaled)

All lessons in this course

  1. apply() on Columns and Rows
  2. apply() with GroupBy
  3. map() and applymap() for Element-Wise Operations
  4. Method Chaining with pipe()
← Back to Pandas & NumPy Academy