从numpy数组中移除出现超过一次的元素

3 投票
4 回答
4381 浏览
提问于 2025-04-17 12:15

问题是,我该如何完全移除数组中出现超过一次的元素。下面的做法在处理较大的数组时非常慢。有没有什么方法可以用numpy来实现呢?提前谢谢大家。

import numpy as np

count = 0
result = []
input = np.array([[1,1], [1,1], [2,3], [4,5], [1,1]]) # array with points [x, y]

# count appearance of elements with same x and y coordinate
# append to result if element appears just once

for i in input:
    for j in input:
        if (j[0] == i [0]) and (j[1] == i[1]):
            count += 1
    if count == 1:
        result.append(i)
    count = 0

print np.array(result)

更新:因为之前的简化过头了

再说清楚一点:我该如何根据某个属性从数组/列表中移除出现超过一次的元素?这里的意思是,如果每个元素的第一个和第二个条目在列表中都出现超过一次,就把所有相关的元素从列表中移除。希望我没有说得太混乱。Eumiro在这方面帮了我很多,但我还是没能把输出列表整理成我想要的样子 :(

import numpy as np 
import collections

input = [[1,1,3,5,6,6],[1,1,4,4,5,6],[1,3,4,5,6,7],[3,4,6,7,7,6],[1,1,4,6,88,7],[3,3,3,3,3,3],[456,6,5,343,435,5]]

# here, from input there should be removed input[0], input[1] and input[4] because
# first and second entry appears more than once in the list, got it? :)

d = {}

for a in input:
    d.setdefault(tuple(a[:2]), []).append(a[2:])

outputDict = [list(k)+list(v) for k,v in d.iteritems() if len(v) == 1 ]

result = []

def flatten(x):
    if isinstance(x, collections.Iterable):
        return [a for i in x for a in flatten(i)]
    else:
        return [x]

# I took flatten(x) from http://stackoverflow.com/a/2158522/1132378
# And I need it, because output is a nested list :(

for i in outputDict:
    result.append(flatten(i))

print np.array(result)

所以,这个方法是可行的,但在处理大列表时不太实用。首先我遇到了 RuntimeError: maximum recursion depth exceeded in cmp 然后在应用 sys.setrecursionlimit(10000) 后,我又遇到了 Segmentation fault。那我该如何将Eumiro的解决方案应用到超过100000个元素的大列表上呢?

4 个回答

1

更新后的解决方案:

根据下面的评论,新方案是:

idx = argsort(A[:, 0:2], axis=0)[:,1]
kidx = where(sum(A[idx,:][:-1,0:2]!=A[idx,:][1:,0:2], axis=1)==0)[0]
kidx = unique(concatenate((kidx,kidx+1)))

for n in arange(0,A.shape[0],1):
    if n not in kidx:
        print A[idx,:][n]

 > [1 3 4 5 6 7]
   [3 3 3 3 3 3]
   [3 4 6 7 7 6]
   [456   6   5 343 435   5]

kidx 是一个索引列表,里面包含你不想要的元素。这种方法可以保留那些前两个内部元素不与其他内部元素匹配的行。因为一切都是通过索引来处理的,所以速度应该还不错,尽管需要对前两个元素进行排序。需要注意的是,原始行的顺序不会被保留,不过我觉得这不是个大问题。

旧解决方案:

如果我理解得没错,你只是想过滤掉一个列表中的列表,条件是每个内部列表的第一个元素等于第二个元素。

根据你更新的输入 A=[[1,1,3,5,6,6],[1,1,4,4,5,6],[1,3,4,5,6,7],[3,4,6,7,7,6],[1,1,4,6,88,7],[3,3,3,3,3,3],[456,6,5,343,435,5]],下面这一行会去掉 A[0]A[1]A[4]A[5] 也会被去掉,因为它符合你的条件。

[x for x in A if x[0]!=x[1]]

如果你可以使用 numpy,有一种非常简便的方法来实现上述功能。假设 A 是一个数组,那么

A[A[0,:] == A[1,:]]

将提取出相同的值。如果你想循环处理这些数据,这种方法可能比上面提到的解决方案更快。

3

这是对Hooked回答的一个修正版本,速度更快。count_unique这个函数的作用是计算每个唯一键在键列表中出现的次数。

import numpy as np
input = np.array([[1,1,3,5,6,6],
                  [1,1,4,4,5,6],
                  [1,3,4,5,6,7],
                  [3,4,6,7,7,6],
                  [1,1,4,6,88,7],
                  [3,3,3,3,3,3],
                  [456,6,5,343,435,5]])

def count_unique(keys):
    """Finds an index to each unique key (row) in keys and counts the number of
    occurrences for each key"""
    order = np.lexsort(keys.T)
    keys = keys[order]
    diff = np.ones(len(keys)+1, 'bool')
    diff[1:-1] = (keys[1:] != keys[:-1]).any(-1)
    count = np.where(diff)[0]
    count = count[1:] - count[:-1]
    ind = order[diff[1:]]
    return ind, count

key = input[:, :2]
ind, count = count_unique(key)
print key[ind]
#[[  1   1]
# [  1   3]
# [  3   3]
# [  3   4]
# [456   6]]
print count
[3 1 1 1 1]

ind = ind[count == 1]
output = input[ind]
print output
#[[  1   3   4   5   6   7]
# [  3   3   3   3   3   3]
# [  3   4   6   7   7   6]
# [456   6   5 343 435   5]]
3
np.array(list(set(map(tuple, input))))

返回

array([[4, 5],
       [2, 3],
       [1, 1]])

更新 1: 如果你也想去掉 [1, 1](因为它出现了多次),你可以这样做:

from collections import Counter

np.array([k for k, v in Counter(map(tuple, input)).iteritems() if v == 1])

返回

array([[4, 5],
       [2, 3]])

更新 2: 使用 input=[[1,1,2], [1,1,3], [2,3,4], [4,5,5], [1,1,7]]

input=[[1,1,2], [1,1,3], [2,3,4], [4,5,5], [1,1,7]]

d = {}
for a in input:
    d.setdefault(tuple(a[:2]), []).append(a[2])

d 现在是:

{(1, 1): [2, 3, 7],
 (2, 3): [4],
 (4, 5): [5]}

所以我们想要取出所有只有一个值的键值对,并重新创建数组:

np.array([k+tuple(v) for k,v in d.iteritems() if len(v) == 1])

返回:

array([[4, 5, 5],
       [2, 3, 4]])

更新 3: 对于更大的数组,你可以调整我之前的解决方案为:

import numpy as np
input = [[1,1,3,5,6,6],[1,1,4,4,5,6],[1,3,4,5,6,7],[3,4,6,7,7,6],[1,1,4,6,88,7],[3,3,3,3,3,3],[456,6,5,343,435,5]]
d = {}
for a in input:
    d.setdefault(tuple(a[:2]), []).append(a)
np.array([v for v in d.itervalues() if len(v) == 1])

返回:

array([[[456,   6,   5, 343, 435,   5]],
       [[  1,   3,   4,   5,   6,   7]],
       [[  3,   4,   6,   7,   7,   6]],
       [[  3,   3,   3,   3,   3,   3]]])

撰写回答