numpy.choose#

numpy.choose(a, choices, out=None, mode='raise')[源代码]#

从索引数组和要选择的数组列表中构造一个数组。

首先,如果您感到困惑或不确定,请务必查看示例 -在其完全通用的情况下,此函数比以下代码描述所显示的要简单。

np.choose(a,c) == np.array([c[a[I]][I] for I in np.ndindex(a.shape)])

但这省略了一些细节。以下是完全通用的摘要

给定一个整数“索引”数组(a)和一组n个数组(choices),a和每个选择数组将首先根据需要广播到公共形状的数组;我们称这些为BaBchoices[i], i = 0,…,n-1,并且对于每个iBa.shape == Bchoices[i].shape。然后,将创建一个形状为Ba.shape的新数组,如下所示:

  • 如果mode='raise'(默认值),那么,首先,a(因此Ba)的每个元素都必须在[0, n-1]范围内;现在,假设i(在该范围内)是Ba(j0, j1, ..., jm)位置的值 - 那么新数组中相同位置的值就是Bchoices[i]中相同位置的值;

  • 如果mode='wrap'a(因此Ba)中的值可以是任何(有符号)整数;使用模运算将超出[0, n-1]范围的整数映射回该范围;然后按上述方式构造新数组;

  • 如果mode='clip'a(因此Ba)中的值可以是任何(有符号)整数;负整数映射到0;大于n-1的值映射到n-1;然后按上述方式构造新数组。

参数:
a整数数组

此数组必须包含[0, n-1]中的整数,其中n是选择的数量,除非mode=wrapmode=clip,在这种情况下,任何整数都是允许的。

choices选择的数组序列

选择数组。a和所有选择都必须可广播到相同的形状。如果choices本身是一个数组(不推荐),那么其最外层维度(即对应于choices.shape[0])被视为定义“序列”。

outarray, optional

如果提供了,结果将插入到此数组中。它应该具有适当的形状和dtype。请注意,如果mode='raise'out始终会被缓冲;使用其他模式可获得更好的性能。

mode{‘raise’(默认),‘wrap’,‘clip’},可选

指定如何处理[0, n-1]范围外的索引

  • ‘raise’:引发异常

  • ‘wrap’:值变为值模n

  • ‘clip’:值 < 0 映射到 0,值 > n-1 映射到 n-1

返回:
merged_array数组

合并的结果。

引发:
ValueError:形状不匹配

如果a和每个选择数组都不能广播到相同的形状。

另请参阅

ndarray.choose

等效方法

numpy.take_along_axis

如果choices是数组,则首选

备注

为了减少误解的可能性,尽管以下“滥用”名义上受支持,但choices不应被视为单个数组,即最外层的类似序列的容器应该是列表或元组。

示例

>>> import numpy as np
>>> 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

几个例子,说明choose如何广播

>>> 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]]])