The ‘Last year (2019)’ should be replaced with ‘LY’ I tried this but it did not work.
JavaScript
x
4
1
df1 = pd.DataFrame({'Revenue':["Last year (2019),This year (2020)","This year",np.nan],
2
'Cost':["This year,Last Year","This year",np.nan]})
3
df1.iloc[:,0:3].replace(to_replace ='Last year (2019)', value = 'LY', regex = True)
4
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.
JavaScript
1
2
1
df1.iloc[:,0:3].replace(to_replace ='Last year (2019)', value = 'LY', regex = True)
2
Following is the testing of above code:
JavaScript
1
11
11
1
import pandas as pd
2
df1 = pd.DataFrame({'Revenue':["Last year (2019),This year (2020)","This year",np.nan],
3
'Cost':["This year,Last Year","This year",np.nan]})
4
df1.iloc[:,0:3].replace(to_replace ='Last year (2019)', value = 'LY', regex = True)
5
6
7
Cost Revenue
8
0 This year,Last Year LY,This year (2020)
9
1 This year This year
10
2 NaN NaN
11