~/learn/Pandas · GroupBy & aggregation

Pipelines with assign and pipe

Chain transformations into readable steps.

8 min readlesson 4 of 13assignpipemap

why this matters

Long analyses turn into a pile of intermediate variables. Chaining keeps each step named, readable and easy to reorder.

assign adds or replaces columns and returns a new frame, so several steps chain together without intermediate variables or chained-assignment warnings.

python · editable
loading editor…

Try it: Add a column flagging rows above the mean revenue.

map applies a lookup to a Series and apply applies a function to a column — both fine on a single column; it is apply(axis=1) across rows that is slow.

python · editable
loading editor…

pipe drops a whole function into the chain, which keeps reusable cleaning steps out of the pipeline body.

python · editable
loading editor…

A readable pipeline

(df
  .query("units > 2")
  .assign(revenue=lambda d: d.units * d.price)
  .sort_values("revenue", ascending=False))

Pro tip

Inside assign, use lambda d: … so each step sees the frame as it exists at that point in the chain.

key takeaways

  • assign adds columns without mutating the original.
  • query filters with a readable expression.
  • pipe inserts your own function into a chain.

check your understanding

Why use a lambda inside assign?

free practice

Build confidence with a question you can solve without Pro.