Pandas map() Method

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

1. Overview and Syntax

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.

Method Signature: Series.map(arg, na_action=None) or DataFrame.map(func, na_action=None)
Parameters:
• arg / func: Dictionary, function, or Series lookup.
• na_action: Set to 'ignore' to skip applying functions to NaN values.
Returns: A Series or DataFrame with substituted values.

2. Dictionary Lookups & Categorical Mapping

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)

3. Formatting Strings & Custom Functions

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)

4. Frequently Asked Questions (FAQs)

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.

5. Common Errors & Troubleshooting

AttributeError: 'Series' object has no attribute 'applymap'
Cause: Attempting to call DataFrame-only methods on Series objects.
Fix: Use Series.map() for Series transformations.
Interactive Companion Jupyter Notebook

Explore interactive code cells, dynamically generate classes, test type vs isinstance comparisons, and run self-validating assertions.

View on GitHub Open In Colab

6. Related Tutorials




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer