maple
maple

Reputation: 1892

How to get count of all element in numpy?

suppose I have an array in numpy

array([1,1,2,3,4,5,5,5,6,7,7,7,7])

What I want is to get two arrays to give count of each element:

array([1,2,3,4,5,6,7])
array([1,1,1,1,3,1,4])

How can I do this without any for loops?

Upvotes: 1

Views: 3479

Answers (2)

hpaulj
hpaulj

Reputation: 231475

In [1043]: np.unique(np.array([1,1,2,3,4,5,5,5,6,7,7,7,7]),return_counts=True)
Out[1043]: (array([1, 2, 3, 4, 5, 6, 7]), array([2, 1, 1, 1, 3, 1, 4]))

Upvotes: 8

3kt
3kt

Reputation: 2553

You can use np.bincount :

>>> import numpy as np
>>> a = np.array([1,1,2,3,4,5,5,5,6,7,7,7,7])
>>> b = np.bincount(a)
>>> b[np.unique(a)]
array([2, 1, 1, 1, 3, 1, 4])

And to get the other array :

>>> np.unique(a)
array([1, 2, 3, 4, 5, 6, 7])

Upvotes: 0

Related Questions