2

I want to transform some of the array values to other values, based on mapping dictionary, using numpy's array programming style, i.e. without any loops (at least in my own code). Here's the code I came up with:

>>> characters
# Result: array(['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'])
mapping = {'a':'0', 'b':'1', 'c':'2'}
characters = numpy.vectorize(mapping.get)(characters)

So basically I want to replace every 'a' letter with '0' etc. But it doesn't work due to the fact that I want only some of the values to be replaced so I didn't provide mapping for every letter. I could always use a loop that iterates over the dictionary entries and substitutes new values in the array, based on mapping, but I'm not allowed to use loops..

Do you have any ideas how could I tackle it using this array programming style?

3
  • So are you converting the index? like index 0 goes to 'a'? Or the other way around, 'a'a become '0's? Maybe you could post an expected output ;-) Commented Nov 22, 2019 at 19:54
  • Could you add an output that actually replaces something? Commented Nov 22, 2019 at 19:54
  • I added explanation, I just wanted to replace every letter 'a' with '0' etc. Commented Nov 22, 2019 at 20:19

1 Answer 1

1

IIUC, you just need to provide a default value for get, otherwise the result is None. This can be done using a lambda function, for example:

import numpy as np

characters = np.array(['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'])
mapping = {'a': '0', 'b': '1', 'c': '2'}

translate = lambda x: mapping.get(x, x)

characters = np.vectorize(translate)(characters)

print(characters)

Output

['H' 'e' 'l' 'l' 'o' ' ' 'W' 'o' 'r' 'l' 'd']

For:

characters = np.array(['H', 'a', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'])

Output

['H' '0' 'l' 'l' 'o' ' ' 'W' 'o' 'r' 'l' 'd']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.