Replace `apply` With Method Call
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-method-call
Section titled “Sourcery refactoring id: replace-apply-with-method-call”Description
Section titled “Description”Replace .apply with a call to a DataFrame’s or Series’s method.
Before
Section titled “Before”import pandas as pd
df = pd.DataFrame(data={"col1": [1, 2], "col2": [3, 4]})df.apply("sum")import pandas as pd
df = pd.DataFrame(data={"col1": [1, 2], "col2": [3, 4]})df.sum()Before
Section titled “Before”import pandas as pd
series_ = pd.Series([1, 1, 2, 3, 5, 8])series_.apply("min")import pandas as pd
series_ = pd.Series([1, 1, 2, 3, 5, 8])series_.min()Explanation
Section titled “Explanation”Instead of calling apply with an aggregation method, it’s less verbose to call
the aggregation method itself.
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.
Related Rule
Section titled “Related Rule”- replace-apply-with-numpy-operation to
use the faster and more performant NumPy operations instead of
apply