'NumPy - Updating all values in array, except for slice

I have the following array:

arr = np.array([[1, 1, 1, 1, 1, 1],
            [2, 0, 0, 0, 0, 2],
            [3, 0, 0, 0, 0, 3],
            [4, 4, 4, 4, 4, 4]])

inverse_slice = arr[1:3, 1:5]

I want to update the values of all values in the array, execpt for the values in the slice. For example, this could be multiplying all values with 2, exepct for values in the slice (the rectangle of 0's in this case).

How can I achieve this in an efficient manner?

NOTE: Performance is critical, as the actual array I'm processing is very large, so iteration using Python for-loops is not sufficient.



Solution 1:[1]

Why not this?

arr2 = arr+1000
arr2[1:3, 1:5] = arr[1:3, 1:5]

arr2:

array([[1001, 1001, 1001, 1001, 1001, 1001],
       [1002,    0,    0,    0,    0, 1002],
       [1003,    0,    0,    0,    0, 1003],
       [1004, 1004, 1004, 1004, 1004, 1004]])

Solution 2:[2]

You could do this working by chunks.

Probably not the most elegant way to do it, though you can cycle over the exact cells you need to affect, while keeping a less than O(n^2) complexity depending on the size of the untouched rectangle:

x_min, x_max = (1, 3)
y_min, y_max = (1, 5)
f = <your function>

arr[:x_min, :] = f(arr[:x_min, :])
arr[x_min:x_max, :y_min] = f(arr[x_min:x_max, :y_min])
arr[x_min:x_max, y_max:] = f(arr[x_min:x_max, y_max:])
arr[x_max:, :] = f(arr[x_max:, :])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Salvatore Daniele Bianco
Solution 2 lemon