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
assignwith alambda, andpipewith your own function - Say when
applyis 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.
- 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 giveassigna small function.dis the table at that point, after thequery.as_index=Falsekeepsstorea 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.
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
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.
- pandas: pandas.DataFrame.pipe: your own functions in a chain
- pandas: pandas.DataFrame.assign: callables that receive the table so far
- pandas: Enhancing performance: why row-by-row apply is slow