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]
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 ;)
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)
Asked: 2015-12-12 16:29:06 +0100
Seen: 384 times
Last updated: Dec 14 '15
Copyright Sage, 2010. Some rights reserved under creative commons license. Content on this site is licensed under a Creative Commons Attribution Share Alike 3.0 license.