gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:32:44 25 4
gpt4 key购买 nike

我正在尝试在一个 numpy 数组中应用条件语句并获取一个包含 1 和 0 值的 bool 数组。

到目前为止,我尝试了 np.where(),但它只允许 3 个参数,而在我的例子中,我还有更多参数。

我首先随机创建数组:

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

现在,如果值低于 30,我想得到 0。如果值大于 70,我想得到 1。如果值在 30 到 70 之间,我想得到一个介于 0 和 1 之间的随机数。如果这个数字大于 0.5,那么数组中的值应该得到 1 作为 bool 值,在其他情况下为 0。我想这是用 np.random 函数再次制作的,但是我不知道如何应用所有参数。

如果输入数组是:

[10,40,50,60,90]

那么预期的输出应该是:

[0,1,0,1,1]

中间的三个值是随机分布的,因此在进行多次测试时它们可以不同。

提前致谢!

最佳答案

使用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]

如果需要 3rd 条件与 0.5 进行比较,则可以将掩码转换为整数,将 True、False 转换为 1、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)

或者你可以链3次numpy.where :

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

或者使用np.select:

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

关于python - 如何在 numpy 数组中应用条件语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57017165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com