← Back to Pandas Course | Chapter 6: Data Operations | Lesson 1 of 7

apply()

apply runs a function on every value, row or column of your data.

In this page:

  1. apply()
Syntax
python
df["column"].apply(function_name)
df.apply(function_name, axis=0)

apply()

Series.apply(func) calls func on each value. DataFrame.apply(func, axis=0) runs func on each column, and axis=1 runs it on each row. It is flexible but slower than vectorized operations, so use it when no built-in method exists.

Note: Prefer vectorized operations such as df["a"] * 2 over apply whenever possible.

Example: apply()

python
import pandas as pd

df = pd.DataFrame({"a": [1, 2, 3], "b": [10, 20, 30]})
print(df["a"].apply(lambda x: x ** 2))
print(df.apply(sum))
print(df.apply(lambda row: row["a"] + row["b"], axis=1))

# Output:
# 0    1
# 1    4
# 2    9
# Name: a, dtype: int64
# a     6
# b    60
# dtype: int64
# 0    11
# 1    22
# 2    33
# dtype: int64
Related Topics
Common Mistakes
  1. Using apply where a vectorized operation exists
  2. Forgetting axis=1 for row-wise work
  3. Returning inconsistent types from the function
Chapter Summary
  • apply runs a function over values
  • axis=0 is per column, axis=1 per row
  • It is slower than vectorized code
  • Use it when no built-in fits
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.