Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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 :

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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading