【发布时间】:2019-01-27 23:52:35
【问题描述】:
我有一个大小为5x5x4x5x5 的numpy 数组a。我有另一个矩阵b,大小为5x5。我想得到a[i,j,b[i,j]] 的i 从0 到4 和j 从0 到4。这会给我一个5x5x1x5x5 矩阵。有没有办法不使用 2 个 for 循环来做到这一点?
【问题讨论】:
标签: python arrays numpy indexing
我有一个大小为5x5x4x5x5 的numpy 数组a。我有另一个矩阵b,大小为5x5。我想得到a[i,j,b[i,j]] 的i 从0 到4 和j 从0 到4。这会给我一个5x5x1x5x5 矩阵。有没有办法不使用 2 个 for 循环来做到这一点?
【问题讨论】:
标签: python arrays numpy indexing
让我们将矩阵a 视为大小为(5, 5) 的100 个(= 5 x 5 x 4) 矩阵。所以,如果你能得到每个三元组的线性索引 - (i, j, b[i, j]) - 你就完成了。这就是np.ravel_multi_index 的用武之地。下面是代码。
import numpy as np
import itertools
# create some matrices
a = np.random.randint(0, 10, (5, 5, 4, 5, 5))
b = np.random(0, 4, (5, 5))
# creating all possible triplets - (ind1, ind2, ind3)
inds = list(itertools.product(range(5), range(5)))
(ind1, ind2), ind3 = zip(*inds), b.flatten()
allInds = np.array([ind1, ind2, ind3])
linearInds = np.ravel_multi_index(allInds, (5,5,4))
# reshaping the input array
a_reshaped = np.reshape(a, (100, 5, 5))
# selecting the appropriate indices
res1 = a_reshaped[linearInds, :, :]
# reshaping back into desired shape
res1 = np.reshape(res1, (5, 5, 1, 5, 5))
# verifying with the brute force method
res2 = np.empty((5, 5, 1, 5, 5))
for i in range(5):
for j in range(5):
res2[i, j, 0] = a[i, j, b[i, j], :, :]
print np.all(res1 == res2) # should print True
【讨论】:
np.take_along_axis 正是为此目的 -
np.take_along_axis(a,b[:,:,None,None,None],axis=2)
【讨论】: