Pandas apply / map / applymap
apply, map, and applymap are the three major functions in Pandas used for data transformation; they can perform flexible element-wise or batch operations on a DataFrame or Series.
Series.map
map is a method of Series, used to transform each element in a Series.
Basic Usage
Example
import
pandas
as
pd
Create a Series
s
=
pd.
Series
(
[
1
,
2
,
3
,
4
,
5
]
)
(
"Original data:"
)
(
s
)
(
)
Using the function
(
"Each element * 2:"
)
(
s.
map
(
lambda
x: x *
2
)
)
(
)
Map using a dictionary
mapping
=
{
1
:
"A"
,
2
:
"B"
,
3
:
"C"
,
4
:
"D"
,
5
:
"E"
}
(
"Mapped using a dictionary:"
)
(
s.
map
(
mapping
)
)
(
)
Map using a Series
mapping_series
=
pd.
Series
(
[
"A"
,
"B"
,
"C"
,
"D"
,
"E"
]
,
index
=
[
1
,
2
,
3
,
4
,
5
]
)
(
"Mapped using a Series:"
)
(
s.
map
(
mapping_series
)
)
Handle missing values
Example
import
pandas
as
pd
import
numpy
as
np
s
=
pd.
Series
(
[
1
,
2
,
np.
nan
,
4
,
5
]
)
(
"Contains NaN:"
)
(
s
)
(
)
map skips NaN by default
(
"map processing (skipping NaN):"
)
(
s.
map
(
lambda
x: x *
2
if
pd.
notna
(
x
)
else
1
)
)
DataFrame.applymap
applymap is a method of DataFrame, applying a function to each element one by one (note: Pandas 2.0+ recommends using DataFrame.map instead).
Example
import
pandas
as
pd
import
numpy
as
np
df
=
pd.
DataFrame
(
{
"A"
:
[
1
,
2
,
3
]
,
"B"
:
[
4
,
5
,
6
]
,
"C"
:
[
7
,
8
,
9
]
}
)
(
"Original data:"
)
(
df
)
(
)
Multiply each element by 2
(
"Each element * 2:"
)
(
df.
applymap
(
lambda
x: x *
2
)
)
(
)
Keep 2 decimal places
(
"2 decimal places:"
)
(
df.
applymap
(
lambda
x:
round
(
x
,
2
)
)
)
applymap operates element by element and can be slow for large data. If you only need to operate on numeric columns, consider vectorized operations or apply with the axis parameter.
DataFrame.apply
apply is the most flexible method, allowing functions to be applied along an axis.
Apply by column
Example
import
pandas
as
pd
import
numpy
as
np
df
=
pd.
DataFrame
(
{
"A"
:
[
1
,
2
,
3
,
4
,
5
]
,
"B"
:
[
10
,
20
,
30
,
40
,
50
]
,
"C"
:
[
100
,
200
,
300
,
400
,
500
]
}
)
(
"Original data:"
)
(
df
)
(
)
Default axis=0, apply by column
(
"Sum of each column:"
)
(
df.
apply
(
sum
)
)
(
)
(
"Max of each column:"
)
(
df.
apply
(
max
)
)
Apply by row
Example
import
pandas
as
pd
import
numpy
as
np
df
=
pd.
DataFrame
(
{
"A"
:
[
1
,
2
,
3
]
,
"B"
:
[
10
,
20
,
30
]
,
"C"
:
[
100
,
200
,
300
]
}
)
(
"Original data:"
)
(
df
)
(
)
axis=1, apply by row
(
"Sum of each row:"
)
(
df.
apply
(
sum
,
axis
=
1
)
)
(
)
Max minus min for each row
(
"Range of each row:"
)
(
df.
apply
(
lambda
x: x.
max
(
)
- x.
min
(
)
,
axis
=
1
)
)
Aggregate using aggfunc
Example
import
pandas
as
pd
import
numpy
as
np
df
=
pd.
DataFrame
(
{
"A"
:
[
1
,
2
,
3
]
,
"B"
:
[
10
,
20
,
30
]
}
)
Apply multiple functions at once
(
"Sum and mean at once:"
)
(
df.
apply
(
[
sum
,
np.
mean
]
)
)
(
)
Return multiple values
result
=
df.
apply
(
lambda
x: pd.
Series
(
{
"sum"
: x.
sum
(
)
,
"mean"
: x.
mean
(
)
,
"max"
: x.
max
(
)
}
,
index
=
[
"sum"
,
"mean"
,
"max"
]
)
)
(
"Multiple values returned:"
)
(
result
)
Series.apply
Series can also use apply, similar to map but more flexible.
Example
import
pandas
as
pd
import
numpy
as
np
s
=
pd.
Series
(
[
1
,
4
,
9
,
16
,
25
]
)
(
"Original data:"
)
(
s
)
(
)
Square root
(
"Square root:"
)
(
s.
apply
(
np.
sqrt
)
)
(
)
Conditional return
(
"Conditional check:"
)
(
s.
apply
(
lambda
x:
"Large"
if
x
10
else
"Small"
)
)
Performance Comparison
Example
import
pandas
as
pd
import
numpy
as
np
import
time
Create large data
n
=
100000
s
=
pd.
Series
(
np.
random
.
randn
(
n
)
)
Test map vs apply
func
=
lambda
x: x *
2
1
start
=
time
.
time
(
)
result1
=
s.
map
(
func
)
map_time
=
time
.
time
(
)
- start
start
=
time
.
time
(
)
result2
=
s.
apply
(
func
)
apply_time
=
time
.
time
(
)
- start
Vectorized (fastest)
start
=
time
.
time
(
)
result3
=
s *
2
1
vec_time
=
time
.
time
(
)
- start
(
f
"map time: {map_time:.4f}s"
)
(
f
"apply time: {apply_time:.4f}s"
)
(
f
"vectorized time: {vec_time:.4f}s"
)
(
"\nConclusion: Prefer vectorized operations for the best performance"
)
Practical: Data transformation
Example
import
pandas
as
pd
import
numpy
as
np
Create a sample DataFrame
df
=
pd.
DataFrame
(
{
"Name"
:
[
"Zhang San"
,
"Li Si"
,
"Wang Wu"
,
"Zhao Liu"
]
,
"Age"
:
[
25
,
30
,
28
,
35
]
,
"Salary"
:
[
12000
,
15000
,
11000
,
18000
]
,
"Department"
:
[
"Technology"
,
"Sales"
,
"Technology"
,
"Operations"
]
}
)
(
"Original data:"
)
(
df
)
(
)
Use apply for row-level computation
def
calculate
(
row
)
:
"""Compute annual income and after-tax salary"""
annual
=
row
[
"Salary"
]
12
tax
=
annual *
0.1
if
annual
120000
else
annual *
0.05
after_tax
=
annual - tax
return
pd.
Series
(
{
"Annual salary"
: annual
,
"Tax"
: tax
,
"After tax"
: after_tax
}
)
result
=
df.
apply
(
calculate
,
axis
=
1
)
df_result
=
pd.
concat
(
[
df
,
result
]
,
axis
=
1
)
(
"Calculation result: "
)
(
df_result
)
Choosing among the three
| Method | Applies to | Scenario | Performance |
|---|---|---|---|
map |
Series | Element-wise transformation, dictionary mapping | fast |
applymap |
DataFrame | Element-wise transformation (non-numeric columns) | Slow |
apply |
Series/DataFrame | Row/column aggregation, custom functions | Medium |
Don't use apply/map when a vectorized operation (a direct operator) is possible; don't use apply when map is possible.