首页 > 解决方案 > 来自外部集的 numpy 计数出现次数

问题描述

我想计算集合中每个元素出现在 ndarray 中的数量。前任:

set = {1, 2, 3}
a = np.array([1, 1, 3, 1, 3])
res = {1:3, 2:0, 3:2}

似乎np.unique没有提供“基本”元素集的选项。最快的方法是什么?

标签: pythonnumpy

解决方案


这是一种方法np.uniquenp.searchsorted-

u,c = np.unique(a,return_counts=True)
s = np.array(list(set))
idx = np.searchsorted(u,s)
idx[idx==len(u)] = 0 # account for set elements out-of-bounds in a
mask = u[idx]==s
cm = c[idx]*mask
out = dict(zip(s,cm))

另一个np.bincount用于集合和数组中正数的特定情况 -

c0 = np.bincount(a,minlength=s.max()+1)
out = dict(zip(s,c0[s]))

推荐阅读