Pandas replace function does not work on Series of strings

Viewed 61

pandas.DataFrame.replace doesn't replace string.

dic = {'Text': ['i8am going to school', 'i8am a very good boy']}
df = pd.DataFrame(dic)
d = df['Text'].replace(to_replace='i8am', value='i am')
print(d)

Expected output:

I am going to school
I am a very good boy
3 Answers

We can use str accessor and then replace the string over it.

d = df.Text.str.replace('i8am', 'I am')

Output

0    I am going to school
1    I am a very good boy

To work with text data, you need to use '.str' more info here - https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html.

import pandas as pd
dic = {'Text': ['i8am going to school', 'i8am a very good boy']}
df = pd.DataFrame(dic)
d = df['Text'].str.replace('i8am', 'i am')

Output -

0    i am going to school
1    i am a very good boy

Plus, You need to check the function signature. You can't just pass random keyword args and expect it to work.

If you do like replace

df['Text'] = df['Text'].replace({'i8am':'i am'},regex=True)
Related