Apply
Apply is a commonly used method, to the point that I would argue it is overused. The .agg
, .transform
, and .map
methods seen so far have relatively clear semantics (.agg
reduces, .transform
maintains shape, .map
applies functions element-wise), but when you reach for .apply
, you can mirror any of these. That flexibility may seem nice at first, but because .apply
leaves it up to pandas to do the right thing, you are typically better off picking the most explicit methods to avoid surprises.
Even still, you will see a lot of code out in the wild (especially from users who did not read this book); so, understanding what it does and what its limitations are can be invaluable.
How to do it
Calling pd.Series.apply
will make .apply
act like .map
(i.e., the function gets applied to each individual element of the pd.Series
).
Let’s take a look at a rather contrived function that prints out each element:
def debug_apply(value):
print(f"Apply was called...