Equivalent to a count list function in a numpy array

I have a listScore matrix with the form (100000.2): I would like to count all the same lines. For example, if listScore was a list of list, I would simply do:

 listScore.count([2,0]) 

to find a list equal to [2.0]. I obviously could convert the type of my listScore to be a list, but I want to keep numpy efficient. Is there any function that I could use to do the same?

Thank you in advance

+5
source share
2 answers

If listScore is a NumPy array, you can do -

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

If the array is always an array of two columns, you can compare the two columns separately with 2 and 0 respectively, for performance and get the count value like this:

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

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

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

Another performance-oriented solution might be cdist from scipy -

 from scipy.spatial.distance import cdist count = (cdist(listScore,np.atleast_2d([2,0]))==0).sum() 
+4
source

With a numpy.matrix you can use:

 (listScore==listScore[ind]).all(1).sum() 

to find the number of rows matching the row with index ind .

or

 (listScore==[2,0]).all(1).sum() 

to match a specific pattern

0
source

All Articles