2

I have a 2d numpy array and a 2d numpy subarray that I want to add to the original array based on a condition. I know that you can add the 2d subarray to the array like this:

original_array[start_x:end_x, start_y:end_y] = sub_array 

but I dont know how to efficiently add only values of the sub_array that are bigger than 0?

Example:

orginal_array = np.array([2,2],[2,2],[2,2],[2,2])
sub_array = np.array([0,0],[1,1],[0,1],[0,0])
expected_result = np.array([2,2], [1,1], [2,1], [2,2])
1
  • Please update the question with 1) an example of the array, 2) an example of the sub array and 3) an example of the expected output. Cheers. Commented Oct 9, 2020 at 8:21

3 Answers 3

1

You can index based on the condition >,< 0 and add the arrays.

orginal_array * (sub_array <= 0) + sub_array * (sub_array > 0)

array([[2, 2],
       [1, 1],
       [2, 1],
       [2, 2]])
Sign up to request clarification or add additional context in comments.

Comments

1

Another approach is to use the np.where function as:

np.where(sub_array > 0, sub_array, original_array)

Output:

array([[2, 2], 
       [1, 1], 
       [2, 1], 
       [2, 2]])

Comments

-1

Try,

sub_array2 = np.select([sub_array>0],[sub_array])
original_array[start_x:end_x, start_y:end_y] = sub_array2 

1 Comment

Unfortunately that does not work as expected. I want the values in the original array stay the same, if the values in the subarray are 0 or less than 0. Look at my updated question

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.