Pandas How To Uncategorized How to replace string with another string in Pandas

How to replace string with another string in Pandas

To replace a string with another string in a Pandas DataFrame, you can use the str.replace() method. This method allows you to replace a substring within a string with a new substring. 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 'apple' with 'pear'
df['fruit'] = df['fruit'].str.replace('apple', 'pear')


This will output:

 fruit count
0 pear 3
1 banana 2
2 orange 4
3 kiwi 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 str.replace() method to replace the substring ‘apple’ with ‘pear’ in the ‘fruit’ column. The resulting DataFrame was printed to the console.

Note that str.replace() is case-sensitive by default. If you want to perform a case-insensitive replacement, you can pass the case=False argument to the method. For example, to replace all instances of ‘apple’, ‘Apple’, ‘APPLE’, etc. with ‘pear’, you could use the following code:

df['fruit'] = df['fruit'].str.replace('apple', 'pear', case=False)

This will replace all instances of ‘apple’ (in any case) with ‘pear’.

Tags: ,

Leave a Reply

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

Related Post