Skip to content

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”

Replace .apply with a call to a DataFrame’s or Series’s method.

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()
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()

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.