我有两个numpy数组。3D或2D阵列reference
和3D阵列map_
。
在本例中,设Reference为
reference = array([[ [11,12,13], [14,15,16], [17,18,19] ],
[ [21,22,23], [24,25,26], [27,28,29] ],
[ [31,32,33], [34,35,36], [37,38,39] ],
[ [41,42,43], [44,45,46], [47,48,49] ]])
让Map成为
map_ = array([[ [0,0], [1,2], [2,2] ],
[ [2,1], [3,2], [3,0] ]])
结果应该是
array([[ [11,12,13], [27,28,29], [37,38,39] ],
[ [24,25,36], [47,48,49], [41,42,43] ]])
我可以把它解为:
array([[reference[i[0],i[1],:] for i in j] for j in map_])
然而,当map_和reference是千乘千的数组时,这会变得非常慢。
有没有最快的方法来实现这一点?
3条答案
按热度按时间xzlaal3s1#
使用高级索引:
(BTW避免使用关键字
map
作为变量名...)时间:
在更大的阵列上,增益可能会更大...例如,对于
map = np.random.randint(0,3,size=(100,100,2))
,我们得到V.S.
cgyqldqp2#
类似于@Julien的答案,但使用元组索引。你只需要把
map_
的尺寸按正确的顺序排列:输出量:
也就是说,如果
map_
是:v64noz0r3#
编辑:朱利安的回答更简洁,应该被接受这个问题。我花了一些时间写这个答案,所以我把它作为1留在这里。我花了很多时间来写,2。其他人可能会在这里面找到一些东西(谁知道呢)
简短的形式在这里。找到下面的长形式:
首先,将你的Map重塑为一个2d数组,以便于索引。注意,我将使用
idx
而不是map
,因为map
是python中预定义的函数: