Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimizing Boolean Compares Between Arrays with Python

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.

like image 982
Nick Avatar asked Dec 02 '25 12:12

Nick


1 Answers

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.

like image 188
HYRY Avatar answered Dec 04 '25 05:12

HYRY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!