apply()

noun

say it: “uh-PLY” /əˈplaɪ/

A pandas method that calls a function on each value in a column, one at a time, and collects what it returns.

What does apply() do in pandas?

apply() is a pandas method that runs a function you choose, or a lambda, on every value of a column, one value at a time, and gives back the results as a new column. It's slower than math on the whole column, so it's for work that math can't do.

import pandas as pd

def shipping(weight):
    return 5.0 if weight < 2 else 12.0

products = pd.DataFrame({"weight_lbs": [1.5, 3.0]})
products["shipping"] = products["weight_lbs"].apply(shipping)
print(products["shipping"].tolist())   # [5.0, 12.0]

In a sentence

  • “apply() ran the shipping function on every product's weight.”
  • “Because apply() works one value at a time, whole-column math is faster when it can do the job.”

Level: Journeyman · More Python terms at this level

Updated