I have a numpy array:
a = [[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]]
I have a dictionary with values I want to substitute/map:
d = { 0 : ( 000, 001 ),
1 : ( 100, 101 ),
2 : ( 200, 201 ),
3 : ( 300, 301 ),
4 : ( 400, 401 )}
So that I end up with:
a = [[(000, 001) (100, 101) (200, 201) (300, 301) (400, 401)]
[(000, 001) (100, 101) (200, 201) (300, 301) (400, 401)]
[(000, 001) (100, 101) (200, 201) (300, 301) (400, 401)]]
According to this SO answer, one way to do a value map based on a dictionary is:
b = np.copy( a )
for k, v in d.items(): b[ a == k ] = v
This works when the key and value are of the same data type. But in my case, the key is an int
while the new value is a tuple (of ints)
. Accordingly, I get a cannot assign 2 input values
error.
Instead of b = np.copy( a )
, I have tried:
b = a.astype( ( np.int, 2 ) )
However, I get the reasonable error of ValueError: could not broadcast input array from shape (3,5) into shape (3,5,2)
.
So, how can I go about mapping ints to tuples in a numpy array?