How to replace list of values with one value

In this post you will learn how to replace list of values with one value in Pandas.

Preparing data for processing is usually tedious and time-consuming. In this post, we will consider the scenario when you have finished preparing the data and suddenly your boss tells you to replace the values in the list with something else in your dataframe.

Can you lose control? Thankfully, this post will make it easier.

How to replace list of values with one value in Pandas

Your task is the following. Your boss gave you a list of values. You have to replace them with another value.

I’ll show you how to replace values in a list using the replace function.

import pandas as pd

my_df = pd.DataFrame({'Id1': ['abc', 'abd', 'abe', 'abf'],
                      'Id2': ['abf', 'abd', 'abb', 'abt'],
                      'Id3': ['abn', 'abr', 'abb', 'aby']})

my_df = my_df.replace(to_replace=['abb', 'abc', 'abd'], value='xyz')

print(f'I changed the list of values to xyz \n{my_df}')

how to replace list of values

I passed the list of values as a parameter in the replace function. The next parameter is the new value to be written to the dataframe.

See also:
Documentation of replace function

Leave a Reply