Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas apply / map / applymap

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

]

)

print

(

"Original data:"

)

print

(

s

)

print

(

)

Using the function

print

(

"Each element * 2:"

)

print

(

s.

map

(

lambda

x: x *

2

)

)

print

(

)

Map using a dictionary

mapping

=

{

1

:

"A"

,

2

:

"B"

,

3

:

"C"

,

4

:

"D"

,

5

:

"E"

}

print

(

"Mapped using a dictionary:"

)

print

(

s.

map

(

mapping

)

)

print

(

)

Map using a Series

mapping_series

=

pd.

Series

(

[

"A"

,

"B"

,

"C"

,

"D"

,

"E"

]

,

index

=

[

1

,

2

,

3

,

4

,

5

]

)

print

(

"Mapped using a Series:"

)

print

(

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

]

)

print

(

"Contains NaN:"

)

print

(

s

)

print

(

)

map skips NaN by default

print

(

"map processing (skipping NaN):"

)

print

(

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

]

}

)

print

(

"Original data:"

)

print

(

df

)

print

(

)

Multiply each element by 2

print

(

"Each element * 2:"

)

print

(

df.

applymap

(

lambda

x: x *

2

)

)

print

(

)

Keep 2 decimal places

print

(

"2 decimal places:"

)

print

(

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

]

}

)

print

(

"Original data:"

)

print

(

df

)

print

(

)

Default axis=0, apply by column

print

(

"Sum of each column:"

)

print

(

df.

apply

(

sum

)

)

print

(

)

print

(

"Max of each column:"

)

print

(

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

]

}

)

print

(

"Original data:"

)

print

(

df

)

print

(

)

axis=1, apply by row

print

(

"Sum of each row:"

)

print

(

df.

apply

(

sum

,

axis

=

1

)

)

print

(

)

Max minus min for each row

print

(

"Range of each row:"

)

print

(

df.

apply

(

lambda

x: x.

max

(

)

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

print

(

"Sum and mean at once:"

)

print

(

df.

apply

(

[

sum

,

np.

mean

]

)

)

print

(

)

Return multiple values

result

=

df.

apply

(

lambda

x: pd.

Series

(

{

   

"sum"

: x.

sum

(

)

,

   

"mean"

: x.

mean

(

)

,

   

"max"

: x.

max

(

)

}

,

index

=

[

"sum"

,

"mean"

,

"max"

]

)

)

print

(

"Multiple values returned:"

)

print

(

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

]

)

print

(

"Original data:"

)

print

(

s

)

print

(

)

Square root

print

(

"Square root:"

)

print

(

s.

apply

(

np.

sqrt

)

)

print

(

)

Conditional return

print

(

"Conditional check:"

)

print

(

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

=

time

.

time

(

)

result2

=

s.

apply

(

func

)

apply_time

=

time

.

time

(

)

Vectorized (fastest)

start

=

time

.

time

(

)

result3

=

s *

2

1

vec_time

=

time

.

time

(

)

print

(

f

"map time: {map_time:.4f}s"

)

print

(

f

"apply time: {apply_time:.4f}s"

)

print

(

f

"vectorized time: {vec_time:.4f}s"

)

print

(

"\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"

]

}

)

print

(

"Original data:"

)

print

(

df

)

print

(

)

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

)

print

(

"Calculation result: "

)

print

(

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.