14.2: A Word of Caution
- Page ID
- 39293
But before we embark, a cautionary note. Some of the things that loops can do – especially the early examples – can also be done using the queries of the last chapter. For instance, we could use a query to find all the strings in a Series that begin with the letter T, or we could use a loop to do the same thing.
Here’s the rule: if you can do it without a loop, that is always preferred. There are two reasons for this. First, it’s less code to write, and less error-prone, to use Pandas’ built-in features rather than crafting a loop yourself. That’s why they created those features (like queries) after all.
Second, and ultimately even more important, using a Pandas function is much faster to execute than a loop. The reason has to do with how a loop is eventually broken down into the little instructions a machine can understand: when Python runs a loop, it plods through the steps methodically, whereas the Pandas functions are all pre-baked into a water-cooled rocket engine that can jet out of the gate.
You don’t need to know any of those nitty-gritty details. All you have to remember is: don’t ever resort to using a loop unless you can’t figure out how to do what you want without one. (And unfortunately, there are indeed those times.)