Open
Description
Original
def foo(x):
return np.mean([len(w) for w in str(x).split()])
df["A"] = df["B"].apply(foo)
Rewritten
def foo(x):
ls = [len(w) for w in str(x).split()]
return sum(ls) / len(ls)
df["A"] = df["B"].apply(foo)
This can be difficult to generalize. Let's just say for now that if we have np.mean(<list comprehension>)
, we transform it as above.
Note: Usually, numpy functions should be applied only to numpy arrays, otherwise they are slower than the Python ones.