'Set Element in Array 1 to Zero, if corresponding Element in Array 2 is less than Threshold

and I am looking for some hints on how to get my problem start.

arr1 = [1, 3, 5, 9, 4]

arr2 = [5, 8, 2, 3, 9]

How can I set the elements in arr1 to 0, if the corresponding element in arr2 <= threshold.

Threshold = 5

Expected output.

new_arr = [1, 3, 0, 0, 4]

I will eventually scale this to 3D arrays.

Thanks in Advance



Solution 1:[1]

Assuming you are talking about numpy arrays due to your tags and not list you have multiple options. If you want to create a new array, you can do

arr2 = np.array(arr2)
arr1 = np.array(arr1)
new_array = np.where(arr2 <= threshold, 0, arr1)

where np.where selects 0 whenever the condition is True, otherwise the entry of the other array at that index.

If you want to change those values to 0 in the source array, you can use logical indexing

arr1[arr2 <= threshold] = 0

Solution 2:[2]

Use zip and a list comprehension:

arr1 = [a if b>=5 else 0 for a,b in zip(arr1, arr2)]

Or to modify arr1 in place:

arr1[:] = [a if b>=5 else 0 for a,b in zip(arr1, arr2)]

Output: [1, 3, 0, 0, 4]

Solution 3:[3]

As written, your arr1 and arr2 appears to be lists, but since you've added NumPy as a tag I will assume that they in fact are NumPy arrays:

import numpy as np
arr1 = np.array([1, 3, 5, 9, 4])
arr2 = np.array([5, 8, 2, 3, 9])

(if you print(arr1) you indeed get what you write). You can now simply do

threshold = 5
arr1[arr2 < threshold] = 0

Read it like "set the elements within arr1 for which the corresponding values in arr2 are less than threshold to 0".

This will work with multi-dimensional NumPy arrays as well.

To better understand what's actually going on, you can try play around with just arr2 < threshold. Try print it out:

print(arr2 < threshold)

This is referred to as a mask. It is in fact itself a (boolean) NumPy array:

mask = arr2 < threshold
mask[0] = True  # make a change!
arr1[mask] = 42  # now apply the mask

Note that in the above examples, arr1 itself is changed (or mutated). That is, the original data within arr1 is not kept. If you want to keep arr1, take a backup first, or equivalently copy arr1 to a new array and use that:

import numpy as np

arr1 = np.array([1, 3, 5, 9, 4])
arr2 = np.array([5, 8, 2, 3, 9])

arr3 = arr1.copy()
arr3[arr2 < threshold] = 0  # mutate arr3, keeping arr1 as is

Solution 4:[4]

Assuming numpy arrays, your problem can be solved by:

threshold = 5

new_arr = arr1*(arr2 >= threshold)

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 Simon Hawe
Solution 2
Solution 3 jmd_dk
Solution 4 dfull