python - 来自外部集的 numpy 计数出现次数
问题描述
我想计算集合中每个元素出现在 ndarray 中的数量。前任:
set = {1, 2, 3}
a = np.array([1, 1, 3, 1, 3])
res = {1:3, 2:0, 3:2}
似乎np.unique
没有提供“基本”元素集的选项。最快的方法是什么?
解决方案
这是一种方法np.unique
和np.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]))
推荐阅读
- java - AWS Kafka (MSK) - 如何生成 Keystore 和 truststore 并在我的 Spring Cloud Stream 应用程序中使用它们?
- python - Python 代码无法在任务调度程序中运行
- angular - Angular - ngAfterViewChecked 执行代码但只执行一次
- node.js - 使用邮递员将数据插入数据库时,在控制器文件中显示错误
- react-native - 使水平行的垂直滚动视图反应原生
- mysql - 如何先返回特定行,然后在 MySQL 中随机化其余行?
- spring - Spring Boot 仅适用于微服务吗?我可以将 Spring Boot 用于单体架构吗?
- javascript - 如何以“星期六,dd.MM.YYYY”的格式获取一年中的所有星期六?
- javascript - 队列管理系统(Laravel 6)的实时更新通知声音
- python - 如何使用另一个 Python 返回一个变量