我有两个数组:
a.shape
# (1024, 768, 100)
heights.shape
# (1024, 768)
我想从a
中提取一个二维图像,它将沿着2
轴取一个元素,从heights
中取其索引。类似于这样:
result = a[:,:,h]
其中h
是数组heights
中的值(在适当的坐标中)。
结果的形状为(1024, 768)
。
使用循环很容易,但效率很低:
result = np.zeros(heights.shape)
for i in range(a.shape[0]):
for j in range(a.shape[1]):
h = heights[i][j]
result[i][j] = a[i][j][h]
示例:
a = np.arange(30).reshape((3,2,5)) + 5
# array([[[ 5, 6, 7, 8, 9],
# [10, 11, 12, 13, 14]],
#
# [[15, 16, 17, 18, 19],
# [20, 21, 22, 23, 24]],
#
# [[25, 26, 27, 28, 29],
# [30, 31, 32, 33, 34]]])
heights = np.asarray([[0, 2], [1, 4], [1, 3]])
# array([[0, 2],
# [1, 4],
# [1, 3]])
print(expected_result)
# array([[ 5, 12],
# [16, 24],
# [26, 33]]
我怎样才能以一种有效的方式做到这一点?
2条答案
按热度按时间yws3nbqq1#
使用
numpy.take_along_axis
+numpy.squeeze
的组合:iih3973s2#
一个更手动的解决方案,您可以使用广播创建适当的花式索引: