numpy.
choose
从索引数组和一组要选择的数组构造数组。
首先,如果混淆或不确定,一定要看一下例子——在它的全部概括性中,这个函数并不像下面的代码描述(在ndi下面)中看起来那么简单= numpy.lib.index_tricks ):
numpy.lib.index_tricks
np.choose(a,c) == np.array([c[a[I]][I] for I in ndi.ndindex(a.shape)]) .
np.choose(a,c) == np.array([c[a[I]][I] for I in ndi.ndindex(a.shape)])
但这忽略了一些微妙之处。以下是一个全面的概述:
给定一个“索引”数组 (a )整数和 n 数组 (choices ) a 根据需要,每个选择数组首先广播到一个公共形状的数组;调用这些数组 Ba 和 [Bchoices[i], i = 0,...,n-1] 我们有,必然的, Ba.shape == Bchoices[i].shape 对于每一个 i . 然后,一个具有形状的新数组 Ba.shape 创建如下:
Ba.shape == Bchoices[i].shape
Ba.shape
如果 mode=raise (默认),然后,首先,每个元素 a (因此) Ba )必须在范围内 [0, n-1] 现在,假设 i (在该范围内)是 (j0, j1, ..., jm) 在位置 Ba -那么新数组中相同位置的值就是 Bchoices[i] 在同一位置;
mode=raise
如果 mode=wrap 值 a (因此) Ba )可以是任意(有符号)整数;模块化算法用于映射范围之外的整数。 [0, n-1] 回到那个范围;然后按照上面的方式构造新的数组;
mode=wrap
如果 mode=clip 值 a (因此) Ba )可以是任意(有符号)整数;负整数映射为0;值大于 n-1 映射到 n-1 ,然后按照上面的方法构造新数组。
mode=clip
此数组中必须包含整数 [0, n-1] 在哪里 n 是选择的数目,除非 mode=wrap 或 mode=clip ,在这种情况下,任何整数都是允许的。
选择数组。 a 所有的选择都必须可以广播到相同的形状。如果 choices 它本身是一个数组(不推荐),那么它的最外层维度(即对应于 choices.shape[0] )被视为定义“序列”。
choices.shape[0]
如果提供,结果将插入到该数组中。它应该有适当的形状和类型。请注意 out 总是缓冲,如果 mode='raise' ;使用其他模式以获得更好的性能。
指定索引外部的方式 [0, n-1] 将被治疗:
“引发”:引发异常 “wrap”:值变为值mod n “clip”:值<0映射到0,值>n-1映射到n-1
“引发”:引发异常
“wrap”:值变为值mod n
“clip”:值<0映射到0,值>n-1映射到n-1
合并结果。
如果 a 并且每个选择数组都不能广播到相同的形状。
参见
ndarray.choose
等效法
numpy.take_along_axis
最好是如果 choices 是一个数组
笔记
为了减少误解的机会,即使名义上支持以下“滥用”, choices 既不应该是,也不应该被认为是单个数组,即,容器之类的最外层序列应该是列表或元组。
实例
>>> 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]]])