Fastest way to replace all elements in a numpy array
I am trying to find the fastest way to replace elements from a numpy array with elements from another using a matching rule. I will give you an example because I think it will be most clear this way.
Let's say we have these 3 arrays:
data = np.array([[1,2,3], [4,5,6], [7,8,9], [1,2,3], [7,5,6]])
map = np.array([0, 0, 1, 0, 1])
trans = np.array([[10,10,10], [20,20,20]])
The array map
indicates the desired match between data
and trans
.
I want to get the result:
array([[11, 12, 13], [14, 15, 16], [27, 28, 29], [11, 12, 13], [27, 25, 26]])
Each element in the array written above is the sum between the element in data
and the corresponding element in trans
.
I try to avoid for loops
, because actually my arrays data
and are trans
much larger, but cannot find a suitable vector function.
could you help me?
source to share
Index in trans
with indices from map
to select rows off trans
based on indices, which act as indices of rows to select, then just add with data
-
data+trans[map]
Make edits in place -
data += trans[map]
Caution: I would use a different variable name than map
for the mapping array, which is also Python built-in
, to avoid any unwanted behavior.
Example run -
In [23]: data = np.array([[1,2,3], [4,5,6], [7,8,9], [1,2,3], [7,5,6]])
...: map1 = np.array([0, 0, 1, 0, 1])
...: trans = np.array([[10,10,10], [20,20,20]])
...:
In [24]: trans[map1]
Out[24]:
array([[10, 10, 10],
[10, 10, 10],
[20, 20, 20],
[10, 10, 10],
[20, 20, 20]])
In [25]: data + trans[map1]
Out[25]:
array([[11, 12, 13],
[14, 15, 16],
[27, 28, 29],
[11, 12, 13],
[27, 25, 26]])
source to share