简体   繁体   English

如何使用二维索引数组从二维数组中提取元素?

[英]How do I extract elements from a 2D array using a 2D array of indices?

I am trying to extract elements from a 2 dimensional array, a , and I am using a 2 dimensional array of indices, b , representing x/y coordinates.我正在尝试从二维数组a中提取元素,并且我正在使用一个二维索引数组b ,表示 x/y 坐标。 I have found something similar for a 1D array but I was unable to successfully apply it to a 2D array: Python - How to extract elements from an array based on an array of indices?我发现一维数组有类似的东西,但我无法成功地将其应用于二维数组: Python - 如何根据索引数组从数组中提取元素?

a = np.random.randn(10,7)
a = a.astype(int)
b = np.array([[1, 2], [2,3], [3,5], [2,7], [5,6]])

I have been using the bit of code below, however it returns a 3D matrix with values from the rows of each of the indices:我一直在使用下面的代码,但是它返回一个 3D 矩阵,其中包含来自每个索引的行的值:

result2 = np.array(a)[b]
result2
Out[101]: 
array([[[ 0, -1,  0,  0,  0,  1,  0],
        [ 0, -1,  0,  0,  0,  0,  0]],

       [[ 0, -1,  0,  0,  0,  0,  0],
        [-1,  0,  0,  1,  0,  0,  0]],

       [[-1,  0,  0,  1,  0,  0,  0],
        [ 0,  0, -1, -2,  1,  0,  0]],

       [[ 0, -1,  0,  0,  0,  0,  0],
        [-1,  0,  0,  0,  0,  0,  1]],

       [[ 0,  0, -1, -2,  1,  0,  0],
        [ 1,  0,  0,  1,  0, -1,  0]]])

How can I modify b in order to index (column 1,row 2)... (column 2, row 3)... (column 3, row 5)... etc?如何修改b以索引(第 1 列,第 2 行)...(第 2 列,第 3 行)...(第 3 列,第 5 行)...等?

... ...

This is a minimal reproducible example and my actual data involves me indexing 500 cells in a 100x100 matrix (using an array of x/y coordinates/indices, size (500x2), similar to the above b ).这是一个最小的可重现示例,我的实际数据涉及我在 100x100 矩阵中索引 500 个单元格(使用 x/y 坐标/索引数组,大小 (500x2),类似于上面的b )。 Would it be best to use a for loop in this case?在这种情况下最好使用 for 循环吗? Something along the lines of...类似于...的东西

for i in b:
    for j in b:
        result2 = np.array(a)[i,j]

I've encountered the same issue not long ago, and the answer is actually quite simple:不久前我也遇到过同样的问题,答案其实很简单:

result = a[b[:,0], b[:,1]]

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

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