Python

Pandas patterns I reach for every day

By Reetu Poudel · 4 December 2026 · 5 min read

Most pandas pain comes from writing it like a for-loop. A few patterns make it clean, fast and readable.

Pandas is the workhorse of data work in Python, and most of the frustration people have with it comes from fighting it — looping over rows, reassigning columns one at a time, losing track of what the data looks like three steps in. A few patterns fix almost all of that.

Chain, don't mutate

Instead of reassigning df over and over, I build a single readable pipeline with method chaining and .assign(). Each step is visible, the original frame is untouched, and there is no mystery about what happened when. A chain reads top to bottom like the steps you would describe out loud.

Vectorise instead of looping

If you find yourself writing for i in range(len(df)), stop. Pandas and NumPy operate on whole columns at once, in C, far faster than a Python loop. A conditional becomes np.where or a boolean mask; a per-row calculation becomes arithmetic on columns. The code shrinks and the runtime often drops by orders of magnitude.

groupby is your best friend

groupby with agg answers "what is the average per category" in one line. The pattern people miss is groupby(...).transform(...), which gives a result the same length as the original frame — perfect for things like "subtract each group's mean" without a clumsy merge.

Check types early, and often

Half of pandas bugs are silent type problems: a numeric column read as object, a date left as a string, a category stored as text. df.dtypes and df.info() take a second and save an hour. Parse dates on load, cast numbers explicitly, and use the category dtype for repeated labels to save memory.

Keep it legible

Clever one-liners feel good and read badly. I would rather have four named steps than one dense expression I cannot explain next week. Data code is read far more than it is written — optimise for the person who has to trust it later, which is usually you.

PythonPandasData Science
← All posts