ZhangZhihui's Blog  

Let’s compare applymap(), apply(), and map() side by side with code and output, so you see clearly when to use each.


Setup

import pandas as pd

df = pd.DataFrame({
    "A": [1, 2, 3],
    "B": [4, 5, 6]
})
print(df)

 

Output:

   A  B
0  1  4
1  2  5
2  3  6

 


1. applymap()element-wise on the entire DataFrame

df.applymap(lambda x: x * 10)

 

Output:

    A   B
0  10  40
1  20  50
2  30  60

 

✅ Every value in every column was multiplied by 10.


2. apply()column-wise or row-wise operations

  • By default (axis=0), applies function to each column (Series).

df.apply(sum, axis=0)   # sum down each column

 

Output:

A     6
B    15
dtype: int64

 

  • With axis=1, applies function to each row.

df.apply(sum, axis=1)   # sum across each row

 

Output:

0     5
1     7
2     9
dtype: int64

 

✅ Works on rows/columns as groups, not individual elements.


3. map()element-wise, but only for a Series

df["A"].map(lambda x: x ** 2)

 

Output:

0    1
1    4
2    9
Name: A, dtype: int64

 

✅ Applies only to one column (Series), not the entire DataFrame.


📌 Quick Summary

FunctionScopeUsage Example
applymap() Element-wise, all DataFrame df.applymap(lambda x: x*2)
apply() Row-wise / Column-wise df.apply(sum, axis=0)
map() Element-wise, Series only df["col"].map(str.upper)

👉 So, if you want element-wise over the whole DataFrame, use applymap().
👉 If you want row or column aggregations/transformations, use apply().
👉 If you want element-wise on a single column, use map().

 

posted on 2025-09-02 17:27  ZhangZhihuiAAA  阅读(14)  评论(0)    收藏  举报