I want to replace string without using replace() function.
Only want to use pandas and numpy.
sample data:
# df
Col1
ab1
de4
The logic of replace is:
awill beibwill begdwill bemewill bet1will be24will be3
Is there any way that I can create a dictionary and use this to identify and replace?
# df
Col1 Col2
ab1 ig2
de4 mt3
>Solution :
You can use translate.
mapping = 'abde14'.maketrans({
'a': 'i',
'b': 'g',
'd': 'm',
'e': 't',
'1': '2',
'4': '3'
})
df['Col2'] = df.Col1.str.translate(mapping)
If it is always mapping to 1 character, this syntax might be more compact.
mapping = str.maketrans('abde14', 'igmt23')