Reputation: 1086
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?
Upvotes: 2
Views: 411
Reputation: 61930
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']
Upvotes: 1