如何使用numpy python计算元素向量的数量 [英] How to count num of elements vector with numpy python

查看:67
本文介绍了如何使用numpy python计算元素向量的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我有:

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

我们可以看到数字 1 出现了四次,数字 4 出现了两次,只有 3 个.

We can see that we have the number 1 four times, the number 4 twice and 3 only ones.

我想得到以下结果:

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

如您所见:每个单元格都替换为其元素的计数.

As you can see: each cell is replaced by the count of it's element.

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

How can i do it in the best efficient way?

推荐答案

一种 vectorized 方法和 np.uniquenp.searchsorted -

One vectorized approach with np.unique and 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())]

样品运行 -

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 -

As per the comments from @Jaime, you can use np.unique alone like so -

_, inv_idx, counts = np.unique(a, return_inverse=True, return_counts=True)
out = counts[inv_idx]

这篇关于如何使用numpy python计算元素向量的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆