# I am new in python. How can i count repetetive array in numpy?

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

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

edit retag close merge delete

Sort by » oldest newest most voted

You can count the number of occurrences of the object [1,2] in the list X as follows:

sage: X.count([1,2])
2


And you can have the length of X as follows:

sage: len(X)
5


I am pretty sure you will be able to deduce the frequency from those two informations ;)

more

Perhaps what you are looking for is something like:

print {i: X.count(i) for i in X}

from itertools import groupby

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

for key, group in groupby(sorted(X)):
print key, len(list(group))

[1, 2] 2
[2, -1] 1
[5, 1] 2


If X is large some optimization may be added.

If elements in X can be replaced to be tuples instead of lists than dictionary comprehension approach may be used as well:

X = [(1,2), (5,1), (1,2), (2,-1) , (5,1)]
print {i: X.count(i) for i in X}


or even:

X = [(1,2), (5,1), (1,2), (2,-1) , (5,1)]
print {i: X.count(i) for i in set(X)}


(let the Python professionals correct me)

more