MWB
MWB

Reputation: 12567

count a range of elements with Numpy

np.unique([1, 3, 0, 3, 1, 1], return_counts=True)

returns

(array([0, 1, 3]), array([1, 3, 2]))

which excludes missing elements, in this case, 2.

Is there an easy and efficient way to get all counts, for example:

count(ar=[1, 3, 0, 3, 1, 1], from=0, to=4) # returns [1, 3, 0, 2]

?

Upvotes: 2

Views: 226

Answers (2)

Kevin
Kevin

Reputation: 3348

You could use np.add.at:

ar = np.array([1, 3, 0, 3, 1, 1])
count = np.zeros(np.amax(ar)+1)
np.add.at(count, ar, 1)

Output in count:

array([1., 3., 0., 2.])

But using np.bincount will be much faster

Upvotes: 2

Nick
Nick

Reputation: 147146

You could use np.bincount, passing it a minlength of the maximum value in the array plus 1:

ar = np.array([1, 3, 0, 3, 1, 1])
np.bincount(ar, minlength=np.amax(ar)+1)
# array([1, 3, 0, 2], dtype=int64)

Upvotes: 4

Related Questions