str.replace()

Pandas

Number of occurrences of pattern in a string.
Returns Series or Index

replacing string

All @ are replaced by #
import pandas as pd 
my_dict={'email':['Ravi@example.com','Raju@example.com','Alex@example.com']}
df = pd.DataFrame(data=my_dict)
print(df.email.str.replace('@','#'))
Output
0    Ravi#example.com
1    Raju#example.com
2    Alex#example.com

Case insensitive search and replace

By using option case=False we can make case insensitive search and replace.
import pandas as pd 
my_dict={'email':['Ravi@example.com','Raju@example.com','Alex@example.com']}
df = pd.DataFrame(data=my_dict)
print(df.email.str.replace('ravi','Ronn',case=False))
Output ( Ravi is replaced by Ronn )
0    Ronn@example.com
1    Raju@example.com
2    Alex@example.com

Using Regular expression

import pandas as pd 
my_dict={'email':['Ra2vi@example.com','Raju@example.com','Alex@example.com']}
df = pd.DataFrame(data=my_dict)
print(df.email.str.replace('^[AC]','*'))
Output ( Char starting with A or C are replaced with * , so A at Alex is replaced )
0    Ra2vi@example.com
1     Raju@example.com
2     *lex@example.com
Let us replace only digits
import pandas as pd 
my_dict={'email':['Ra2vi@example.com','Raju@example.com','Alex@example.com']}
df = pd.DataFrame(data=my_dict)
print(df.email.str.replace('[0-9]','*'))
Output
0    Ra*vi@example.com
1     Raju@example.com
2     Alex@example.com
Let us replace a or b chars
import pandas as pd 
my_dict={'email':['Ra2vi@example.com','Raju@example.com','Alex@example.com']}
df = pd.DataFrame(data=my_dict)
print(df.email.str.replace('[a|b]','*'))
Output is here
0    R*2vi@ex*mple.com
1     R*ju@ex*mple.com
2     Alex@ex*mple.com

Number of replacements

In above code we have replaced all the occurrences. Now let us limit to one only replacement.
import pandas as pd 
my_dict={'email':['Ra2vi@example.com','Raju@example.com','Alex@example.com']}
df = pd.DataFrame(data=my_dict)
print(df.email.str.replace('[a|b]','*',n=1))
Output
0    R*2vi@example.com
1     R*ju@example.com
2     Alex@ex*mple.com
Pandas contains() Converting char case slice() split()
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2023 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer