1
X = [[1,2], [5,1], [1,2], [2,-1] , [5,1]]

I want to count "frequency" of repetitive elements for example [1,2]

3 Answers 3

2

Unless speed is really an issue, the simplest approach is to map the sub arrays to tuples and use a Counter dict:

X = [[1,2], [5,1], [1,2], [2,-1] , [5,1]]

from collections import Counter

cn = Counter(map(tuple, X))
print(cn)
print(list(filter(lambda x:x[1] > 1,cn.items())))
Counter({(1, 2): 2, (5, 1): 2, (2, -1): 1})
((1, 2), 2), ((5, 1), 2)]

If you consider [1, 2]equal to [2, 1] then you could use a frozenset Counter(map(frozenset, X)

Sign up to request clarification or add additional context in comments.

Comments

0

Take a look at numpy.unique: http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.unique.html

You can use the return_counts argument for getting the count of each item:

values, counts = numpy.unique(X, return_counts = True)
repeated = values[counts > 1]

1 Comment

Won't this just return a flat array , how do you know what is paired or the frequency?
-1

Assuming I understand what you want:

Try to count each item in your list into a dictionary dict then select from dict items that its count > 1

The following code might help you:

freq = dict()

for item in x:
    if tuple(item) not in x:
        freq[tuple(item)] = 1
    else:
        freq[tuple(item)] += 1

print {k:v for(k,v) in freq.items() if v > 1}

That code will give you the output:

{(1, 2): 2}

1 Comment

The OP specifically asked for a numpy solution. This solution would be a lot slower on numpy arrays.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.