NumPy参考 >例行程序 >Indexing routines > numpy.choose
numpy.
choose
(a,options,out = None,mode ='raise' )[源代码] ¶从索引数组和一组数组中构造一个数组以供选择。
首先,如果感到困惑或不确定,请务必看一下示例-完全具有通用性,此函数不如下面的代码描述(ndi =下方numpy.lib.index_tricks
)看起来那么简单
:
np.choose(a,c) == np.array([c[a[I]][I] for I in ndi.ndindex(a.shape)])
。
但这忽略了一些微妙之处。这是一个完全概括的摘要:
给定一个由整数组成的“索引”数组(a)和一个n个数组(choices)的序列,根据需要,首先将a和每个choice数组广播到具有共同形状的数组;称这些Ba和Bchoices [i],i = 0,…,n-1,
对于每个i,我们必然有它。然后,创建具有形状的新数组,如下所示:Ba.shape == Bchoices[i].shape
Ba.shape
如果mode=raise
(缺省值),那么,首先,每个元件
一个(并且因此巴)必须在范围[0,N-1] ; 现在,假设
i(在该范围内)是Ba中(j0,j1,…,jm)位置处的值-那么新数组中相同位置处的值就是Bchoices [i]中相同位置处的值位置;
如果mode=wrap
,在值一(并因此钡)可以是任何(签字)整数; 模算术用于将[0,n-1]范围以外的整数映射
回该范围;然后按照上面的方法构造新数组;
如果mode=clip
,在值一(并因此钡)可以是任何(签字)整数; 负整数映射到0;大于n-1的值
映射到n-1;然后按上述方法构造新数组。
此数组必须包含[0,n-1]中的整数,其中n是选择的数目,除非mode=wrap
或mode=clip
,在这种情况下,任何整数都是允许的。
选择数组。一个和所有的选择都必须broadcastable相同的形状。如果choices本身是一个数组(不建议使用),则将其最外面的维度(即与对应的维度
choices.shape[0]
)视为定义“序列”。
如果提供,结果将被插入此数组。它应该具有适当的形状和dtype。注意,如果mode ='raise',则out总是被缓冲;使用其他模式以获得更好的性能。
指定如何处理[0,n-1]以外的索引:
'raise':引发异常
'wrap':值变成值mod n
'clip':值<0映射为0,值> n-1映射为n-1
合并结果。
如果一个和每一个选择阵列是不是所有broadcastable到相同的形状。
也可以看看
ndarray.choose
等效方法
numpy.take_along_axis
如果options是数组,则更可取
笔记
为了减少误解的机会,即使名义上支持以下“滥用”,选择也不应该也不应被视为单个数组,即,最外层的类似序列的容器应该是列表或元组。
例子
>>> 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]]])