简体   繁体   English

用 Numpy 计算一系列元素

[英]count a range of elements with Numpy

np.unique([1, 3, 0, 3, 1, 1], return_counts=True)

returns返回

(array([0, 1, 3]), array([1, 3, 2]))

which excludes missing elements, in this case, 2 .它排除了缺失的元素,在本例中为2

Is there an easy and efficient way to get all counts, for example:是否有一种简单有效的方法来获取所有计数,例如:

count(ar=[1, 3, 0, 3, 1, 1], from=0, to=4) # returns [1, 3, 0, 2]

? ?

You could use np.bincount , passing it a minlength of the maximum value in the array plus 1:您可以使用np.bincount ,将数组中最大值的minlength加 1 传递给它:

ar = np.array([1, 3, 0, 3, 1, 1])
np.bincount(ar, minlength=np.amax(ar)+1)
# array([1, 3, 0, 2], dtype=int64)

You could use np.add.at :您可以使用np.add.at

ar = np.array([1, 3, 0, 3, 1, 1])
count = np.zeros(np.amax(ar)+1)
np.add.at(count, ar, 1)

Output in count : Output count

array([1., 3., 0., 2.])

But using np.bincount will be much faster但是使用np.bincount会快得多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM