Applying Functions

Pandas Basics

1 min read

Published Sep 29 2025, updated Oct 24 2025


21
0
0
0

PandasPython

What is .apply()?

  • .apply() applies a function to a Pandas object (Series or DataFrame).
  • It works elementwise, rowwise, or columnwise, depending on how you use it.
  • It’s more flexible than vectorised operations, but often slower.



On a Series

When used on a Series, the function is applied elementwise:

import pandas as pd

s = pd.Series([1, 2, 3, 4])

s.apply(lambda x: x**2)

Output:

0 1
1 4
2 9
3 16
dtype: int64




On a DataFrame

When used on a DataFrame, you can choose axis:

  • axis=0 (default) → apply function to each column.
  • axis=1 → apply function to each row.

Column example:

df = pd.DataFrame({
    "A": [1, 2, 3],
    "B": [10, 20, 30]
})

# Apply columnwise (axis=0)
df.apply(sum, axis=0)

Output:

A 6
B 60
dtype: int64


Row example:

# Apply rowwise (axis=1)
df.apply(lambda row: row["B"] - row["A"], axis=1)

Output:

0 9
1 18
2 27
dtype: int64





Returning New Columns

You can assign results back to new columns:

df["Diff"] = df.apply(lambda row: row["B"] - row["A"], axis=1)





Returning DataFrames

If your function returns a Series, .apply() can expand it into multiple columns:

def stats(row):
    return pd.Series({"Sum": row.sum(), "Mean": row.mean()})

df_stats = df.apply(stats, axis=1)

Products from our shop

Docker Cheat Sheet - Print at Home Designs

Docker Cheat Sheet - Print at Home Designs

Docker Cheat Sheet Mouse Mat

Docker Cheat Sheet Mouse Mat

Docker Cheat Sheet Travel Mug

Docker Cheat Sheet Travel Mug

Docker Cheat Sheet Mug

Docker Cheat Sheet Mug

Vim Cheat Sheet - Print at Home Designs

Vim Cheat Sheet - Print at Home Designs

Vim Cheat Sheet Mouse Mat

Vim Cheat Sheet Mouse Mat

Vim Cheat Sheet Travel Mug

Vim Cheat Sheet Travel Mug

Vim Cheat Sheet Mug

Vim Cheat Sheet Mug

SimpleSteps.guide branded Travel Mug

SimpleSteps.guide branded Travel Mug

Developer Excuse Javascript - Travel Mug

Developer Excuse Javascript - Travel Mug

Developer Excuse Javascript Embroidered T-Shirt - Dark

Developer Excuse Javascript Embroidered T-Shirt - Dark

Developer Excuse Javascript Embroidered T-Shirt - Light

Developer Excuse Javascript Embroidered T-Shirt - Light

Developer Excuse Javascript Mug - White

Developer Excuse Javascript Mug - White

Developer Excuse Javascript Mug - Black

Developer Excuse Javascript Mug - Black

SimpleSteps.guide branded stainless steel water bottle

SimpleSteps.guide branded stainless steel water bottle

Developer Excuse Javascript Hoodie - Light

Developer Excuse Javascript Hoodie - Light

Developer Excuse Javascript Hoodie - Dark

Developer Excuse Javascript Hoodie - Dark

© 2025 SimpleSteps.guide
AboutFAQPoliciesContact