pandas in depth · lesson 10 of 12
Parts in this lesson
A(df.query(...).assign(...).groupby(...))one step per line
Bassign(revenue=lambda d: d["kilos"] * d["price"])a column from the table so far
Cdf.pipe(my_function)your own step in a chain

Method chaining and apply

Last updated

As analyses grow, notebooks fill with names like df2, df_rice and df_final. Method chaining writes a whole analysis as one readable sequence of steps instead. In this lesson you'll write chains with query, assign and pipe, and learn when apply is fine and when it makes code a hundred times slower.

By the end of this lesson you can

  • Write an analysis as a method chain, one step per line
  • Use assign with a lambda, and pipe with your own function
  • Say when apply is slow, and replace it with column maths

A chain, step by step

Rice revenue by store, biggest first. Step through the chain, then run it.

A chain, one step at a time. A chain is a list of steps, each taking the table the step before made. It starts with the whole sales table.Batangasrice42Batangassugar12Liparice35Lipasugar10Tanauanrice29Tanauansugar8Batangasrice38Batangassugar11Liparice33Lipasugar9Tanauanrice30Tanauansugar7storeitemkilossales.query("item == 'rice'").assign(revenue=...).groupby("store")["revenue"].sum().sort_values(...)
1 of 4 A chain is a list of steps, each taking the table the step before made. It starts with the whole sales table.
chain.ipynb
  • The whole chain is inside round brackets, so Python lets it run over several lines. Each line starts with a dot and does one thing, and reads like a recipe.
  • assign(revenue=lambda d: ...): in a chain there's no name for "the table so far", so you give assign a small function. d is the table at that point, after the query.
  • as_index=False keeps store a column (lesson 4.5).
  • pipe(add_revenue), in the second cell, puts your own function into a chain. Name a step that's more than one line, test it on its own, and pipe it in.

To see what a chain does, comment out its last lines (put # in front) and run it: you get the table at that step. Chains have no in-between names to keep track of, and nothing in memory goes stale.

Wrong way: apply, one row at a time

apply with axis=1 runs a Python function on each row. It's easy to write, and it works. Run the cells, and compare the timings.

apply.ipynb

Both ways give the same answers (True). But the apply line is timed on only 10,000 rows, and the column maths on all 100,000, and apply is still far slower. Per row, it's usually 100 times slower or worse. On a million rows that's the difference between a moment and several minutes.

The reason is lesson 2.1's race. apply hands each row to Python as a small Series, one at a time. big["kilos"] * big["price"] hands both whole columns to NumPy's C code at once.

So: if the function is arithmetic, comparisons or np.where, write it as column maths. Use str and dt for text and dates. Keep apply for small tables, or for something with no column version, and time it with %timeit if the table is big.

Check what you learned

In .assign(vat=lambda d: d["revenue"] * 0.12), what is d?
Which is fastest on a million rows?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Data Analysis