Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply conditional statement in numpy array?

I am trying to apply conditional statements in a numpy array and to get a boolean array with 1 and 0 values.

I tried so far the np.where(), but it allows only 3 arguments and in my case I have some more.

I first create the array randomly:

numbers = np.random.uniform(1,100,5)

Now, if the value is lower then 30, I would like to get a 0. If the value is greater than 70, I would like to get 1. And if the value is between 30 and 70, I would like to get a random number between 0 and 1. If this number is greater than 0.5, then the value from the array should get 1 as a boolean value and in other case 0. I guess this is made again with the np.random function, but I dont know how to apply all of the arguments.

If the input array is:

[10,40,50,60,90]

Then the expected output should be:

[0,1,0,1,1]

where the three values in the middle are randomly distributed so they can differ when making multiple tests.

Thank you in advance!

like image 566
Nick Avatar asked Oct 14 '25 18:10

Nick


1 Answers

Use numpy.select and 3rd condition should should be simplify by numpy.random.choice:

numbers = np.array([10,40,50,60,90])
print (numbers)
[10 40 50 60 90]

a = np.select([numbers < 30, numbers > 70], [0, 1], np.random.choice([1,0], size=len(numbers)))
print (a)
[0 0 1 0 1]

If need 3rd condition with compare by 0.5 is possible convert mask to integers for True, False to 1, 0 mapping:

b = (np.random.rand(len(numbers)) > .5).astype(int)
#alternative
#b = np.where(np.random.rand(len(numbers)) > .5, 1, 0)

a = np.select([numbers < 30, numbers > 70], [0, 1], b)

Or you can chain 3 times numpy.where:

a = np.where(numbers < 30, 0,
    np.where(numbers > 70, 1, 
    np.where(np.random.rand(len(numbers)) > .5, 1, 0)))

Or use np.select:

a = np.select([numbers < 30, numbers > 70, np.random.rand(len(numbers)) > .5], 
               [0, 1, 1], 0)
like image 131
jezrael Avatar answered Oct 17 '25 06:10

jezrael



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!