简体   繁体   中英

add numpy subarray to numpy array based on condition

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

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

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

Try,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM