【问题标题】:How to find indices of matching elements in arrays?如何查找数组中匹配元素的索引?
【发布时间】:2020-06-01 03:57:55
【问题描述】:

我有两个向量,向量 A 是 (1298,1),向量 B 在 for 循环中变化但始终只是一个列向量,我正在尝试使用 numpy.where 来查找其中元素的 A 索引B. 目前我有一个 for 循环通过 Vector B element-wise 并使用 numpy.isclose 但我想知道是否有人知道更快的函数和/或如何在没有嵌套 for 循环的情况下做到这一点?它工作但非常缓慢。 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) ```

【问题讨论】:

  • 你能举一些输入例子吗?
  • 您是否也可以在代码中使用A 和B 以便我们知道哪个是哪个?
  • 所以 A 是 (1298,1) 向量,B 通常是 (10,1) 和 (1,1) 之间的大小,元素都是从 1 到 10,000 的整数,对应于模拟软件使用的 atom-id #s(这是 MD 模拟的后处理脚本)

标签: python numpy for-loop comparison indices


【解决方案1】:

从来没有任何理由遍历向量 A 的所有 1298 个元素,为了使用 numpy.where 和 numpy.isclose,我只需要一次使用 B 中的元素,这样 numpy 就可以正确广播。以下代码运行得更快。任何进一步的改进总是受欢迎的。

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

【讨论】:

    猜你喜欢
    • 2018-12-29
    • 2021-11-03
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    • 2017-03-06
    • 2023-03-24
    相关资源
    最近更新 更多