replace() function in pandas – replace a string in dataframe python

In this tutorial we will learn how to replace a string or substring in a column of a dataframe in python pandas with an alternative string. We will be using replace() Function in pandas python

Lets look at it with an example

Create dataframe:

## create dataframe

import pandas as pd
d = {'Quarters' : ['quarter1','quarter2','quarter3','quarter4'],
     'Revenue':[23400344.567,54363744.678,56789117.456,4132454.987]}
df=pd.DataFrame(d)
print df

resultant dataframe will be

String Replace in the column of a dataframe in python pandas

Now lets use replace() function in pandas python to replace “q” with “Q” in Quarters column

# Replace function in python to replace a substring with another 

df['Quarters_Replaces'] = map(lambda x: x.replace("q","Q"), df['Quarters'])
print df

the occurrences of “q”  is replaced with “Q” and the result is stored in ‘Quarters_Replaces’ column

so the resultant dataframe will be

String Replace in the column of a dataframe in python pandas

 

previous String Replace in the column of a dataframe in python pandas - replace() function in pandas                                                                                                        next String Replace in the column of a dataframe in python pandas - replace() function in pandas

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.

    View all posts