Skip to content

np.mean() on list to sum(ls) / len(ls) #5

Open
@baziotis

Description

@baziotis

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    patternA pattern that Dias does not already rewrite into a faster version.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions