map() и applymap() для поэлементных операций
Применяйте функцию к каждому элементу Series с помощью map(), а к каждой ячейке DataFrame — с помощью applymap().
«map() и applymap() для поэлементных операций» — бесплатный урок Pandas & NumPy Academy на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения 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() для поэлементных операций» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Pandas & NumPy Academy, подпишись на CoddyKit PRO. Курс Pandas & NumPy Academy содержит 4 уроков всего.
Чему я научусь в уроке «map() и applymap() для поэлементных операций»?
Применяйте функцию к каждому элементу Series с помощью map(), а к каждой ячейке DataFrame — с помощью applymap(). Ты практикуешь Pandas & NumPy Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Pandas & NumPy Academy?
Предыдущий опыт не требуется. Pandas & NumPy Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «map() и applymap() для поэлементных операций»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Pandas & NumPy Academy?
Да. Каждый урок Pandas & NumPy Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- apply() для столбцов и строк
- apply() с GroupBy
- map() и applymap() для поэлементных операций
- Цепочки методов с pipe()