How to replace last 2 characters if available in python

Viewed 312

Parse and replace last 2 specific characters from the string if available.

For Eg: 0 = O, 5 = S, 1=I

Input Data:

Col1

AZBYCCCD0
NZBY23HG1
BZYCQ05CO
YODZ225H0
NaN
CS45DRNZQ

Expected Output:

Col1

AZBYCCCDO
NZBY23HGI
BZYCQ05CO
YODZ225HO
NaN
CS45DRNZQ

I have been trying to use :

repl = {'0':'O','1':'I'}
df['Col1'] = df['Col1'].astype(str).str[7:].replace(repl, regex=True)

But the above script doesn't work.

Please Suggest

4 Answers

The problem you are seeing is that you are only selecting the last two characters and thus the function only returns the last two. You need to combine the original portion with the replaced portion.

df = pd.DataFrame([
'AZBYCCCD0',
'NZBY23HG1',
'BZYCQ05CO',
'YODZ225H0',
pd.np.NaN,
'CS45DRNZQ',], columns = ['Col1'])

repl = {'0':'O','1':'I'}
df['Col1'].astype(str).str[:7] + df['Col1'].astype(str).str[7:].replace(repl, regex=True)

Which returns as expected:

0    AZBYCCCDO
1    NZBY23HGI
2    BZYCQ05CO
3    YODZ225HO
4          nan
5    CS45DRNZQ
Name: Col1, dtype: object

Can be done via replace: Modify the regex and lambda function if required:

repl = {'0':'O','1':'I'}
df['Col1'] = df['Col1'].str[:7] + df['Col1'].str[7:].str.replace(r'0|1', lambda x : repl[x.group(0)], regex=True)
#or
df['Col1'] = df['Col1'].str[:7] + df['Col1'].str[7:].replace(repl, regex=True)

I think you can try something like this (assuming you are working on one word at a time):

repl = {'0':'O','1':'I', '5':'S'}

def func1(string):
 str_list = list(string)
 for i in range(len(str_list)):
  if str_list[i] in repl:
   str_list[i] = repl[str_list[i]]
 string = "".join(str_list)
 return string

I think this should work. It does not require any import.

x="Col1,AZBYCCCD0,NZBY23HG1,BZYCQ05CO,YODZ225H0,NaN,CS45DRNZQ"
d=x.split(",")
for j in d:
    print("Original Word: ",j.strip())
    last_chars=str(j[-3:])
    j=j.strip(last_chars)
    if "0" in last_chars:
        last_chars=last_chars.replace("0","O")
    if "1" in last_chars:
        last_chars=last_chars.replace("1","I")
    
    #print(last_chars)
    print("New Word: "+j+last_chars)
Related