import pandas as pd
s = pd.Series(['cat', 'dog', 'cow'])
mapping = {'cat': 'feline', 'dog': 'canine'}
print(s.map(mapping))
Expected Output:
0 feline
1 canine
2 NaN
dtype: object
The map() method performs element-wise value substitutions across Pandas Series and DataFrames (Pandas 2.1+). It accepts dictionaries, callable Python functions, or matching Pandas Series lookup tables.
Series.map(arg, na_action=None) or DataFrame.map(func, na_action=None)arg / func: Dictionary, function, or Series lookup.na_action: Set to 'ignore' to skip applying functions to NaN values.Map raw category keys or codes to human-readable text labels using Python dictionaries.
import pandas as pd
df_students = pd.DataFrame({
'NAME': ['Ravi', 'Ananya', 'Alex'],
'GRADE_CODE': [1, 2, 3]
})
grade_map = {1: 'Grade A', 2: 'Grade B', 3: 'Grade C'}
df_students['GRADE_NAME'] = df_students['GRADE_CODE'].map(grade_map)
print(df_students)
Format floating-point numbers or apply string manipulations using Python format strings or lambdas.
import pandas as pd
prices = pd.Series([19.99, 5.5, 100.0])
formatted_prices = prices.map(lambda x: f"${x:.2f}")
print(formatted_prices)
Q: What happens if a key is missing from a mapping dictionary?
Unmapped keys produce NaN in the output series. To preserve unmapped original values, use replace() instead of map().
Q: What is the difference between map() and applymap()?
In Pandas 2.1+, applymap() is deprecated in favor of DataFrame.map() for element-wise transformations on DataFrames.
Series.map() for Series transformations.
Explore interactive code cells, dynamically generate classes, test type vs isinstance comparisons, and run self-validating assertions.
View on GitHubAuthor & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.