Ask Your Question

Revision history [back]

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})
click to hide/show revision 2
additional examples of `.sum()`

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