How do you create a new Pandas DataFrame column by applying a function across multiple columns row-wise? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you create a new Pandas DataFrame column by applying a function across multiple columns row-wise?

message-square
0

Use vectorized column arithmetic (df["col_a"] + df["col_b"]), np.where() / np.select() for conditional logic, or df.assign(...) for method chaining whenever possible—falling back to df.apply(func, axis=1) (or zip(df["a"], df["b"]) list comprehension) only when your custom function requires complex Python objects, external API calls, or branching logic that cannot be vectorized.

Basic Example

import numpy as np
import pandas as pd

df = pd.DataFrame({
    "price": [100.0, 250.0, 80.0],
    "qty": [2, 1, 5],
    "discount": [0.10, 0.0, 0.25],
})

# 1. Recommended (vectorized arithmetic — 100x+ faster than apply):
df["total"] = df["price"] * df["qty"] * (1.0 - df["discount"])

# 2. Recommended for conditional multi-column rules (np.where / np.select):
df["tier"] = np.where(df["total"] >= 200, "VIP", "Standard")

# 3. Fallback when custom non-vectorizable Python logic is genuinely required (`axis=1`):
def format_summary(row: pd.Series) -> str:
    return f"{int(row['qty'])}x @ ${row['price']:.2f} -> ${row['total']:.2f} ({row['tier']})"

df["summary"] = df.apply(format_summary, axis=1)
print(df[["total", "tier", "summary"]])
#    total      tier                       summary
# 0  180.0  Standard  2x @ $100.00 -> $180.00 (Standard)
# 1  250.0       VIP  1x @ $250.00 -> $250.00 (VIP)
# 2  300.0       VIP  5x @ $80.00 -> $300.00 (VIP)

Key Details & Edge Cases

  • Never forget axis=1 inside df.apply(func, axis=1):
    • df.apply(func) defaults to axis=0 (passing each column as a Series), which immediately raises KeyError: 'price' when your function indexes row["price"]. Always specify axis=1 to iterate across rows.
  • Why df.apply(..., axis=1) is slow (and how zip(...) beats it on Python logic):
    • df.apply(func, axis=1) constructs a brand-new pd.Series object for every single row in Python, adding massive per-row overhead on DataFrames over 10,000 rows.
    • When your function cannot be vectorized with NumPy/Pandas operators, iterating over zip(df["price"], df["qty"]) inside a list comprehension runs 5–15× faster than df.apply(..., axis=1):
      df["summary"] = [f"{q}x @ ${p:.2f}" for p, q in zip(df["price"], df["qty"])]
      
  • Returning multiple new columns from a single apply(..., axis=1) call (result_type="expand"):
    • If your row function returns a tuple or list of values, pass result_type="expand" to unpack them directly into multiple target columns:
      df[["net", "tax"]] = df.apply(
          lambda r: (r["total"] * 0.85, r["total"] * 0.15),
          axis=1,
          result_type="expand",
      )
      
  • Avoid SettingWithCopyWarning when assigning to a filtered DataFrame:
    • If df came from a slice (sub = df[df["qty"] > 1]), call .copy() first (sub = df[df["qty"] > 1].copy()) or use df.assign(total=lambda d: d["price"] * d["qty"]) to return a clean DataFrame without mutating in place.
  • Silent dtype upcasting trap inside row (pd.Series) during axis=1:
    • Because df.apply(..., axis=1) packs an entire row into a single 1D Series, mixing int and float columns in the same DataFrame coerces row["qty"] to float (2.0 instead of 2) inside your callback! Cast explicitly (int(row["qty"])) or use zip(...) to preserve native column dtypes.

Comparison of Multi-Column Row Computation Methods in Pandas

Approach Syntax Example Speed (100k Rows) Preserves Column Dtypes? Best Used When
Vectorized Pandas / NumPy (Best) df["c"] = df["a"] * df["b"] ~1 ms (C/SIMD speed) Yes Arithmetic, string .str ops, .dt date math, and np.where() / np.select() conditions.
df.assign(...) df = df.assign(c=lambda d: d["a"] + d["b"]) ~1 ms (vectorized) Yes Functional method chains (.query(...).assign(...).sort_values(...)) without intermediate variables.
zip() List Comprehension df["c"] = [f(a, b) for a, b in zip(df["a"], df["b"])] ~25 ms (fast Python loop) Yes (exact per-column types) Calling custom Python functions, regex/parsers, or external libraries across 2–4 columns.
df.apply(fn, axis=1) df["c"] = df.apply(fn, axis=1) ~400 ms (builds Series per row) No (coerces row to common dtype) Small DataFrames (<10k rows) where a row function dynamically inspects many columns by name.