ASKSAGE: Sage Q&A Forum - Individual question feedhttp://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Tue, 25 Jun 2013 12:15:49 -0500frequency (count) in Numpy Arrayhttp://ask.sagemath.org/question/10279/frequency-count-in-numpy-array/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!
Tue, 25 Jun 2013 11:28:27 -0500http://ask.sagemath.org/question/10279/frequency-count-in-numpy-array/Answer by slelievre for <p>Hi experts!</p>
<p>For a list <code>L</code> the command <code>L.count(z)</code> shows the number of times that the element <code>z</code> is repeated in list <code>L</code>.</p>
<p>For example:</p>
<pre><code>[I] L=[1,1,3,1,4,5,8]
[I] L.count(1)
[O] 3
</code></pre>
<p>How can i do that with a Numpy array?</p>
<p>Waiting for your answers.</p>
<p>Thanks a lot!</p>
http://ask.sagemath.org/question/10279/frequency-count-in-numpy-array/?answer=15137#post-id-15137Of 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).Tue, 25 Jun 2013 12:05:07 -0500http://ask.sagemath.org/question/10279/frequency-count-in-numpy-array/?answer=15137#post-id-15137Answer by mresimulator for <p>Hi experts!</p>
<p>For a list <code>L</code> the command <code>L.count(z)</code> shows the number of times that the element <code>z</code> is repeated in list <code>L</code>.</p>
<p>For example:</p>
<pre><code>[I] L=[1,1,3,1,4,5,8]
[I] L.count(1)
[O] 3
</code></pre>
<p>How can i do that with a Numpy array?</p>
<p>Waiting for your answers.</p>
<p>Thanks a lot!</p>
http://ask.sagemath.org/question/10279/frequency-count-in-numpy-array/?answer=15138#post-id-15138Thanks slelievre!!
Case closedTue, 25 Jun 2013 12:15:49 -0500http://ask.sagemath.org/question/10279/frequency-count-in-numpy-array/?answer=15138#post-id-15138