Generally, iterrows should only be used in very, very specific cases. This is the general order of precedence for performance of various operations:
- vectorization
- using a custom Cython routine
- apply
- reductions that can be performed in Cython
- iteration in Python space
- itertuples
- iterrows
- updating an empty frame (e.g., using loc one-row-at-a-time)
Using a custom Cython routine is usually too complicated, so let’s skip that for now.
-
Vectorization is always, always the first and best choice. However, there is a small set of cases (usually involving a recurrence) which cannot be vectorized in obvious ways. Furthermore, on a smallish
DataFrame, it may be faster to use other methods. -
applyusually can be handled by an iterator in Cython space. This is handled internally by pandas, though it depends on what is going on inside theapplyexpression. For example,df.apply(lambda x: np.sum(x))will be executed pretty swiftly, though of course,df.sum(1)is even better. However something likedf.apply(lambda x: x['b'] + 1)will be executed in Python space, and consequently is much slower. -
itertuplesdoes not box the data into aSeries. It just returns the data in the form of tuples. -
iterrowsdoes box the data into aSeries. Unless you really need this, use another method. -
Updating an empty frame a-single-row-at-a-time. I have seen this method used WAY too much. It is by far the slowest. It is probably common place (and reasonably fast for some Python structures), but a
DataFramedoes a fair number of checks on indexing, so this will always be very slow to update a row at a time. Much better to create new structures andconcat.