Applying Functions
Pandas Basics
1 min read
This section is 1 min read, full guide is 30 min read
Published Sep 29 2025, updated Oct 24 2025
21
Show sections list
0
Log in to enable the "Like" button
0
Guide comments
0
Log in to enable the "Save" button
Respond to this guide
Guide Sections
Guide Comments
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)
Copy to Clipboard
Output:
0 1
1 4
2 9
3 16
dtype: int64
Copy to Clipboard
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)
Copy to Clipboard
Toggle show comments
Output:
A 6
B 60
dtype: int64
Copy to Clipboard
Row example:
# Apply rowwise (axis=1)
df.apply(lambda row: row["B"] - row["A"], axis=1)
Copy to Clipboard
Toggle show comments
Output:
0 9
1 18
2 27
dtype: int64
Copy to Clipboard
Returning New Columns
You can assign results back to new columns:
df["Diff"] = df.apply(lambda row: row["B"] - row["A"], axis=1)
Copy to Clipboard
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)
Copy to Clipboard














