【问题标题】:How to apply conditional statement in numpy array?如何在numpy数组中应用条件语句?
【发布时间】:2019-11-22 19:45:49
【问题描述】:

我正在尝试在一个 numpy 数组中应用条件语句并获得一个具有 1 和 0 值的布尔数组。

到目前为止,我尝试了 np.where(),但它只允许 3 个参数,在我的情况下我还有一些。

我先随机创建数组:

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

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

如果输入数组是:

[10,40,50,60,90]

那么预期的输出应该是:

[0,1,0,1,1]

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

提前谢谢你!

【问题讨论】:

    标签: python pandas conditional-statements numpy-ndarray


    【解决方案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, 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)
    

    或者你可以链接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)
    

    【讨论】:

    • 谢谢!到目前为止,我从未使用过 np.select。将仔细研究此功能:)
    • 好吧,对于 30 到 70 之间的数字,我们使用 np.random 函数。到目前为止,一切都很好。但是如果他们得到一个小于或等于 0.5 的值,布尔值应该是 0。如果他们得到一个大于 0.5 的值,那么他们得到的值是 1。
    猜你喜欢
    • 2021-06-04
    • 2019-12-31
    • 1970-01-01
    • 2020-02-28
    • 2015-08-16
    • 1970-01-01
    • 2021-08-26
    • 2020-11-21
    相关资源
    最近更新 更多