在numpy数组的不同行中选择不同列的元素

时间:2022-05-15 21:24:14
In [62]: a
Out[62]: 
array([[1, 2],
       [3, 4]])

Is there an easy way to get [2,3], i.e. the second element of the first row, and the first element of the second row? I have the list of the indices for each row, i.e. [1,0] in this case. I have tried a[:,[1,0]], but it doesn't work.

是否有一种简单的方法来获得[2,3],即第一行的第二个元素和第二行的第一个元素?我有每行的索引列表,在这种情况下是[1,0]。我尝试了[:,[1,0]],但它不起作用。

1 个解决方案

#1


You need to specify both i and j for all the elements you want. For example:

您需要为所需的所有元素指定i和j。例如:

import numpy as np
a = np.array([[1, 2],
              [3, 4]])
i = [0, 1]
j = [1, 0]
print(a[i, j])
# [2, 3]

If you need one item from each row, you can use i = np.arange(a.shape[0])

如果每行需要一个项目,可以使用i = np.arange(a.shape [0])

#1


You need to specify both i and j for all the elements you want. For example:

您需要为所需的所有元素指定i和j。例如:

import numpy as np
a = np.array([[1, 2],
              [3, 4]])
i = [0, 1]
j = [1, 0]
print(a[i, j])
# [2, 3]

If you need one item from each row, you can use i = np.arange(a.shape[0])

如果每行需要一个项目,可以使用i = np.arange(a.shape [0])