Skip to content
Advertisement

Replace an exact substring in column value

The ‘Last year (2019)’ should be replaced with ‘LY’ I tried this but it did not work.

df1 = pd.DataFrame({'Revenue':["Last year (2019),This year (2020)","This year",np.nan],
           'Cost':["This year,Last Year","This year",np.nan]})
df1.iloc[:,0:3].replace(to_replace ='Last year (2019)', value = 'LY', regex = True)

enter image description here

I have tried several regex attempts using ‘b’ but nothing seems to work. Any help is apprecciated

Advertisement

Answer

Following may help you here, you need to escape ( and ) to make it treat like as a literal character.

df1.iloc[:,0:3].replace(to_replace ='Last year (2019)', value = 'LY', regex = True)

Following is the testing of above code:

import pandas as pd
df1 = pd.DataFrame({'Revenue':["Last year (2019),This year (2020)","This year",np.nan],
           'Cost':["This year,Last Year","This year",np.nan]})
df1.iloc[:,0:3].replace(to_replace ='Last year (2019)', value = 'LY', regex = True)


    Cost                Revenue
0   This year,Last Year LY,This year (2020)
1   This year           This year
2   NaN NaN
Advertisement