繁体   English   中英

在numpy数组中查找相似元素的索引

[英]Find the indices of similar elements in numpy array

我有一个numpy数组,其中有不同的值,其中一些值可能相等。 我想返回一个列表列表,每个列表包含相等元素的索引。 例如,想象

A=np.array([2,3,2,1,1,1,3,4,5,6,6,6,6,3])

那我想要的结果应该是

[[0,2],[1,6,13],[3,4,5],[7],[8],[9,10,11,12]]

这是我的解决方案,但我正在寻找一种更智能的方法:

h=[]
s=set()
for i in list_name:

    if i in s:
        continue
    h.append(np.where(list_name==i))
    s.add(i)

print h

尝试使用np.unique 1在数组中查找唯一元素。

使用np.where 2遍历此数组。 查找元素为0的所有索引的示例为

numpy.where(x == 0)[0]

假设顺序无关紧要,那应该可以。

import numpy as np
input_array = np.array([2,3,2,1,1,1,3,4,5,6,6,6,6,3])
out_array = [np.where(input_array == element)[0].tolist() for element in np.unique(input_array)]

当我运行它时,我得到

[[3, 4, 5], [0, 2], [1, 6, 13], [7], [8], [9, 10, 11, 12]]

您可以使用哈希图。 键可以是数组中的int,值可以是存储该int索引的链表。

遍历数组,并为数组中的每个int都将其索引添加到哈希图中。

最后,从地图中的列表中检索那些索引。

查找表可以很好地做到这一点,然后可以显式地查找它们:

mytable = {}

for i, value in enumerate(list_name):
    mytable[value] = [i, *mytable.get(value,[])]

mytable.get(2)
[0,2]

如果只需要索引,则:

indices = [mytable.get(a) for a in list_name]

[[0,2],[1,6,13],[3,4,5],[7],[8],[9,10,11,12]]

它不是NumPy解决方案,但可以解决问题(并且也适用于NumPy数组)。

from collections import defaultdict

a = [2, 3, 2, 1, 1, 1, 3, 4, 5, 6, 6, 6, 6, 3]
positions = defaultdict(set)

for index, value in enumerate(a):
    positions[value].add(index)

print(dict(positions))

输出

{2: {0, 2}, 3: {1, 13, 6}, 1: {3, 4, 5}, 4: {7}, 5: {8}, 6: {9, 10, 11, 12}}

我的尝试:

金达丑陋,不得不做最后的独特,但工作

 import numpy as np A=np.array([2,3,2,1,1,1,3,4,5,6,6,6,6,3]) def index(my_list, element): return [i for i, x in enumerate(my_list) if x == element] print np.unique(np.array([index(A,i) for i in A])) >> [[0, 2] [1, 6, 13] [3, 4, 5] [7] [8] [9, 10, 11, 12]] 

暂无
暂无

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

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