【发布时间】:2022-10-04 20:23:39
【问题描述】:
我有 2 个数组作为输入。在数组上作为输出。数组a 保存数据,形状为(N,M),而数组b 保存索引,形状为(N,X,2)。结果数组的形状应为(N,X),其值取自a。
现在它只适用于 for 循环。既然我有巨大的数组作为输入,我怎么能矢量化它?
下面是一个示例代码来演示我现在所拥有的:
import numpy as np
# a of shape (N,M)
# b of shape (N,X,2)
# t_result of shape (N, X)
a = np.random.randint(0, 10, size=(10, 10))
b = np.random.randint(0, 2, size=(10, 9, 2))
t_result = np.empty((10, 9))
for i in range(b.shape[0]):
t_result[i] = a[i, b[i, :, 0]]
print(t_result)
print(t_result.shape)
【问题讨论】:
标签: python numpy vectorization numpy-slicing