首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Python中查找重复项的索引

在Python中查找重复项的索引
EN

Stack Overflow用户
提问于 2020-03-05 15:52:48
回答 4查看 128关注 0票数 1

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

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

我需要找出是否有副本,如果有,它们在哪里。副本的值本身并不重要(例如,上面的示例将生成:[0,2,3,5,...] )

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

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2020-03-05 16:08:56

如果你已经有了一个数值数组,你可以使用np.uniquereturn_inverse标志。使用逆数组查找唯一元素计数超过1的所有位置,并查找其索引。

代码语言:javascript
复制
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)
票数 7
EN

Stack Overflow用户

发布于 2020-03-05 16:06:38

如果将numpy数组转换为列表

代码语言:javascript
复制
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]

票数 0
EN

Stack Overflow用户

发布于 2020-03-05 16:12:15

您可以执行以下操作:

代码语言:javascript
复制
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列表。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60540492

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档