Ask Your Question
0

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

asked 2015-12-12 16:29:06 +0100

Nazila gravatar image

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 flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
1

answered 2015-12-13 14:37:59 +0100

tmonteil gravatar image

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 ;)

edit flag offensive delete link more
0

answered 2015-12-14 21:06:46 +0100

Eugene gravatar image

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)

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2015-12-12 16:29:06 +0100

Seen: 284 times

Last updated: Dec 14 '15