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 和每个 choice 数组首先被广播(如有必要)到具有公共形状的数组;调用这些 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',则 a (以及 Ba )中的值可以是任何(有符号)整数;模运算用于将 [0, n-1] 范围之外的整数映射回该范围;然后如上构造新数组;如果
mode='clip',则 a (以及Ba)中的值可以是任何(有符号)整数;负整数映射为 0;大于n-1的值映射为n-1;然后如上构造新数组.
- 参数:
- a整型数组
该数组必须包含
[0, n-1]中的整数,其中n是选择的数量,除非mode=wrap或mode=clip,在这种情况下,任何整数都是允许的.- choices数组序列
选择数组. a 和所有选择必须可广播到相同的形状. 如果 choices 本身是一个数组(不推荐),那么它的最外层维度(即,对应于
choices.shape[0]的维度)被视为定义“序列”.- outarray,可选
如果提供,结果将插入到此数组中. 它应具有适当的形状和 dtype. 请注意,如果
mode='raise',则始终会缓冲 out ;使用其他模式以获得更好的性能.- 模式{‘raise’ (默认), ‘wrap’, ‘clip’}, 可选
指定如何处理
[0, n-1]之外的索引:‘raise’ : 引发异常
‘wrap’ : 值变为 value mod
n‘clip’ : 值 < 0 映射到 0,值 > n-1 映射到 n-1
- 返回:
- merged_arrayarray
合并后的结果.
- 提出:
- 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]]])