Home > OS >  replace value in one column without using replace() function
replace value in one column without using replace() function

Time:02-19

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

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)
  • Related