2

I have a numpy array arr containing 0s and 1s,

arr = np.random.randint(2, size=(800,800))

Then I casted it to astype(np.float32) and inserted various float numbers at various positions. In fact, what I would like to do is insert those float numbers only where the original array had 1 rather than 0; where the original array had 0 I want to keep 0.

My thought was to take a copy of the array (with .copy()) and reinsert from that later. So now I have arr above (1s and 0s), and a same-shaped array arr2 with numerical elements. I want to replace the elements in arr2 with those in arr only where (and everywhere where) the element in arr is 0. How can I do this?

Small example:

arr = np.array([1,0],
               [0,1])
arr2 = np.array([2.43, 5.25],
                [1.54, 2.59])

Desired output:

arr2 = np.array([2.43, 0],
                [0, 2.59])

N.B. should be as fast as possible on arrays of around 800x800

2
  • Please provide the code that you have worked on. Commented Apr 16, 2021 at 14:52
  • arr2 * arr ? Commented Apr 16, 2021 at 15:01

2 Answers 2

1

Simply do:

arr2[arr == 0] = 0

or

arr2 = arr2 * arr
Sign up to request clarification or add additional context in comments.

3 Comments

Fastest method wins (arr2 = arr2*arr)
Even faster: arr2 *= arr
Nice! Forgot that inplace operations can be used here to further optimize this.
1

@swag2198 is correct, an alternative is below

Numpy has a functin called 'where' which allows you to set values based on a condition from another array - this is essentially masking

below will achieve what you want - essentially it will return an array the same dimensions as arr2, except wherever there is a zero in arr, it will be replaced with zero

arr = np.array([[1,0],[0,1]])
arr2 = np.array([[2.43, 5.25],
                [1.54, 2.59]])


arr_out = np.where(arr, arr2, 0)

the advantage of this way is that you can pick values based on two arrays if you wish - say you wanted to mask an image for instance - replace the background

Comments

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.