Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map NumPy integer list values to lists according to lambda function

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]]
like image 320
AfonsoSalgadoSousa Avatar asked Jan 22 '26 20:01

AfonsoSalgadoSousa


1 Answers

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()
like image 66
Mad Physicist Avatar answered Jan 25 '26 08:01

Mad Physicist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!