Skip to content

Replace apply With Method Call

Sourcery refactoring id: replace-apply-with-method-call

Description

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

Before

import pandas as pd

df = pd.DataFrame(data={"col1": [1, 2], "col2": [3, 4]})
df.apply("sum")

After

import pandas as pd

df = pd.DataFrame(data={"col1": [1, 2], "col2": [3, 4]})
df.sum()

Before

import pandas as pd

series_ = pd.Series([1, 1, 2, 3, 5, 8])
series_.apply("min")

After

import pandas as pd

series_ = pd.Series([1, 1, 2, 3, 5, 8])
series_.min()

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.