原文:https://docs.scipy.org/doc/numpy/reference/generated/numpy.choose.html
校对:(虚位以待)
numpy.
choose
(a, choices, out=None, mode='raise')[source]从索引数组和一组数组构造数组以供选择。
首先,如果混淆或不确定,肯定看看例子 - 在它的完全通用性,这个函数不如下面的代码描述简单(下面ndi = numpy.lib.index_tricks
):
np.choose(a,c) == np.array([c[a[I]][I] for I in ndi.ndindex(a.shape)])
.
但这里省略了一些细微之处。这里是一个完全一般的总结:
Given an “index” array (a) of integers and a sequence of n arrays (choices), a and each choice array are first broadcast, as necessary, to arrays of a common shape; calling these Ba and Bchoices[i], i = 0,...,n-1 we have that, necessarily, Ba.shape == Bchoices[i].shape
for each i. 然后,创建形状为Ba.shape
的新数组,如下所示:
mode=raise
(默认),则首先,a(并且因此Ba)的每个元素必须在范围[0,n-1];现在,假设i(在该范围内)是中(j0,j1,...,jm) - 则新数组中相同位置处的值是在相同位置的Bchoices [i]中的值;mode=wrap
,则a(因此Ba)中的值可以是任何模运算用于将范围[0,n-1]之外的整数映射回该范围;然后新数组如上构建;mode=clip
,则a(因此Ba)中的值可以是任何负整数映射到0;大于n-1的值映射到n-1;然后如上构造新的数组。参数: | a:int数组
choices:数组的序列
out:数组,可选
mode:{'raise'(默认值),'wrap','clip'},可选
|
---|---|
返回: | merged_array:数组
|
上升: | ValueError:shape mismatch
|
也可以看看
ndarray.choose
笔记
为了减少误解的可能性,即使下面的“滥用”被名义上支持,选择既不应该也不应被认为是单个数组,即,最外层序列容器应该是列表或元组。
例子
>>> 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]]])