Skip to content

Replace apply With NumPy Operation

Documentation Index

Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt

Use this file to discover all available pages before exploring further.

Sourcery refactoring id: replace-apply-with-numpy-operation

Section titled “Sourcery refactoring id: replace-apply-with-numpy-operation”

Replace apply with a NumPy operation.

import pandas as pd
series_ = pd.Series([5, 8, 13, 21, 34])
other = series_.apply(lambda num: num + 5)
import pandas as pd
series_ = pd.Series([5, 8, 13, 21, 34])
other = series_ + 5

For numeric operations, using pandas directly gives you better performance than apply. The bigger your dataset, the bigger this performance gain tends to be. This is because pandas uses fast, vectorized NumPy code, but apply operates on each value of your Series or DataFrame separately.

apply is a versatile method, that can be used for various different use cases. However, there’s often a less verbose or more performant alternative. Try to check out those alternatives - especially when you’re working with a big dataset.