Ask Your Question
0

frequency (count) in Numpy Array

asked 2013-06-25 18:28:27 +0200

mresimulator gravatar image

updated 2013-06-25 19:06:57 +0200

slelievre gravatar image

Hi experts!

For a list L the command L.count(z) shows the number of times that the element z is repeated in list L.

For example:

[I] L=[1,1,3,1,4,5,8]
[I] L.count(1)
[O] 3

How can i do that with a Numpy array?

Waiting for your answers.

Thanks a lot!

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
1

answered 2013-06-25 19:05:07 +0200

slelievre gravatar image

updated 2013-06-25 19:16:01 +0200

Of course you could always convert the array to a list:

sage: import numpy as np
sage: L = np.array([1,1,3,1,4,5,8])
sage: list(L).count(1)
3

but here is something more direct:

sage: (L == 1).sum()
3

or

sage: sum(L == 1)
3

Also, if you want to count occurrences of every element in the array, you can do:

sage: from collections import Counter
sage: Counter(L)
Counter({1: 3, 8: 1, 3: 1, 4: 1, 5: 1})

The command sum will also count how many elements in an array satisfy a property.

For example to see how many are odd:

sage: (L%2).sum()
5

or how many are between 3 and 5:

sage: ((3r <= L) & (L <= 5r)).sum()
3

(here 3r and 5r are a way to input raw Python integers, as the comparison with Sage integers would not work well -- I'm not sure why).

edit flag offensive delete link more
0

answered 2013-06-25 19:15:49 +0200

mresimulator gravatar image

Thanks slelievre!!

Case closed

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: 2013-06-25 18:28:27 +0200

Seen: 77,686 times

Last updated: Jun 25 '13