Q&A library Python

How do I apply a function to a column in pandas?

Python Beginner applymapvectorisation

Short answer

Use map or apply on a single column to run a function on every value, but prefer a vectorised expression or built-in string and numeric methods where one exists, because they are much faster.

The short version

Series.apply and Series.map run a function on every value in a column. They are handy for custom logic, but they loop internally, so a vectorised expression or a built-in method like .str or arithmetic on the whole column is faster where one exists. Reach for apply when no vectorised form is available.

The straightforward case

import pandas as pd

df = pd.DataFrame({"price": [10, 20, 30]})

df["with_vat"] = df["price"].apply(lambda p: p * 1.2)
print(df)

This works, but multiplying the column directly does the same thing faster.

df["with_vat"] = df["price"] * 1.2

When apply earns its place

Use apply when the logic is genuinely per-value and cannot be written as a single expression, for example a lookup or a multi-branch rule.

def band(p):
    if p < 15:
        return "cheap"
    elif p < 25:
        return "mid"
    return "dear"

df["band"] = df["price"].apply(band)

map for simple lookups

For replacing values through a dictionary, map is clearer than apply.

codes = {"cheap": "C", "mid": "M", "dear": "D"}
df["code"] = df["band"].map(codes)

Note that map returns NaN for any value not in the dictionary, which is useful for spotting unexpected inputs.

Prefer built-in accessors for text and dates

For string work, the .str accessor is both faster and clearer than apply.

df["band"].str.upper()          # vectorised, no lambda needed

Column-wise versus row-wise

Series.apply runs on one column. DataFrame.apply with axis=1 runs a function per row, receiving the whole row as a Series. Row-wise apply is flexible but slow, so use it only when the logic needs several columns and cannot be vectorised.

df.apply(lambda r: r["price"] * (1.2 if r["band"] == "dear" else 1.0), axis=1)

Need this solved on your own data?

The library is free and always will be. When the problem is bigger than an answer, we take on the work.

Start a project