'replace value in one column without using replace() function

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:

  1. a will be i
  2. b will be g
  3. d will be m
  4. e will be t
  5. 1 will be 2
  6. 4 will be 3

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 1:[1]

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 renatomt