Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of count list function in numpy array

I have a matrix listScore with the shape (100000,2): I would like to count all the identical rows like. For instance, if listScore was a list of list I would simple do:

listScore.count([2,0])

to look for all the list equal to [2,0]. I could obviously transform the type of my listScore so that it would be a list but I want to keep to effectiveness of numpy. Is there any function I could use to do the same thing ?

Thanks in advance

like image 214
Dirty_Fox Avatar asked Sep 28 '22 06:09

Dirty_Fox


People also ask

Is there a NumPy count function?

NumPy count() functionThe count() function is used to return an array with the count values of non-overlapping occurrences(unique) of a given substring in the range [start, end]. This function calls str. count internally, for every element of the given ndrray.

How do you count a list array in Python?

Python len() method enables us to find the total number of elements in the array/object. That is, it returns the count of the elements in the array/object.


1 Answers

If listScore is a NumPy array, you could do -

count = np.all(listScore == np.array([2,0]),axis=1).sum()

If the array is always a 2 columns array, then you can compare the two columns separately with 2 and 0 respectively for performance and get the count like so -

count = ((listScore[:,0] ==2) & (listScore[:,1] ==0)).sum()

If you are a fan of np.einsum, you might like to try this twisted one -

count = (~np.einsum('ij->i',listScore != [2,0])).sum()

Another performance-oriented solution could be with cdist from scipy -

from scipy.spatial.distance import cdist
count = (cdist(listScore,np.atleast_2d([2,0]))==0).sum()
like image 190
Divakar Avatar answered Oct 06 '22 01:10

Divakar