numpy.where()在以numpy.where(数组条件,数组1,数组2)的形式输入时如何工作?

时间:2017-09-03 15:43:19

标签: python arrays python-3.x numpy where

我希望有人可以就numpy.where()函数的工作方式提供一些说明。在尝试了几个不同的输入后,我无法绕过它。以下面的第一个例子为例,输出:

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

是:

array([1, 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])

1 个答案:

答案 0 :(得分:1)

如果给np.where提供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等价物),它也不支持广播或多维数组和单参数形式,但我希望它有助于理解3参数形式np.where