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:
a
will bei
b
will beg
d
will bem
e
will bet
1
will be2
4
will 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
CodePudding user response:
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')
CodePudding user response:
You can create your function for it and use apply.
import pandas as pd
df = pd.DataFrame()
df['col'] = ['asdsd', 'xxx', '41xwqa']
def custom_replace(element):
translate_dict = {
'a': 'i',
'b': 'g',
'd': 'm',
'e': 't',
'1': '2',
'4': '3'
}
return_element = ''
for char in element:
try:
return_element = translate_dict[char]
except:
return_element = char
return return_element
df['col'].apply(custom_replace)