python - 使用索引数组对多维 numpy 数组进行索引

标签 python arrays numpy

在给定索引数组的情况下,我很难对二维数组进行索引。

假设我有:

# Indexing array 
idx = np.array([0,2,1,2,1])

# Array to be indexed
my_array = np.array([[0,2,1], [0,5,1], [1,2,1], [5,1,3], [2,6,2]])

预期输出应该是 0 my_array 第一个条目的索引,2 my_array 第二个条目的索引依此类推,因此:

# Expected output
expected_array = np.array([0,1,2,3,6])

我实际上是使用 for 循环做到的:

# Using for-loop
expected_array = np.array([])
for i in range(len(my_array)):
    expected_array = np.append(idx, my_array[i][idx[i]])

但是我想知道是否有一种方法可以在不使用 for 循环的情况下进行数组索引?假设len(idx)==len(my_array)一直以来。

最佳答案

您可以使用numpy.arange创建一个数组来索引行,每次只是每一行。然后使用您的 idx 数组为每行建立索引。

>>> my_array[np.arange(my_array.shape[0]), idx]
array([0, 1, 2, 3, 6])

关于python - 使用索引数组对多维 numpy 数组进行索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45283837/

相关文章:

arrays - slice : Trouble appending to a slice in a struct

python - 使用 numpy 生成 tall 数组

python - 如何对同一个字典值同时使用键和索引?

python - 匹配所有包含的正则表达式 ''(2 个单引号)

python - 如何从索引开始查找第一次出现的 bool 值

Java:将类扩展为数组

python - Pandas :要列出的列的累积值[无迭代]

将 char 数组转换为 atoi 失败

python - 使用 SVD 进行降维,指定要保持的能量

python - 对 numpy 数组中的每一行应用函数?