Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing an string in a dataframe python

I have a (7,11000) dataframe. in some of these 7 columns, there are strings. In Coulmn 2 and row 1000, there is a string 'London'. I want to change it to 'Paris'. how can I do this? I searched all over the web but I couldnt find a way. I used theses commands but none of them works:

df['column2'].replace('London','Paris')
df['column2'].str.replace('London','Paris')
re.sub('London','Paris',df['column2'])

I usually receive this error:

TypeError: expected string or bytes-like object
like image 363
CFD Avatar asked Aug 09 '26 08:08

CFD


1 Answers

If you want to replace a single row (you mention row 1000), you can do it with .loc. If you want to replace all occurrences of 'London', you could do this:

import pandas as pd
df = pd.DataFrame({'country': ['New York', 'London'],})
df.country = df.country.str.replace('London', 'Paris')

Alternatively, you could write your own replacement function, and then use .apply:

def replace_country(string):
    if string == 'London':
        return 'Paris'
    return string

df.country = df.country.apply(replace_country)

The second method is a bit overkill, but is a good example that generalizes better for more complex tasks.

like image 87
Charles Avatar answered Aug 12 '26 00:08

Charles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!