0

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
Peter Chen
  • 1,464
  • 3
  • 21
  • 48
  • Does this answer your question? [Character Translation using Python (like the tr command)](https://stackoverflow.com/questions/555705/character-translation-using-python-like-the-tr-command) – UjinT34 Feb 18 '22 at 19:17
  • but this need `string` package. If I only want to use `pandas` and `numpy`, how to do so? – Peter Chen Feb 18 '22 at 19:20

2 Answers2

2

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')
Emma
  • 8,518
  • 1
  • 18
  • 35
  • Does 'abde14' be the required string before `maketrans()`? – Peter Chen Feb 18 '22 at 19:43
  • oh, seems not necessary. But this was using it, I don't know the difference, though. https://www.geeksforgeeks.org/python-pandas-series-str-translate/ – Emma Feb 18 '22 at 19:44
0

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)
renatomt
  • 288
  • 2
  • 11