Get Started

Replace multiple values II

As discussed in the video, instead of using the .replace() function multiple times to replace multiple values, you can use lists to map the elements you want to replace one to one with those you want to replace them with.

As you have seen in our popular names dataset, there are two names for the same ethnicity. We want to standardize the naming of each ethnicity by replacing

  • 'ASIAN AND PACI' to 'ASIAN AND PACIFIC ISLANDER'
  • 'BLACK NON HISP' to 'BLACK NON HISPANIC'
  • 'WHITE NON HISP' to 'WHITE NON HISPANIC'

In the DataFrame names, you are going to replace all the values on the left by the values on the right.

This is a part of the course

“Writing Efficient Code with pandas”

View Course

Exercise instructions

  • Replace all the ethnicities by their respective alternative, as indicated above.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

start_time = time.time()

# Replace ethnicities as instructed
names['Ethnicity'].replace([____,____, ____], [____,____,____], inplace=True)

print("Time using .replace(): {} sec".format(time.time() - start_time))

This exercise is part of the course

Writing Efficient Code with pandas

IntermediateSkill Level
4.5+
11 reviews

Learn efficient techniques in pandas to optimize your Python code.

This chapter shows the usage of the replace() function for replacing one or multiple values using lists and dictionaries.

Exercise 1: Replace scalar values using .replace()Exercise 2: Replacing scalar values IExercise 3: Replace scalar values IIExercise 4: Replace values using listsExercise 5: Replace multiple values IExercise 6: Replace multiple values II
Exercise 7: Replace values using dictionariesExercise 8: Replace single values IExercise 9: Replace single values IIExercise 10: Replace multiple values IIIExercise 11: Most efficient method for scalar replacement

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free