3

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.

2
  • are your inverse_slice indices always found in a rectangle shape? Commented Apr 1, 2022 at 14:11
  • 1
    @lemon yes, they are always rectangular Commented Apr 1, 2022 at 16:57

2 Answers 2

3

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]])
Sign up to request clarification or add additional context in comments.

2 Comments

That seems like a good solution, however there is a bit of memory overhead since you have to copy the entire array, but that is perhaps unavoidable?
You right. I'm sure that there is another way. Let me think.
1

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:, :])

1 Comment

This is probably a viable solution, given the low memory complexity. It's not elegant, but if it works it works!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.