从索引矩阵矢量化数组访问

2024-04-26 00:23:33 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑以下几点:

In [51]: arr = np.arange(6, 10)

In [52]: idx = np.random.randint(4, size=(3, 4))

In [53]: idx
Out[53]:
array([[0, 3, 3, 1],
    [1, 3, 3, 2],
    [1, 1, 1, 1]])

In [54]: result = np.empty_like(idx)

In [55]: for i in range(idx.shape[0]):
    ...:     result[i] = arr[idx[i]]
    ...:

In [56]: result
Out[56]:
array([[6, 9, 9, 7],
    [7, 9, 9, 8],
    [7, 7, 7, 7]])

如何对for循环进行矢量化?我找不到通过索引矩阵“多次”访问一维数组的方法,其中每一行都是索引数组


Tags: inforsizenprandom数组resultout
1条回答
网友
1楼 · 发布于 2024-04-26 00:23:33

如注释中所述,您可以使用idx数组简单地索引到数组arr

In [47]: arr 
Out[47]: array([6, 7, 8, 9])

In [48]: idx     
Out[48]: 
array([[3, 2, 2, 0],
       [0, 3, 2, 3],
       [3, 2, 2, 3]])

In [49]: arr[idx] 
Out[49]: 
array([[9, 8, 8, 6],
       [6, 9, 8, 9],
       [9, 8, 8, 9]])

如果你想要一个不那么神奇,更具启发性的方法,那么下面的方法会更有帮助

# flatten the `idx` array; index into `arr`; then reshape to `idx's` shape.

In [50]: arr[idx.ravel()].reshape(idx.shape) 
Out[50]: 
array([[9, 8, 8, 6],
       [6, 9, 8, 9],
       [9, 8, 8, 9]])

相关问题 更多 >