得到一个数组的子数组的有效途径,该指数映射 [英] Efficient way of getting a subarray of an array that the indices are mapped
问题描述
我有一个矩阵说 A
。我需要得到它的一个子矩阵,基本上它的指数是从映射来主矩阵的指标(此图不一定1-1)。我有以下的code生成的子矩阵与这里的映射被认为是之
。
导入numpy的是NP
DEF变换(A):
B = np.zeros(A.flatten()。塑造[0])
因为我在范围内(A.flatten()形状[0]):
multi_idx = np.unravel_index(I,A.shape)
B〔np.sum(multi_idx)] = A [multi_idx]应用在指数#系统映射:B [np.sum(multi_idx)
返回b
A = np.arange(27).reshape([3,3,3])
打印
打印转换(A)
通过输出:
[[[0 1 2]
[3 4 5]
[6 7 8] [9 10 11]
[12 13 14]
[15 16 17]] [18 19 20]
[21 22 23]
[24 25 26]]]
[0 9. 18. 21. 24. 25. 26. 0 0 0 0 0 0 0 0。
0 0 0 0 0 0 0 0 0 0 0 0]
np.ogrid
可以使基于指数前pressions一种方便的方法数组。例如,
导入numpy的是NPA = np.arange(27).reshape([3,3,3])
B = np.zeros(A.size)
I,J,K = np.ogrid [0:3,0:3,0:3]
B〔I + J + K] = A
打印(B)
收益
[0 9. 18. 21. 24. 25. 26. 0 0 0 0 0 0 0 0。
0 0 0 0 0 0 0 0 0 0 0 0]
注意,分配
B [X] = A
等同于
B [X.ravel()] = A.ravel()
和分配是<青霉>为了完成从左到右的。因此,如果 X
有许多重复的值,只有最后的价值最终会影响 B
。这有处理地图的非一到一内斯在你想要的方式的影响。
I have a matrix say a
. I need to get a sub-matrix of it, which basically the indices of it are coming from a mapping on the indices of the main matrix(This map is not necessarily 1-1). I have the following code to generate the sub-matrix and here the mapping is considered to be sum
.
import numpy as np
def transform(A):
B=np.zeros(A.flatten().shape[0])
for i in range(A.flatten().shape[0]):
multi_idx=np.unravel_index(i,A.shape)
B[np.sum(multi_idx)]=A[multi_idx] #the mapping applied on the indices: B[np.sum(multi_idx)]
return B
A=np.arange(27).reshape([3,3,3])
print A
print transform(A)
With output:
[[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]]
[[ 9 10 11]
[12 13 14]
[15 16 17]]
[[18 19 20]
[21 22 23]
[24 25 26]]]
[ 0. 9. 18. 21. 24. 25. 26. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
np.ogrid
can be a convenient way to make expressions based on the indices in an array. For example,
import numpy as np
A = np.arange(27).reshape([3,3,3])
B = np.zeros(A.size)
i, j, k = np.ogrid[0:3, 0:3, 0:3]
B[i+j+k] = A
print(B)
yields
[ 0. 9. 18. 21. 24. 25. 26. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
Note that the assignment
B[X] = A
is equivalent to
B[X.ravel()] = A.ravel()
and the assignment is done in order from left to right. Thus, if X
has many duplicate values, only the last value ultimately affects B
. This has the effect of handling the non-one-to-one-ness of your map in the way you desire.
这篇关于得到一个数组的子数组的有效途径,该指数映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!