How to REPLACE multiple values in a Pandas DataFrame in Python

How to REPLACE multiple values in a Pandas DataFrame in Python

Replacing multiple values in a Pandas DataFrame in Python can be done by using the replace() function. This function allows you to replace one or more values in a DataFrame with new values.

First, you need to import the Pandas library and create a DataFrame. For example, you can create a DataFrame with some sample data.

import pandas as pd

data = {'product': ['Apple', 'Banana', 'Cherry', 'Date', 'Eggplant'],

'price': [1.2, 2.3, 2.5, 1.7, 2.0],

'quantity': [3, 5, 2, 4, 8]

}

df = pd.DataFrame(data)

Next, you can use the replace() function to replace multiple values in the DataFrame. You can pass a dictionary containing the current values as keys and the new values as values to the replace() function.

For example, if you want to replace ‘Apple’ with ‘Green Apple’ and ‘Banana’ with ‘Yellow Banana’ in the ‘product’ column, you can use the following code:

df = df.replace({'product': {'Apple': 'Green Apple', 'Banana': 'Yellow Banana'}})

Alternatively, you can also use the replace() function inplace to change the values in the same dataframe

df.replace({'product': {'Apple': 'Green Apple', 'Banana': 'Yellow Banana'}}, inplace=True)

You can also use values parameter to replace values, it can take a dictionary or a scalar value.

df.replace({'product': {'Apple': 'Green Apple', 'Banana': 'Yellow Banana'}},value=np.nan, inplace=True)

By using the replace() function in this way, you can easily replace multiple values in a Pandas DataFrame in Python. This can be useful for data cleaning and preprocessing, as it allows you to standardize the data and make it easier to work with.

 

In this Learn through Codes example, you will learn: How to REPLACE multiple values in a Pandas DataFrame in Python.

Find more … …

Python Example – Write a Python program to replace dictionary values with their average

Pandas Example – Write a Pandas program to replace more than one value with other values in a given DataFrame

R Program to extract or replace parts of a factor

PostgreSQL Example – How to Replace Missing Values

Essential Gigs