How to Use applymap in pandas for Element-wise DataFrame Operations
Use
applymap in pandas to apply a function to each element of a DataFrame individually. It works element-wise, unlike apply which works on rows or columns. Simply call df.applymap(your_function) to transform every cell.Syntax
The basic syntax of applymap is:
df.applymap(func): Applies the functionfuncto each element of the DataFramedf.
Explanation:
df: Your pandas DataFrame.func: A function that takes a single value and returns a transformed value.
python
df.applymap(func)
Example
This example shows how to use applymap to square every number in a DataFrame.
python
import pandas as pd df = pd.DataFrame({ 'A': [1, 2, 3], 'B': [4, 5, 6] }) # Function to square a number def square(x): return x * x # Apply square function to each element result = df.applymap(square) print(result)
Output
A B
0 1 16
1 4 25
2 9 36
Common Pitfalls
1. Using applymap on Series: applymap works only on DataFrames, not Series. Use apply or map for Series.
2. Function expecting multiple arguments: The function passed to applymap must take exactly one argument (a single cell value).
3. Using apply when you want element-wise: apply works on rows or columns, not element-wise. For element-wise, use applymap.
python
import pandas as pd df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}) # Wrong: applymap on Series (raises AttributeError) try: df['A'].applymap(lambda x: x*2) except AttributeError as e: print(f'Error: {e}') # Correct: use apply or map on Series result = df['A'].apply(lambda x: x*2) print(result)
Output
Error: 'Series' object has no attribute 'applymap'
0 2
1 4
Name: A, dtype: int64
Quick Reference
| Method | Use Case | Input Type | Output Type |
|---|---|---|---|
| applymap(func) | Apply function element-wise to DataFrame | DataFrame | DataFrame |
| apply(func, axis=0 or 1) | Apply function to rows or columns | DataFrame | Series or DataFrame |
| map(func or dict) | Map values in Series | Series | Series |
Key Takeaways
Use applymap to apply a function to each individual cell in a DataFrame.
The function passed to applymap must take one argument and return a value.
applymap works only on DataFrames, not on Series.
For element-wise operations on Series, use map or apply instead.
applymap differs from apply which works on rows or columns, not element-wise.