例如,如果我有:
a=np.array([[1,1,4,1,4,3,1]])
我们可以看到数字 1 有四次,数字 4 有两次,只有 3 次。
我想得到以下结果:
array(4,4,2,4,2,1,4)
如您所见:每个单元格都被其元素的计数所取代。
我怎样才能以最有效的方式做到这一点?
最佳答案
一种矢量化
方法 np.unique
和 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())]
sample 运行-
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])
根据@Jaime 的评论,您可以像这样单独使用 np.unique
-
_, inv_idx, counts = np.unique(a, return_inverse=True, return_counts=True)
out = counts[inv_idx]
关于python - 如何使用numpy python计算元素向量的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31499988/