Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 236
Rudy Avatar asked Jan 20 '26 17:01

Rudy


1 Answers

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]])
like image 93
Salvatore Daniele Bianco Avatar answered Jan 22 '26 07:01

Salvatore Daniele Bianco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!