How can I map each value of an integer NumPy array to a list according to a lambda function?
I have the following code:
x = [0, 1, 2, 0, 0, 2, 1, 1]
colours = [[0, 0, 0], [255, 0, 0], [0, 255, 0], [0, 0, 255]]
coloured = lambda v: colours[int(v)]
vcoloured = np.vectorize(coloured)
x_color = vcoloured(x) # throws ValueError: setting an array element with a sequence.
# would like to get x_color = [[0, 0, 0], [255, 0, 0], [0, 255, 0], [0, 0, 0], [0, 0, 0], [0, 255, 0], [255, 0, 0], [255, 0, 0]]
Don't bother with lists at all. If you have numpy arrays, it's much faster to use the power of numpy:
>>> x = np.array([0, 1, 2, 0, 0, 2, 1, 1])
>>> colors = np.array([[0, 0, 0], [255, 0, 0], [0, 255, 0], [0, 0, 255]])
>>> x_color = colors[x]
>>> x_color
array([[ 0, 0, 0],
[255, 0, 0],
[ 0, 255, 0],
[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 255, 0],
[255, 0, 0],
[255, 0, 0]])
Yeah, I went ahead and Americanized your spelling, but functionally, the array x_colored will behave just like a list for all practical purposes. If you absolutely need a list, just call tolist on the result:
x_color = colors[x].tolist()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With