How to do this search or replace numpy array?

I have a numpy 2D array, A containing an index into another array, B What is a good way to get C from A and B using numpy?

 A = array([[1, 1, 0, 2], [1, 0, 0, 2], [1, 1, 0, 2]]) B = array([0, 5, 3]) C = array([[5, 5, 0, 3], [5, 0, 0, 3], [5, 5, 0, 3]]) 
+4
source share
2 answers

How about this C = B[A] . What is the beauty of numpy:

 In [1]: import numpy as np In [2]: A = np.array([[1, 1, 0, 2], ...: [1, 0, 0, 2], ...: [1, 1, 0, 2]]) In [3]: B = np.array([0, 5, 3]) In [4]: B[A] Out[4]: array([[5, 5, 0, 3], [5, 0, 0, 3], [5, 5, 0, 3]]) 
+8
source
 x,y = a.shape for i in range(x): for j in range(y) c[i][j] = b[a[i][j]] 
-1
source

Source: https://habr.com/ru/post/1381963/


All Articles