요소별 연산에 map()과 applymap() 사용하기
map()으로 Series의 모든 요소에, applymap()으로 DataFrame의 모든 셀에 함수를 적용합니다.
요소별 연산에 map()과 applymap() 사용하기은(는) CoddyKit의 무료 Pandas & NumPy Academy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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() 사용하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Pandas & NumPy Academy 강의 전체를 잠금 해제할 수 있습니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“요소별 연산에 map()과 applymap() 사용하기”에서 뭘 배우나요?
map()으로 Series의 모든 요소에, applymap()으로 DataFrame의 모든 셀에 함수를 적용합니다. 브라우저에서 직접 실행하는 실습 코드로 Pandas & NumPy Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Pandas & NumPy Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Pandas & NumPy Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“요소별 연산에 map()과 applymap() 사용하기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Pandas & NumPy Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Pandas & NumPy Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 열과 행에 apply() 적용하기
- GroupBy와 함께 apply() 사용하기
- 요소별 연산에 map()과 applymap() 사용하기
- pipe()를 사용한 메서드 연결