4

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!

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks you! I have never used the np.select so far. Will take a closer look to this function :)
Well, and for numbers between 30 and 70, we use the np.random function. So far, so good. But then if they get a value lower or equal than 0.5, the boolean value should be 0. If they get a value greater than 0.5, then they obtain the value 1.

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.