python - 如何使用numpy python计算元素向量的数量

标签 python performance numpy

例如,如果我有:

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

我们可以看到数字 1 有四次,数字 4 有两次,只有 3 次。

我想得到以下结果:

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

如您所见:每个单元格都被其元素的计数所取代。

我怎样才能以最有效的方式做到这一点?

最佳答案

一种矢量化方法 np.uniquenp.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/

相关文章:

python - Numpy 教程 - bool 索引

python - ValueError : Could not find function url in draco. apps.home.models

java - I/O 线程的直接切换还是阻塞队列?

swift - 如果我在 Swift 中为多个级别使用嵌套类或结构,是否会出现性能问题?

python - “numpy.ndarray”对象没有属性 'concatenate'错误

python - 为什么 shell=True 和 shell=False 做同样的事情?

python - 如何知道何时在 Python 中管理资源

.net - 最佳文件缓冲区读取大小?

python - 如何将具有数字和非数字条目的 numpy 数组转换为所有 float

python - 非常大的数组的 Numpy 点积