w3resource

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


Pandas: Custom Function Exercise-9 with Solution


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.

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.