You can use pd.Series.str.replace which is similar to re.sub, you can pass a function to repl param.
from random import randint
from string import ascii_uppercase
mapping = {char:str(randint(0, 9)) for char in ascii_uppercase}
#{'A': '1', 'B': '3', 'C': '1', 'D': '1', 'E': '4', 'F': '9', 'G': '9', 'H': '5',
#'I': '8', 'J': '0', 'K': '0', 'L': '1', 'M': '5', 'N': '3', 'O': '8', 'P': '5',
#'Q': '5', 'R': '8', 'S': '9', 'T': '8', 'U': '0', 'V': '8', 'W': '1', 'X': '6',
#'Y': '7', 'Z': '5'}
def repl(match):
return ''.join(mapping[char] for char in match.group(0))
df['StockCode'] = df['StockCode'].str.replace(r"[A-Z]{,3}$", repl)
df
InvoiceNo StockCode
0 536 85123
1 536 710535 # 'Z' -> 5
2 536 844063 # 'B' -> 3
3 536 226239 # 'S' -> 9
When there is more than one alphabet at the end.
df = pd.DataFrame({
'InvoiceNo':536,
'StockCode':['85123', '71053ZAZ', '84406BAR', '22623BIR']
})
df['StockCode'] = df['StockCode'].str.replace(r"[A-Z]{,3}$", repl)
InvoiceNo StockCode
0 536 85123
1 536 71053515 # 'ZAZ' -> '515'
2 536 84406318 # 'BAR' -> '318'
3 536 22623388 # 'BIR' -> '388'
z, with what number you want to replacez?1?..2?...3??...4??? or you want to replace with any number randomly?