从索引数组和一组数组中构造一个数组以供选择。
首先,如果感到困惑或不确定,请务必看一下示例-完全具有通用性,此函数不如下面的代码描述所示简单(在ndi =numpy.lib.index_tricks):
np.choose(a,c) == np.array([c[a[I]][I] for I in ndi.ndindex(a.shape)])。
但这省略了一些微妙之处。这是一个完全概括的摘要:
给定一个整数的“index”数组(a)和n个数组(选择项)的序列,根据需要首先将a和每个选择数组广播到具有共同形状的数组;称这些Ba和Bchoices [i],i = 0,…,n-1,我们必然Ba.shape == Bchoices[i].shape每个i。然后,一个新的形状Ba.shape创建如下:
如果mode=raise(默认值),那么,首先,a(以及Ba)的每个元素都必须在[0,n-1]范围内;现在,假设i(在该范围内)是Ba中(j0,j1,…,jm)位置处的值-那么新数组中相同位置处的值就是Bchoices [i]中相同位置处的值位置;
如果mode=wrap,(因此,Ba)中的值可以是任何(有符号)整数;模算术用于将[0,n-1]范围以外的整数映射回该范围;然后按照上面的方法构造新数组;
如果mode=clip,(因此,Ba)中的值可以是任何(有符号)整数;负整数映射到0;大于n-1的值映射到n-1;然后按上述方法构造新数组。
参数:a: : int array
该数组必须包含[0,n-1]中的整数,其中n是选择的数目,除非mode=wrap或者mode=clip,在这种情况下,任何整数都是允许的。
choices: : sequence of arrays
选择数组。和所有选择必须广播为相同的形状。如果choices本身是一个数组(不建议使用),则其最外面的维度(即对应于choices.shape[0])被视为定义了“sequence”。
out: : array, 可选参数
如果提供,结果将被插入此数组。它应该具有适当的形状和dtype。请注意,如果mode ='raise',则out总是被缓冲;使用其他模式以获得更好的性能。
mode: : {‘raise’ (default), ‘wrap’, ‘clip’}, 可选参数
指定将如何处理[0,n-1]以外的索引:
‘raise’:an exception is raised
‘wrap’:value becomes value mod n
‘clip’:values < 0 are mapped to 0, values > n-1 are mapped to n-1
返回值:merged_array: : 数组
合并结果。
异常:ValueError:shape mismatch:
如果和每个选择数组都不能全部广播为相同形状。
注意:
为了减少误解的机会,即使名义上支持以下“abuse”,也不应将选择视为单个数组,也不应将其视为单个数组,即最外面的sequence-like容器应该是列表或元组。
例子:
>>> choices = [[0, 1, 2, 3], [10, 11, 12, 13],
... [20, 21, 22, 23], [30, 31, 32, 33]]
>>> np.choose([2, 3, 1, 0], choices
... # the first element of the result will be the first element of the
... # third (2+1) "array" in choices, namely, 20; the second element
... # will be the second element of the fourth (3+1) choice array, i.e.,
... # 31, etc.
... )
array([20, 31, 12, 3])
>>> np.choose([2, 4, 1, 0], choices, mode='clip') # 4 goes to 3 (4-1)
array([20, 31, 12, 3])
>>> # because there are 4 choice arrays
>>> np.choose([2, 4, 1, 0], choices, mode='wrap') # 4 goes to (4 mod 4)
array([20, 1, 12, 3])
>>> # i.e., 0
几个示例说明了如何选择广播:
>>> a = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
>>> choices = [-10, 10]
>>> np.choose(a, choices)
array([[ 10, -10, 10],
[-10, 10, -10],
[ 10, -10, 10]])
>>> # With thanks to Anne Archibald
>>> a = np.array([0, 1]).reshape((2,1,1))
>>> c1 = np.array([1, 2, 3]).reshape((1,3,1))
>>> c2 = np.array([-1, -2, -3, -4, -5]).reshape((1,1,5))
>>> np.choose(a, (c1, c2)) # result is 2x3x5, res[0,:,:]=c1, res[1,:,:]=c2
array([[[ 1, 1, 1, 1, 1],
[ 2, 2, 2, 2, 2],
[ 3, 3, 3, 3, 3]],
[[-1, -2, -3, -4, -5],
[-1, -2, -3, -4, -5],
[-1, -2, -3, -4, -5]]])