简体   繁体   English

如何在 Numpy 中使用 3d 索引数组进行二维数组切片

[英]How can I use a 3d array of indices for a 2d array slicing in Numpy

I have 2 arrays as input.我有 2 arrays 作为输入。 On array as output. Array a holds the data and is of shape (N,M) , while array b holds the indices and is of shape (N,X,2) .在数组上为 output。数组a保存数据并且形状为(N,M) ,而数组b保存索引并且形状为(N,X,2) The resulting array should be of shape (N,X) , with the values taken from a .结果数组的形状应为(N,X) ,其值取自a

Right now it only works with a for loop.现在它只适用于 for 循环。 How could I vectorize it since I have huge arrays as input?由于我有巨大的 arrays 作为输入,我该如何对其进行矢量化?

Below is a sample code to demonstrate what I have right now:下面是一个示例代码,用于演示我现在拥有的内容:

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)

Ok so I adapted a bit the answer to another post from scleronomic :好的,所以我对scleronomic的另一篇文章的答案进行了一些调整:

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))

t_result = a[np.arange(a.shape[0])[:,None],b[np.arange(b.shape[0]),:,0]]

print(t_result)
print(t_result.shape)

I am not sure whether or not it is the best solution but it works.我不确定它是否是最佳解决方案,但它确实有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM