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
Essential Gigs
For only $50, Nilimesh will develop time series forecasting model for you using python or r. | Note: please contact me…www.fiverr.com
For only $50, Nilimesh will do your data analytics and econometrics projects in python. | Note: please contact me…www.fiverr.com
For only $50, Nilimesh will do your machine learning and data science projects in python. | Note: please contact me…www.fiverr.com
For only $50, Nilimesh will do your gis and spatial programming projects in python. | Note: please contact me before…www.fiverr.com