用于逐元素操作的 map() 和 applymap()
使用 map() 对 Series 的每个元素应用函数,使用 applymap() 对 DataFrame 的每个单元格应用函数。
用于逐元素操作的 map() 和 applymap() 是 CoddyKit 上的免费 Pandas & NumPy Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Pandas & NumPy Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Pandas & NumPy Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
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.
常见问题解答
「用于逐元素操作的 map() 和 applymap()」课时是免费的吗?
是的 — 「用于逐元素操作的 map() 和 applymap()」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Pandas & NumPy Academy 课程的其余内容,请升级到 CoddyKit PRO。 Pandas & NumPy Academy 课程共包含 4 节课。
「用于逐元素操作的 map() 和 applymap()」这节课中我会学到什么?
使用 map() 对 Series 的每个元素应用函数,使用 applymap() 对 DataFrame 的每个单元格应用函数。 你通过在浏览器中直接运行的动手代码来练习 Pandas & NumPy Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Pandas & NumPy Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Pandas & NumPy Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「用于逐元素操作的 map() 和 applymap()」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Pandas & NumPy Academy 课中编写并运行代码吗?
能。每节 Pandas & NumPy Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 对列和行使用 apply()
- 对 GroupBy 使用 apply()
- 用于逐元素操作的 map() 和 applymap()
- 使用 pipe() 链式调用方法