How to count the number of elements using numpy python

For example, if I have:

a=np.array([[1,1,4,1,4,3,1]])

      

We see that we have the number 1 four times, the number 4 two and three only ones.

I want to get the following result:

array(4,4,2,4,2,1,4)

      

As you can see: each cell is replaced with the counter of that item.

How can I do this in the best way?

+3


source to share


3 answers


One approach vectorized

with np.unique

and np.searchsorted

-

# Get unique elements and their counts
unq,counts = np.unique(a,return_counts=True)

# Get the positions of unique elements in a. 
# Use those positions to index into counts array for final output.
out = counts[np.searchsorted(unq,a.ravel())]

      

Example run -



In [86]: a
Out[86]: array([[1, 1, 4, 1, 4, 3, 1]])

In [87]: out
Out[87]: array([4, 4, 2, 4, 2, 1, 4])

      

As per @Jaime's comments, you can use np.unique

yourself like this -

_, inv_idx, counts = np.unique(a, return_inverse=True, return_counts=True)
out = counts[inv_idx]

      

+3


source


Use collections.Counter

:

from collections import Counter
ctr = Counter(a.flat)
result = np.array([ctr[i] for i in a.flat])

      



If you want yours to result

have the same dimensions as a

, use reshape

:

result = result.reshape(a.shape)

      

0


source


I tried to combine both numpy and counter:

from collections import Counter
a=np.array([[1,1,4,1,4,3,1]])

# First I count the occurence of every element and stor eit in the dict-like counter
# Then I take its get-method and vectorize it for numpy-array usage
vectorized_counter = np.vectorize(Counter(a.flatten()).get)

vectorized_counter(a)

      

Of:

array([[4, 4, 2, 4, 2, 1, 4]])

      

0


source







All Articles