map() and applymap() for Element-Wise Operations
Apply a function to every element of a Series with map() and to every cell of a DataFrame with applymap().
map() and applymap() for Element-Wise Operations is a free Pandas & NumPy Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Pandas & NumPy Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Series.map() Overview
Series.map() applies a function, dictionary, or another Series to every element of a Series and returns a new Series. Unlike apply(), which can receive complex objects, map() always operates on individual scalar values. It is the standard tool for encoding categorical values, looking up labels from a mapping table, or applying a simple transformation element by element.
import pandas as pd
codes = pd.Series(['N', 'S', 'E', 'N', 'W'])
region_names = {'N': 'North', 'S': 'South', 'E': 'East', 'W': 'West'}
names = codes.map(region_names)
print(names)map() with a Function
Pass a function (including a lambda) to map() when the transformation involves logic rather than a lookup table. The function receives one scalar at a time, so it cannot access other rows or columns. For a simple conditional label assignment, map() with a function is cleaner than a loop but slower than np.where() for large Series.
prices = pd.Series([5.0, 25.0, 80.0, 150.0])
category = prices.map(lambda p: 'budget' if p < 20 else 'mid' if p < 100 else 'premium')
print(category)map() vs. replace()
Both map() and replace() can substitute values using a dictionary. The key difference: map() returns NaN for any value not found in the dictionary (unless you use fillna() afterwards), while replace() leaves unmatched values unchanged. Use replace() when you only want to change specific values and keep everything else as is.
s = pd.Series(['A', 'B', 'C', 'D'])
map_dict = {'A': 'Alpha', 'B': 'Beta'}
print('map():', s.map(map_dict).tolist()) # C,D → NaN
print('replace():', s.replace(map_dict).tolist()) # C,D → unchangedmap() with a Series (Label Lookup)
You can pass another Series to map() as a lookup table: the calling Series' values are used as keys to look up values in the argument Series' index. This is a concise way to join a lookup table without a full merge() call — it works like a vectorised dictionary lookup where the lookup table is indexed by key.
prices_lookup = pd.Series(
[10.0, 25.0, 50.0],
index=['SKU-001', 'SKU-002', 'SKU-003']
)
orders = pd.Series(['SKU-002', 'SKU-001', 'SKU-003', 'SKU-001'])
order_prices = orders.map(prices_lookup)
print(order_prices)DataFrame.applymap() for Cell-Wise Operations
DataFrame.applymap() (called DataFrame.map() in Pandas 2.1+) applies a function to every individual cell of a DataFrame. Unlike apply(axis=0) which receives a full column, applymap() receives one scalar at a time. It is useful for formatting all cells uniformly — for example, rounding every numeric cell to 2 decimal places or converting every string cell to lowercase.
df = pd.DataFrame({
'a': [1.234, 5.678, 9.012],
'b': [3.456, 7.890, 2.345]
})
# Round every cell to 1 decimal place
df_rounded = df.applymap(lambda x: round(x, 1))
print(df_rounded)applymap() for String Formatting
Apply consistent string formatting to every cell of a mixed-string DataFrame — for example, title-casing all values, or converting None to an empty string. applymap(str.strip) strips whitespace from every cell in the entire DataFrame with a single call, which is far more concise than iterating over columns and applying .str.strip() to each one individually.
df_str = pd.DataFrame({
'name': [' Alice ', 'Bob ', ' Carol'],
'city': ['new york ', ' london', 'paris ']
})
df_clean = df_str.applymap(str.strip)
print(df_clean)applymap() for Currency Formatting
When preparing a DataFrame for display in a report, format numeric cells as currency strings using applymap(). This converts numbers to display-ready strings without modifying the underlying data types — the transformation is only for the final output. Apply it as the last step before calling to_excel() or to_html() to export the formatted table.
revenue_table = pd.DataFrame({
'North': [12300.0, 9800.0],
'South': [7400.0, 11200.0]
}, index=['Q1', 'Q2'])
formatted = revenue_table.applymap(lambda x: f'${x:,.0f}')
print(formatted)Pandas 2.1: applymap Renamed to map
In Pandas 2.1, DataFrame.applymap() was renamed to DataFrame.map() to be consistent with Series.map(). The old applymap() still works with a deprecation warning. In production code, check your Pandas version and use df.map(func) if on 2.1+ to avoid deprecation warnings in future releases.
import pandas as pd
print('Pandas version:', pd.__version__)
# Forward-compatible pattern:
if hasattr(pd.DataFrame, 'map'):
df_clean = df_str.map(str.strip) # Pandas 2.1+
else:
df_clean = df_str.applymap(str.strip) # Pandas < 2.1
print(df_clean)map() for Encoding Categorical Features
Machine learning models require numeric inputs, so categorical columns must be encoded. Use map() with an integer-encoding dictionary to convert categories to ordinal numbers before feeding a DataFrame to a model. For nominal categories without natural order, prefer pd.get_dummies() or scikit-learn's OneHotEncoder instead.
size_order = {'small': 0, 'medium': 1, 'large': 2, 'enterprise': 3}
df['size_encoded'] = df['order_size'].map(size_order)
print(df[['order_size', 'size_encoded']])Chaining map() for Multi-Step Lookup
Chain two map() calls when you need a two-level lookup: first map a code to an intermediate key, then map the intermediate key to a final label. For example, map product SKU to category code, then map category code to category name. Chaining two map() calls is cleaner than a nested dictionary or a merge followed by another merge.
sku_to_cat_code = {'SKU-001': 'C1', 'SKU-002': 'C2', 'SKU-003': 'C1'}
cat_code_to_name = {'C1': 'Electronics', 'C2': 'Apparel'}
skus = pd.Series(['SKU-001', 'SKU-002', 'SKU-003'])
cat_names = skus.map(sku_to_cat_code).map(cat_code_to_name)
print(cat_names)Element-Wise Null Handling with map
When using map(func), the function is called even for NaN values, which can cause TypeError if the function does not handle None. Wrap the function with a null guard using pd.isna(x) or use na_action='ignore' parameter in map() to skip NaN values and leave them as NaN in the output without calling the function.
s = pd.Series([1.0, None, 3.0, None, 5.0])
# na_action='ignore' skips NaN values
result = s.map(lambda x: x * 2, na_action='ignore')
print(result)Quick Check
Test your understanding of Data Analysis concepts from this lesson.
Lesson Recap
In this lesson you learned: using Series.map() for scalar lookups with functions and dictionaries, using DataFrame.applymap()/map() for cell-wise formatting across all columns, and understanding the difference between map() and replace() for handling unmatched values. Next up we explore method chaining with pipe() for readable transformation pipelines.
Frequently asked questions
Is the “map() and applymap() for Element-Wise Operations” lesson free?
Yes — the full text of “map() and applymap() for Element-Wise Operations” is free to read here on the web, and the Pandas & NumPy Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Pandas & NumPy Academy course, upgrade to CoddyKit PRO.
What will I learn in “map() and applymap() for Element-Wise Operations”?
Apply a function to every element of a Series with map() and to every cell of a DataFrame with applymap(). You practise Pandas & NumPy Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Pandas & NumPy Academy?
No prior experience is required. Pandas & NumPy Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “map() and applymap() for Element-Wise Operations” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Pandas & NumPy Academy lesson?
Yes. Every Pandas & NumPy Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- apply() on Columns and Rows
- apply() with GroupBy
- map() and applymap() for Element-Wise Operations
- Method Chaining with pipe()