例如,如果我有:
a=np.array([[1,1,4,1,4,3,1]])
我们可以看到我们的数字是4次,4次是2次,只有3次。
我希望得到以下结果:
array(4,4,2,4,2,1,4)
如您所见:每个单元格都被其元素的计数所取代。
我怎样才能以最有效的方式做到这一点?
答案 0 :(得分:3)
vectorized
方法
# 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())]
示例运行 -
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]
答案 1 :(得分:0)
from collections import Counter
ctr = Counter(a.flat)
result = np.array([ctr[i] for i in a.flat])
如果您希望result
与a
具有相同的尺寸,请使用reshape
:
result = result.reshape(a.shape)
答案 2 :(得分:0)
我试图将numpy和Counter结合起来:
from collections import Counter
a=np.array([[1,1,4,1,4,3,1]])
# First I count the occurence of every element and stor eit in the dict-like counter
# Then I take its get-method and vectorize it for numpy-array usage
vectorized_counter = np.vectorize(Counter(a.flatten()).get)
vectorized_counter(a)
输出:
array([[4, 4, 2, 4, 2, 1, 4]])