Python 当以numpy.where(数组条件,array1,array2)的形式输入时,numpy.where()是如何工作的?

Python 当以numpy.where(数组条件,array1,array2)的形式输入时,numpy.where()是如何工作的?,python,arrays,python-3.x,numpy,where,Python,Arrays,Python 3.x,Numpy,Where,我希望有人能澄清一下numpy.where()函数是如何工作的。在尝试了几个不同的输入之后,我无法对它进行控制。以下面的第一个示例为例,输出: np.where([True,False],[1,0],[3,4]) 是: 布尔值数组应用于数组[1,0]和[3,4]以产生输出的准确程度如何 一些附加测试的结果如下所示: import numpy as np np.where([True,False],[1,0],[3,4]) Out[129]: array([1, 4]) np.where([

我希望有人能澄清一下
numpy.where()
函数是如何工作的。在尝试了几个不同的输入之后,我无法对它进行控制。以下面的第一个示例为例,输出:

np.where([True,False],[1,0],[3,4])
是:

布尔值数组应用于数组
[1,0]
[3,4]
以产生输出的准确程度如何

一些附加测试的结果如下所示:

import numpy as np

np.where([True,False],[1,0],[3,4])
Out[129]: array([1, 4])

np.where([True,False],[1,0],[6,4])
Out[130]: array([1, 4])

np.where([True,False],[1,0],[0,0])
Out[131]: array([1, 0])

np.where([True,False],[0,0],[0,0])
Out[132]: array([0, 0])

np.where([True,False],[1,0],[0,12])
Out[133]: array([ 1, 12])

np.where([True,False],[1,6],[4,12])
Out[134]: array([ 1, 12])

np.where([True,True],[1,6],[4,12])
Out[135]: array([1, 6])

np.where([False,False],[1,6],[4,12])
Out[136]: array([ 4, 12])

np.where([True,False],[1,0],[3,4])
Out[137]: array([1, 4])

np.where([True,True],[1,0],[3,4])
Out[138]: array([1, 0])

np.where([True,True],[1,0],[3,4])
Out[139]: array([1, 0])

np.where([True,False],[1,0],[3,4])
Out[140]: array([1, 4])

如果您为
np提供3个参数,其中
第一个参数是一个条件,它决定结果中的对应值是从第二个参数(如果条件中的值是
True
)还是从第三个参数(如果条件中的值是
False
)获取的

因此,当所有值均为
True
时,它将是第一个参数的副本,如果所有值均为
False
时,它将是第二个参数的副本。如果它们混合在一起,则为组合

将其视为更复杂的版本:

def where(condition, x, y):
    result = []
    for idx in range(len(condition)):
        if condition[idx] == True:
            result.append(x[idx])
        else:
            result.append(y[idx])
    return result

该函数当然要慢得多(甚至不是最快的纯Python等效函数),它也不支持广播或多维数组以及单参数形式,但我希望它有助于理解
np的3参数形式。where

非常感谢。这正是我的困惑所在。
def where(condition, x, y):
    result = []
    for idx in range(len(condition)):
        if condition[idx] == True:
            result.append(x[idx])
        else:
            result.append(y[idx])
    return result