简体   繁体   English

如何在numpy数组中应用条件语句?

[英]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. 我试图在一个numpy数组中应用条件语句,并获得一个值为1和0的布尔数组。

I tried so far the np.where(), but it allows only 3 arguments and in my case I have some more. 我到目前为止尝试了np.where(),但它只允许3个参数,在我的情况下我还有更多参数。

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. 现在,如果该值低于30,我想得到0.如果该值大于70,我想得到1.如果值在30到70之间,我想得到一个随机的数字介于0和1之间。如果此数字大于0.5,则数组中的值应为1作为布尔值,在其他情况下为0.我想这是使用np.random函数再次进行的,但我不知道如何应用所有参数。

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! 先感谢您!

Use numpy.select and 3rd condition should should be simplify by numpy.random.choice : 使用numpy.select和第三个条件应该由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: 如果需要3rd条件与0.5比较可能将掩码转换为整数为True, False1, 0映射:

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 : 或者你可以连锁3次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 : 或者使用np.select

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM