numpy数组中的计数列表函数的等价物

Dir*_*Fox 5 python arrays numpy

我有一个listScore形状(100000,2)的矩阵:我想计算所有相同的行.例如,如果listScore是列表列表,我会很简单:

listScore.count([2,0])
Run Code Online (Sandbox Code Playgroud)

查找等于[2,0]的所有列表.我显然可以改变我的类型,listScore这样它就是一个列表,但我想保持有效性numpy.我可以使用任何功能做同样的事情吗?

提前致谢

Div*_*kar 4

如果listScore是 NumPy 数组,你可以这样做 -

count = np.all(listScore == np.array([2,0]),axis=1).sum()
Run Code Online (Sandbox Code Playgroud)

如果数组始终是 2 列数组,那么您可以分别使用20分别比较两列的性能并获得计数,如下所示 -

count = ((listScore[:,0] ==2) & (listScore[:,1] ==0)).sum()
Run Code Online (Sandbox Code Playgroud)

如果你是它的粉丝np.einsum,你可能会想尝试一下这种扭曲的——

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

另一个以性能为导向的解决方案可能是cdist from scipy-

from scipy.spatial.distance import cdist
count = (cdist(listScore,np.atleast_2d([2,0]))==0).sum()
Run Code Online (Sandbox Code Playgroud)