w3resource

Replace values in a Pandas Series using map() and dictionary mapping


9. Replace Values Using map() with a Dictionary

Write a Python program that applies map() function to replace values based on a dictionary.

In this exercise, we have used map() function to replace values in a Pandas Series based on a dictionary mapping.

Sample Solution:

Code :

import pandas as pd

# Create a sample Series
s = pd.Series([1, 2, 3, 4, 5])

# Define a dictionary to map values
replace_dict = {1: 'one', 2: 'two', 3: 'three'}

# Apply the dictionary mapping using map()
s_mapped = s.map(replace_dict)

# Output the result
print(s_mapped)

Output:

0      one
1      two
2    three
3      NaN
4      NaN
dtype: object                             

Explanation:

  • Created a Pandas Series with 5 values.
  • Defined a dictionary replace_dict to map numeric values to string equivalents.
  • Applied map() to the Series to replace values based on the dictionary.
  • Returned the Series with replaced values where applicable, leaving other values as NaN.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to replace specified values in a Series using map() with a provided dictionary mapping.
  • Write a Pandas program to apply map() to a Series to substitute abbreviations with full names using a dictionary.
  • Write a Pandas program to use map() to recode a Series of numerical codes into descriptive labels based on a dictionary.
  • Write a Pandas program to replace missing or placeholder values in a Series by mapping them to standard values using map().

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.