Pandas How To Uncategorized How to replace specific values in column in Pandas

How to replace specific values in column in Pandas

To replace specific values in a column in Pandas, you can use the replace() method. This method allows you to replace one or more values with a new value or set of values. Here’s an example:

import pandas as pd

# create a sample dataframe
data = {'fruit': ['apple', 'banana', 'orange', 'kiwi'],
'count': [3, 2, 4, 1]}
df = pd.DataFrame(data)

# replace 'kiwi' with 'pear'
df['fruit'] = df['fruit'].replace('kiwi', 'pear')

# replace 'banana' and 'orange' with 'mango'
df['fruit'] = df['fruit'].replace(['banana', 'orange'], 'mango')


This will output:

 fruit count
0 apple 3
1 mango 2
2 mango 4
3 pear 1

In the example above, we first created a sample DataFrame with a ‘fruit’ column containing four different fruits and a ‘count’ column indicating the number of each fruit. We then used the replace() method to replace the value ‘kiwi’ with ‘pear’ and the values ‘banana’ and ‘orange’ with ‘mango’. The original DataFrame was modified in place, and the resulting DataFrame was printed to the console.

Note that you can also use replace() with a dictionary of replacement values. For example, to replace ‘apple’ with ‘red apple’ and ‘kiwi’ with ‘green kiwi’, you could use the following code:

df['fruit'] = df['fruit'].replace({'apple': 'red apple', 'kiwi': 'green kiwi'})

This will replace ‘apple’ with ‘red apple’ and ‘kiwi’ with ‘green kiwi’, leaving the other values in the ‘fruit’ column unchanged.


Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post