【问题标题】:Finding indices of duplicate items in Python在 Python 中查找重复项的索引
【发布时间】:2020-06-17 19:08:37
【问题描述】:

我有一个 2D numpy-ndarray,大小如下:(416,2)

[[10,10],[3,6],[2,4],[10,10],[0,0],[2,4],...]

我需要查找是否有任何重复,如果有,它们在哪里。重复项本身的值无关紧要(即上面的示例将使:[0,2,3,5,...]

有没有办法做到这一点?谢谢。

【问题讨论】:

  • @bzoei 你能详细说明一下,你究竟需要如何找到骗子,因为就给定数组而言,骗子将位于[0, 3, 4..] 的位置?
  • @Shubham 也有同样的想法,但看起来作者需要非唯一项目的索引,而不是具有重复值的项目。

标签: python matrix indexing duplicates numpy-ndarray


【解决方案1】:

如果你已经有一个 numpy 数组,你可以使用 np.unique 并使用 return_inverse 标志。使用逆数组查找唯一元素计数超过 1 的所有位置,并找到它们的索引。

import numpy as np
arr = np.array([[10,10],[3,6],[2,4],[10,10],[0,0],[2,4]])
vals, inverse, count = np.unique(arr,
                                 return_inverse=True,
                                 return_counts=True,
                                 axis=0)
out = np.where(count[inverse] > 1)[0] #find all indices where counts > 1
print(out) #array([0, 2, 3, 5], dtype=int64)

【讨论】:

  • @bzoei 接受的解决方案需要O(n^2) 时间。我认为这比目前接受的答案更好。
  • 正确,这将随时间线性缩放O(n),因此更大的数组应该会看到更大的收益。编辑:另外,不知道为什么投反对票。 耸耸肩
【解决方案2】:

如果将 numpy 数组转换为列表

items = [[10,10],[3,6],[2,4],[10,10],[0,0],[2,4]]
index = [i for i, v in enumerate(items) if items.count(v) > 1]

index 将是 [0, 2, 3, 5]

【讨论】:

    【解决方案3】:

    您可以执行以下操作:

    a = np.array([[1, 2], [3, 4], [5, 6], [3, 4]])
    temp = []
    tempdict = {}
    i = 0
    for array in a:
        try:
            tempdict[str(array)].append(i)
        except:
            tempdict[str(array)] = [i]
        i += 1
    for key in tempdict:
        if len(tempdict[key]) > 1:
            print(tempdict[key])
    

    这将返回有重复的numpy数组的索引,并且不需要转换为常规的python列表。

    【讨论】:

      【解决方案4】:

      或者,如果您想将所有内容保存在 numpy 中:

      import numpy as np
      
      narray = np.array([[10,10],[3,6],[2,4],[10,10],[0,0],[2,4]])
      u, c = np.unique(narray, return_counts=True, axis = 0)
      dup = u[c > 1]
      array_indices = np.unique(np.nonzero(np.isin(narray, dup))[0])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-11
        • 2021-06-21
        • 1970-01-01
        • 2012-10-29
        • 2021-04-05
        • 2014-08-16
        • 2023-03-23
        • 2022-11-26
        相关资源
        最近更新 更多