3

I've got some Python code I'm trying to optimize. It deals with two 2D arrays of identical size (their size can be arbitrary). The first array is full of arbitrary Boolean values, and the second is full of semi-random numbers between 0 and 1.

What I'm trying to do is change the binary values based on the values in the modifier array. Here's a code snippet that works just fine and encapsulates what I'm trying to do within two for-loops:

import numpy as np
xdim = 3
ydim = 4
binaries = np.greater(np.random.rand(xdim,ydim), 0.5)
modifier = np.random.rand(xdim,ydim)

for i in range(binaries.shape[0]):
    for j in range(binaries.shape[1]):
        if np.greater(modifier[i,j], 0.2):
            binaries[i,j] = False

My question: is there a better (or more proper) way to do this? I'd rather use things like slices instead of nested for loops, but the comparisons and Boolean logic make me think that this might be the best way.

1 Answer 1

6
binaries &= ~(modifier > 0.2)

modifiler > 0.2 create a binary array, ~ operator does boolean not, and &= does boolean and.

NOTE ~ &= are bitwise operators, but you can use them as boolean operators.

Sign up to request clarification or add additional context in comments.

2 Comments

Nice. Thanks. I didn't know about the &= operator.
+1 I thought it would be faster to assign False to items meeting the condition, i.e. 'binaries[modifier > 0.2] = False, than &-ing both arrays, but your answer is about 10x faster. It's of course a little faster if you do binaries &= modifier <= 0.2`.

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.