简体   繁体   English

如何找到数组中匹配元素的索引?

[英]How to find indices of matching elements in arrays?

I have two vectors, vector A is (1298,1), Vector B varies in a for loop but is always just a column vector, I am trying to use numpy.where to find the A-indices of the elements in B. Currently I have a for loop combing through Vector B element-wise and using numpy.isclose but I was wondering if anyone knows a quicker function and/or how to do this without a nested for loop?我有两个向量,向量 A 是 (1298,1),向量 B 在 for 循环中变化但始终只是一个列向量,我正在尝试使用 numpy.where 来查找 B 中元素的 A 索引。目前我有一个 for 循环组合 Vector B 元素并使用 numpy.isclose 但我想知道是否有人知道更快的函数和/或如何在没有嵌套 for 循环的情况下执行此操作? It works but very slowly.它有效但非常缓慢。 The for loops looks like this for 循环看起来像这样

sphere_indices=[]
for k in range(len(A)):
    for j in range(len(B)):
         if np.isclose(B[j,0],A[k,0]):
              sphere_indices.append(k) ```

There was never any reason to iterate through the all 1298 elements of vector A, in order to use numpy.where and numpy.isclose I just needed to use the elements in B one at a time so numpy can broadcast properly.从来没有任何理由遍历向量 A 的所有 1298 个元素,为了使用 numpy.where 和 numpy.isclose 我只需要一次使用 B 中的元素,这样 numpy 就可以正确广播。 The following code runs much faster.下面的代码运行得更快。 Any further improvements are always welcome.任何进一步的改进总是受欢迎的。

                    for j in range(len(index)):
                        sphere_indices1=np.where(np.isclose(sphere_index[:,0],index[j,0]))
                        sphere_indices.append(sphere_indices1[0])```

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

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