I'm trying to add the values of a small 2D numpy array ("source") into a larger 2D numpy array ("frame"), starting at a specific position in the frame-array ("pos_x" , "pos_y"). Right now, I have two for-loops adding the source-value to the frame-value at each position:
for i in range(x):
for j in range(y):
frame[pos_x+i][pos_y+j] += source[i][j]
("x" and "y" being the source-arrays' shape)
However, the arrays are quite large (the frame array shape: 5000x8000, and the source array shape: 1000x5000). So this process takes quite long (ca. 15 seconds).
Is there any way to speed up this process, either through list comprehension, or mapping, or anything else?
I've tried list comprehension like this with multiple statements and assignments:
frame = [[frame[pos_x+i][pos_y+j] + source[i][j] for j in range(y)] for i in range(x)]
(adapted from the Threads: How can I do assignments in a list comprehension? and Multiple statements in list compherensions in Python?)
but it takes just as long as the original for-loops.
Another idea was to only allow the loop for non-zero values with if source[i][j] != 0
. But when I tried that, it took over three times as long (potential sub-question: any idea why?).